一尘不染

HQL休眠内连接

hibernate

如何在Hibernate中编写此SQL查询?我想使用Hibernate创建查询,而不是创建数据库。

SELECT * FROM Employee e INNER JOIN Team t ON e.Id_team=t.Id_team

我在SQLServer2008中创建了实体类,

@Entity
@Table(name="EMPLOYEE")
public class Employee
{
    @Id @GeneratedValue
    @Column(name="ID_EMPLOYEE")
    private int id_employee;
    @Column(name="SURNAME")
    private String surname;
    @Column(name="FIRSTNAME")
    private String firstname;
    @Column(name="ID_PROFESSION")
    private int id_profession;
    @Column(name="ID_BOSS")
    private int id_boss;
    @Column(name="HIRED_DATE")
    private Date hired;
    @Column(name="SALARY")
    private double salary;
    @Column(name="SALARY_ADD")
    private double salary_add;
    @Column(name="ID_TEAM")
    private int id_team;
    //setters and getters
}

@Entity
@Table(name="TEAM")
public class Team
{
    @Id @GeneratedValue
    @Column(name="ID_TEAM")
    private int id_team;
    @Column(name="TEAMNAME")
    private String teamname;
    @Column(name="ADDRESS")
    private String address;
    //setters and getters
}

我试图以多种方式构建有效的选择查询,但仍然无法正常工作。

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();                 
session.beginTransaction();
String select = "FROM Employee e INNER JOIN Team t ON e.Id_team=t.Id_team";
Query query = session.createQuery(select);
List elist = query.list();
session.getTransaction().commit();
session.close();

实体有问题吗?


阅读 233

收藏
2020-06-20

共1个答案

一尘不染

仅当实体之间存在关联时才能使用联接。您的Employee实体不应将名称为id_team,类型int为的字段映射到列。它应该与Team实体具有ManyToOne关联,并映射为JoinColumn:

@ManyToOne
@JoinColumn(name="ID_TEAM")
private Team team;

然后,以下查询将完美运行:

select e from Employee e inner join e.team

这将加载所有员工,除了那些与任何团队无关的员工。

当然,对于其他所有映射为实体的表的外键,其他字段也是如此(id_bossid_profession)。

现在是您阅读Hibernate文档的时候了,因为您错过了它的实质以及它的工作原理中非常重要的部分。

2020-06-20