我有两个实体如下:
@Entity
@Table(name = "tax")
public class TaxReturn {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "period")
private String fillingPeriod;
@Column(name = "created_date")
private LocalDateTime dateCreated;
@Column(name = "total_tax")
private int totalTax;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "tax_id", nullable = false)
private List<Employee> employees;
}
@Entity
@Table(name = "emp")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "other_name")
private String firstName;
@Column(name = "surname")
private String lastName;
@Column(name = "tax_amount")
private int taxAmount;
}
上述信息代表一份回报,其中包含一份员工名单,说明已缴纳多少税款。退货实体包含所有员工的总金额。我需要在HQL中编写一个查询,该查询将使用返回ID和员工ID检索员工。下面是我写的,但我收到一个错误,因为它没有生成正确的mysql。
session.getTransaction().begin();
Long taxReturnId = 5L;
Long empId = 4L;
Query query = session.createQuery("select p.employees from TaxReturn p left join Employee e where p.id = '5' and e.id = '4'");
List<Employee> employeeList = query.list();
System.out.println(employeeList.get(0).toString());
session.getTransaction().commit();
这是正确的查询吗?
谢谢, 阿什利
答案 0 :(得分:0)
查询应为:
select p.employees from TaxReturn p left join p.employees e where p.id = '5' and e.id = '4'
N.B。连接部分与您的不同,因为您必须在连接时指定映射关系的字段。
您也可以返回TaxReturn
并从那里获得List
的{{1}}:
Employee
另外,我注意到你以非传统的方式绘制了关系
通常单向映射在Query query = session.createQuery("select p from TaxReturn p left join p.employees e where p.id = '5' and e.id = '4'");
List<Employee> employeeList = query.singleResult().getEmployees();
侧完成,而不是相反。还有一些与性能相关的问题,请查看此Article了解更多详情