[英]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.