我有两个实体,即:
状态
@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 查询检索它,但我似乎找不到解决方案
如何使用 CriteriaBuilder
、CriteriaQuery
和 Root
在 Hibernate 查询中编写此查询 SELECT InsurerId FROM State;
..
最佳答案
如果您想选择所有州的所有保险公司 ID:
String selectionQuery = "SELECT s.insurer.insurerId FROM State s";
List<String> insurersIds = session.createQuery(selectionQuery).list();
如果您想选择某个州的保险公司 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
编辑:
您应该按照普拉萨德在回答中所写的那样更新您的保险公司实体。
关于java - 如何在hibernate中查找外键的id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58321886/