I've two tables, one is User and another one is Employee
User:
public class User {
private int id;
private String userName;
private String password;
private Employee employee;
// Getter and setter
}
User.hbm.xml:
<hibernate-mapping>
<class name="com.site.dto.User" table="user">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="userName" type="string">
<column name="user_name" length="50" not-null="true" unique="true" />
</property>
<property name="password" type="string">
<column name="password" length="50" not-null="true" unique="true" />
</property>
<one-to-one name="employee" class="com.site.dto.Employee" fetch="join" cascade="all"/>
</class>
</hibernate-mapping>
Employee:
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String name;
private User user;
// Getter and setter
}
Employee.hbm.xml:
<hibernate-mapping>
<class name="com.site.dto.Employee" table="employee">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="name" type="string">
<column name="name" length="50" not-null="true" unique="true" />
</property>
// I'm enforcing the many-to-one to one-to-one by adding unique="true"
<many-to-one name="user" column="user_id" class="com.site.dto.User" not-null="true" unique="true" fetch="join" cascade="all"/>
</class>
</hibernate-mapping>
Now after logging in, I'm fetching the User table
User user = userService.getCredentials(sessionDetails.getLoginUserName());
Employee employee = user.getEmployee();
DaoImpl code:
@Transactional
public User getCredentials(String userName) {
Criteria cr = getSession().createCriteria(User.class);
cr.add(Restrictions.eq("userName", userName));
return (User) cr.uniqueResult();
}
For verification, I tried System.out.println(employee.getId());
, but it was returning null. Infact, not directly as null, as Null Pointer exception which means it's null. I tried changing the fetch types, but I can't get the employee object. To verify further I'm atleast getting the user object, I get the expected user Id when sysout user.getId();
Yesterday I was having all the mapping in hibernate annotation instead of hbm.xml. At that time I've put @One-to-One annotation for both User and Employee and it was working successfully. But today I've changed everything to hbm.xml, and the problem occurs.