如何将SQL查询更改为HQL或Criteria?

时间:2014-12-23 17:33:06

标签: hibernate hql criteria

我有以下表格....

@Entity
@Table
public class Emp_PersonalDetails {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="EMPID")
private int id;
private String firstName;
private String middleName;
private String lastName;
private String driversLicenseNo;
private String passportNo;
@Column(columnDefinition="DATE")
private Date pportLicenseExp;
private String gender;;
private String nationality;
private String maritalStatus;
@Column(columnDefinition="DATE")
private Date dob;
@Column(columnDefinition="mediumblob")
byte[] image;
@OneToOne(mappedBy = "details", cascade = CascadeType.ALL)  
private Emp_JobDetails jobDetails;
@OneToOne(mappedBy = "details", cascade = CascadeType.ALL)  
private Emp_Reporting reportingDetails;

\ contrutor + getters& setter方法

和另一个......

@Entity
@Table
public class Emp_JobDetails {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "EJDID")
private int id;
private String jobTitle;
private String department;
private String status;
private String category;
private Date startDate;
private Date endDate;
private String location;
private Date joinedDate;
@Column(length=1000)
private String otherDetails;
@OneToOne
private Emp_PersonalDetails details;

\ contrutor + getters&制定者 最后......

@Entity
@Table
public class Emp_Reporting {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "RDID")
private int id;
private String manager;
private String reportingMethod;
private Date prDate;
private Date nextPrDate;
private String level;
@Column(length=1000)
private String comments;
@OneToOne

// @PrimaryKeyJoinColumn     私人Emp_PersonalDetails详细信息;

这里的SQL查询工作正常,但是太长了。如何将其更改为基于HQL或基于条件的查询?感谢

SELECT EMPP.empid, EMPP.firstName, EMPP.middleName, EMPP.lastName, EMPJ.jobTitle, 
       EMPJ.status, EMPJ.department, EMPR.manager 
FROM   Emp_PersonalDetails EMPP 
JOIN   Emp_JobDetails EMPJ 
ON     EMPP.EMPID = EMPJ.EJDID 
JOIN   Emp_Reporting EMPR 
ON     EMPP.EMPID = EMPR.RDID 
WHERE  EMPP.firstName LIKE :name 
OR     EMPP.empid LIKE:id

1 个答案:

答案 0 :(得分:0)

我会从Emp_Reporting表中选择:)

SELECT EMPP.empid, [ommited for formatting ...] 
FROM Emp_Reporting EMPR 
         inner join EMPR.details EMPP
         inner join EMPP.jobDetails EMPJ 
WHERE EMPP.firstName LIKE :name OR EMPP.id= :id

ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("EMPP.id"));
projectionList.add(Projections.property("EMPP.firstName"));
projectionList.add(Projections.property("..."));
Criteria criteria = createCriteria(Emp_Reporting.class,"EMPR")
        .createAlias("details","EMPP")
        .createAlias("EMPP.jobDetails","EMPJ")
        .setProjection(projectionList)
        .add(Restrictions.eq("EMPP.firstName", value))
        .add(Restrictions.eq("EMPP.id", value));