在Hibernate中加入3个实体

时间:2016-07-13 09:03:32

标签: java hibernate jpa entity

我有以下实体:

Person.java

@Table(name = persons)
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "UserID", nullable = false) 
    private Long userId;

    @Column(name = "Employeenumber", nullable = false) private String employeeNumber;
    @Column(name = "Firstname", nullable = false) private String firstName;
    @Column(name = "Lastname", nullable = false) private String lastName;

    public User() { }

    public User(String employeeNumber, String firstName, String lastName) {
        super();

        this.employeeNumber = employeeNumber;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    /*
        getter and setters

        ...
    */

}

Personhistory.java

@Entity
@Table(name = personhistory)
public class Personhistory {

    @Id
    @Column(name = "UserID", nullable = false) 
    private Long userId;

    @Column(name = "Fromdate", nullable = false) private Date fromDate;
    @Column(name = "Todate", nullable = false) private Date toDate;
    @Column(name = "TeamID", nullable = false) private Integer teamId;


    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "UnikId", nullable = false) 
    private Integer unikId;

    public Userhistory() {

    }


    public Userhistory(Long userId, Date fromDate, Date toDate, int teamId) {
        super();

        this.userId = userId;
        this.fromDate = fromDate;
        this.toDate = toDate;
        this.teamId = teamId;
    }

    /*
        Getters and setters

        ...
    */

}

Team.java

@Entity
@Table(name = "team")
public class Team {
    @Id
    @Column(name = "TeamID") 
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int teamId;

    @Column(name = "TeamNumber") private String teamNumber;

    public Team() {}

    public Team(String teamNumber) {
        super();
        this.teamNumber = teamNumber;
    }

    /*
        Getters and setters

        ...
    */

}

我想像这样进行API调用:

localhost:8080/users/{employee}

当他在队中以及那支队伍时,取回一个包含该人的对象(他的号码,名字和姓氏)。

如果我在MSSQL中编写此查询,它将如下所示:

select * from persons p

join personhistory ph on ph.UserID = p.UserID
    and ph.Fromdate <= cast(getdate() as date)
    and ph.Todate >= cast(getdate() as date)
join team t on t.TeamID = ph.TeamID

where u.Employeenumber = '999'

我一直在寻找不同的解决方案,如HQL,JPQL,Criteria等,但我无法使其发挥作用。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

AFAIK Hibernate 5.1提供了更多的通用连接,但是对于以前的版本,您必须使用交叉连接并在where子句中添加条件或提供实体之间的真实关系并加入该关系(使用“使用“其他连接条件的关键字”。

示例(请注意,为简单起见,我遗漏了许多注释):

class Person {      
  @OneToMany( mappedBy = "user" )
  Collection<Personhistory> history;

  ...
}

class Personhistory {
  @ManyToOne
  Person user;

  @ManyToOne
  Team team;

  ...
}

然后查询可能变为

select p, ph, t from Person p 
  join p.history ph with ph.fromdate <= :date and ph.toDate >= :date
  join ph.team t
  where p.employeeNumber = :number