【问题标题】:hibernate query with join带有连接的休眠查询
【发布时间】:2018-05-07 10:17:02
【问题描述】:

我有两个实体如下:

@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();

写出正确的查询吗?

谢谢, 阿什利

【问题讨论】:

  • 我觉得这段关系有点模糊。多个员工可以有一个TaxReturn 吗??
  • 看起来您想检索Employee #4 以及根本没有TaxReturn 信息。所以,FROM Employee e WHERE e.id = 4
  • 能否用简单句(不涉及技术内容)的查询说明您要解决的业务
  • 因为是雇主为其雇员提交纳税申报表,所以是的,多个雇员可以属于一个纳税申报表。但我不想让这种关系成为双向的。
  • @ShafinMahmud 我需要能够检索特定回报的员工

标签: java spring hibernate


【解决方案1】:

查询应该是:

select p.employees from TaxReturn p left join p.employees e where p.id = '5' and e.id = '4'

注意连接部分与您的不同,因为您必须在连接时指定映射关系的字段。

您也可以只返回一个TaxReturn,然后从那里获得EmployeeList

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();

我还注意到您以非常规的方式将关系映射为 通常单向映射在ManyToOne 一侧完成,而不是相反。还有一些与性能相关的问题,请查看Article了解更多详情

【讨论】:

    猜你喜欢
    • 2013-01-19
    • 2012-11-08
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    相关资源
    最近更新 更多