[英]Performing a Hibernate Join on two tables with a One to Many Association
我基本上有一個數據庫,其中有兩個具有以下模式的表:
Employee
|id|Age|Sex|
Table
|Table_id|Emp_id|Location|
我的employee.hbm.xml文件如下所示:
<property name="id"
type="integer"
column="emp_id" />
<property name="age"
type="integer"
column="age" />
<property name="sex"
type="string"
column="sex" />
我的table.hbm.xml文件如下所示:
<property name="table_id"
type="integer"
column="table_id" />
<property name="emp_id"
type="integer"
column="emp_id" />
<property name="location"
type="string"
column="location" />
我有必要的類與映射,即getter和setter方法。 他們看着像是:
public class EmployeeModel {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="id", referencedColumnName="emp_id")
private int id;
private int age;
private String sex;
//Getters and setters for all the variables
public class TableModel {
@OneToMany(mappedBy="EmployeeModel")
private int table_id;
private int emp_id;
private String location;
private int table_id;
private int emp_Id;
private String location;
//Getters and setters for all the variables
為了收集返回數據,我創建了一個名為EmployeeTableModel的新類,它看起來像:
public class EmployeeTableModel{
private int table_id;
private int emp_id;
private String location;
private int table_id;
private int emp_Id;
private String location;
}
如您所知,我基本上需要打個電話,向我提供該員工及其所在的桌子的詳細信息。它們之間存在一對一的關聯。 我了解我的代碼具有多對一的關聯,請對此進行糾正。 目前,我的查詢是:
List<EmployeeTableModel> data = sess.createCriteria(EmployeeModel.class)
.setFetchMode("TableModel", FetchMode.JOIN)
.add(Restrictions.eq("emp_id", "ANY INPUT" )).list();
我希望它能給我一個類似的查詢:
select e.id,e.age,e.sex,t.table_id,t.emp_id,t.location from employee e, table t;
但是,它給了我:
select e.id,e.age,e.sex from employee e;
我在表中添加了一個Employee變量,我更正了查詢,使用了HQL,但是我仍然無法弄清楚出了什么問題。 有人可以告訴我這是怎么回事嗎? 或給出替代答案?
使用JPA / Hibernate時,請盡可能避免在各列中進行思考。 考慮實體,讓框架進行更改。
您的查詢僅請求EmployeeModel
的列表,因為您這樣做
sess.createCriteria(EmployeeModel.class)
這就是您得到的(嘗試將其強制轉換為List<EmployeeTableModel>
的事實可能會導致編譯時警告和運行時錯誤。
順便說一句,談論實體時,您的模型似乎被誤導了。 您的屬性應該是實體(而不是外鍵); 代替
private int table_id;
private int emp_id;
private String location;
你做
private int table_id;
private Employee employee;
private String location;
注釋似乎也位於錯誤的位置,並且您沒有定義ID。我建議您再次閱讀Hibernate文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.