我有两个实体部门和员工。部门有一份员工名单。员工有一个现场部门。我可以创建Employees并将它们添加到Department内的列表中。数据库表在persist上按预期填充。如果我查询部门,我会得到部门和员工名单。这一切都很好。如果我查询Employee并获取Department字段,则返回null。
@Entity
@Table(name = "DEPARTMENT")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "DPT_ID")
private long id;
@Column(name = "NAME", nullable = false, unique = true)
private String name;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "DEPARTMENT") //we need to duplicate the physical information
private List<Employee> employees = new ArrayList<>();
…
--
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "EMP_ID")
private long id;
@Column(name = "NAME", nullable = false)
private String name;
@Column(name = "DESIGNATION")
private String designation;
@ManyToOne
@JoinColumn(name = "DEPARTMENT", insertable = false, updatable = false)
private Department department;
...
--
employee.getDepartment()返回null的查询
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.getTransaction();
transaction.begin();
Department department = new Department();
department.setName("IT Department");
Employee employee1 = new Employee();
employee1.setName("Adam");
employee1.setDesignation("Manager");
Employee employee2 = new Employee();
employee2.setName("Miller");
employee2.setDesignation("Software Engineer");
Employee employee3 = new Employee();
employee3.setName("Smith");
employee3.setDesignation("Associate Engineer");
department.getEmployees().add(employee1);
department.getEmployees().add(employee2);
department.getEmployees().add(employee3);
session.persist(department);
session.flush();
transaction.commit();
transaction = session.getTransaction();
transaction.begin();
{
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Employee> query = builder.createQuery(Employee.class);
Root<Employee> root = query.from(Employee.class);
query.select(root);
Query<Employee> q = session.createQuery(query);
List<Employee> employees = q.getResultList();
for (Employee employee : employees) {
System.out.println("EMPLOYEE NAME: " + employee.getName());
System.out.println("DEPARTMENT NAME: " + employee.getDepartment()); // gives null
}
}
{
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Department> query = builder.createQuery(Department.class);
Root<Department> root = query.from(Department.class);
query.select(root);
Query<Department> q = session.createQuery(query);
List<Department> departments = q.getResultList();
for (Department deps : departments) {
System.out.println(deps.getName());
System.out.println(deps.getEmployees()); // list of employees is filled
}
}
表格似乎填写正确。但是如果我在查询的Employee上使用getDepartment,我会得到null。如果我在查询的部门使用getEmployees,我将获得所有员工。
我试过这里描述的两种方式:https://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html/ch07.html#collections-bidirectional
例7.21。双向一对多,多对一方作为协会所有者
和
例7.22。作为所有者的一对多方的双向关联
对我来说也是如此。
我错过了什么?
这是完整的测试项目:updated Project zip
已解决的固定项目:SOLVED PROBLEM PROJECT
看起来像Owning entity
问题,所以我认为你的测试是以两种不同的方式持久化数据。在您的注释@OneToMany(cascade = CascadeType.ALL)
中,您已声明Department
是该关系的所有者。所以,如果你坚持使用数据
dept.getEmployees().add(emp);
然后部门(id)字段将被更新
Hibernate: insert into EMPLOYEE (EMP_ID, DESIGNATION, NAME) values (null, ?, ?)
Hibernate: update EMPLOYEE set DEPARTMENT=? where EMP_ID=?
但如果坚持下去
emp.setDepartment(dept);
那么员工的部门(id)字段将不会更新。
Hibernate: insert into EMPLOYEE (EMP_ID, DESIGNATION, NAME) values (null, ?, ?)
如果员工的部门ID未持久存在,则无法检索部门。如果您将Employee作为关系的所有者,那么它会更有效,因为它具有外键。
@OneToMany(cascade = CascadeType.ALL, mappedBy="department")
private List<Employee> employees; // don't need to make a list, only for fetches
// and
@ManyToOne
@JoinColumn(name = "DEPARTMENT")
private Department department;
在坚持关系时设置员工的部门。然后使用departmentid完成插入,而不单独更新。
Hibernate: insert into EMPLOYEE (EMP_ID, DEPARTMENT, DESIGNATION, NAME) values (null, ?, ?, ?)
标准代码没有明显的错误,因为JPA将遵循带注释的关系,但它在两个单独的查询中这样做,因为您没有特定的连接。
Hibernate: select employee0_.EMP_ID as EMP_ID1_1_, employee0_.DEPARTMENT as DEPARTME4_1_, employee0_.DESIGNATION as DESIGNAT2_1_, employee0_.NAME as NAME3_1_ from EMPLOYEE employee0_
Hibernate: select department0_.DPT_ID as DPT_ID1_0_0_, department0_.NAME as NAME2_0_0_ from DEPARTMENT department0_ where department0_.DPT_ID=?
如果添加特定的Fetch,则它将在单个SQL语句中执行。
root.fetch("department");
和
Hibernate: select employee0_.EMP_ID as EMP_ID1_1_0_, department1_.DPT_ID as DPT_ID1_0_1_, employee0_.DEPARTMENT as DEPARTME4_1_0_, employee0_.DESIGNATION as DESIGNAT2_1_0_, employee0_.NAME as NAME3_1_0_, department1_.NAME as NAME2_0_1_ from EMPLOYEE employee0_ inner join DEPARTMENT department1_ on employee0_.DEPARTMENT=department1_.DPT_ID
在我看来,你的关系映射是不正确的!尝试更改这样的代码。
@ManyToOne
@JoinColumn(name = "DEPT_ID")
private Department department;
@OneToMany(mappedBy = "department",cascade = CascadeType.ALL)
private List<Employee> employees = new ArrayList<>();
尝试使用以下代码,只需将联接表从Employee指向Department。
@ManyToOne
@JoinColumn(name = "DPT_ID", insertable = false, updatable = false)
private Department department;
我发现了问题。我使用相同的会话进行持久化和查询。
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.getTransaction();
transaction.begin();
…
session.persist(stuff);
session.flush();
transaction.commit();
transaction = session.getTransaction();
transaction.begin();
query stuff
如果我在持续并打开一个新会话后关闭会话,一切正常。
我在我的问题中添加了一个固定版本的测试项目,以防有人感兴趣。