[英]how to find id of foreign key in hibernate
我有兩個實體,即:
State
@Entity
@Table(name = "State")
public class StateEntity {
@Column(name = "id", length = 36, nullable = false, unique = true)
private String id;
@ManyToOne (fetch = FetchType.LAZY)
@JoinColumn(name = "InsurerId", nullable = false)
private InsurerEntity insurer;
@Column(name ="StateName", length = 50, nullable = false)
private String stateName;
//getters and setters
}
保險公司
@Entity
@Table(name = "Insurer")
public class InsurerEntity {
@Column(name = "InsurerId", length = 36, nullable = false, unique = true)
private String insurerId;
@Column(name = "InsurerName", length = 100, nullable = true)
private String insurerName;
@OneToMany(mappedBy = "state", fetch = FetchType.LAZY)
private List<StateEntity> stateEntityList;
//getters and setters
}
保險公司的 id 保存在state數據庫中,我想使用 hibernate 查詢檢索它,但我似乎找不到解決方案
如何編寫此查詢SELECT InsurerId FROM State;
在 Hibernate 查詢中使用CriteriaBuilder
, CriteriaQuery
和Root
..
如果您想 select 所有州的所有保險公司 ID:
String selectionQuery = "SELECT s.insurer.insurerId FROM State s";
List<String> insurersIds = session.createQuery(selectionQuery).list();
如果您想 select 某個 state 的 Insurer's Id:
String selectionQuery = "SELECT s.insurer.insurerId FROM State s WHERE s.id = :stateId";
String insurerId = (String) session.createQuery(selectionQuery).setParameter("stateId", stateId).getSingleResult(); //This should be placed in a try/catch block to handle org.hibernate.NonUniqueResultException
編輯:
正如 Prasad 在他的回答中所寫,您應該更新您的 Insurer 實體。
為此,您還必須在 map 兩個 class 中將 @oneToMany 注釋放入 class InsurerEntity 中
@OneToMany(fetch = FetchType.LAZY,mappedBy="StateEntity", cascade = CascadeType.ALL)
private List< StateEntity > StateEntitys;
當您獲取狀態時,您還將在其中獲得 InsurerEntity 的 object ,您可以使用 getter 訪問它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.