我有两张桌子,一张是用户,另一张是员工
用户:
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>
员工:
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>
登录后,我正在提取用户表
User user = userService.getCredentials(sessionDetails.getLoginUserName());
Employee employee = user.getEmployee();
DaoImpl代码:
@Transactional
public User getCredentials(String userName) {
Criteria cr = getSession().createCriteria(User.class);
cr.add(Restrictions.eq("userName", userName));
return (User) cr.uniqueResult();
}
为了验证,我尝试了System.out.println(employee.getId());
,但它返回了null。事实上,不是直接为null,因为空指针异常意味着它是空的。我尝试更改了获取类型,但我无法获得员工对象。为了进一步验证我至少获取用户对象,我在sysout user.getId();
昨天我在hibernate注释中使用了所有映射而不是hbm.xml。那时我已经为用户和员工提供了@ One-to-One注释,并且它正在成功运行。但今天我已将所有内容更改为hbm.xml,并且出现问题。