Hibernate JPQL连接获取(如果不为null)
有两个实体:职位和员工 目标是让一名员工有职位或没有职位。 如果某个职位存在,则此查询有效,但如果不存在,则将抛出错误 如果员工有或没有职位,如何更改此查询以接收该员工Hibernate JPQL连接获取(如果不为null),hibernate,jpa,jpql,Hibernate,Jpa,Jpql,有两个实体:职位和员工 目标是让一名员工有职位或没有职位。 如果某个职位存在,则此查询有效,但如果不存在,则将抛出错误 如果员工有或没有职位,如何更改此查询以接收该员工 public Employee getEmployee(Long id) { EntityManager em = entityManagerFactory.createEntityManager(); em.getTransaction().begin(); Employee employee;
public Employee getEmployee(Long id) {
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
Employee employee;
try {
employee = em.createQuery("select e " +
"from Employee e " +
"join fetch e.position p " +
"where e.employeeId= :id)", Employee.class)
.setParameter("id", id)
.getSingleResult();
em.getTransaction().commit();
} catch (NoResultException ex){
throw new RuntimeException("MAMA mia");
}
return employee;
}
@Entity
@Table(name = "position")
public class Position {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "POSITION_ID", updatable = false)
private Long id;
@Column(name = "NAME")
private String name;
@JoinTable(name = "Position_Employee_JT")
@OneToMany(fetch = LAZY, cascade = ALL)
private Set<Employee employeeSet = new HashSet<();
}
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "EMPLOYEE_ID", updatable = false)
private Long employeeId;
@ManyToOne(fetch = LAZY)
private Position position;
}
public Employee getEmployee(长id){
EntityManager em=EntityManager工厂。createEntityManager();
em.getTransaction().begin();
员工;
试一试{
employee=em.createQuery(“选择e”+
“来自员工e”+
“加入获取e.p位置”+
“其中e.employeeId=:id)”,Employee.class)
.setParameter(“id”,id)
.getSingleResult();
em.getTransaction().commit();
}捕获(noresultex异常){
抛出新的运行时异常(“MAMA mia”);
}
返回员工;
}
@实体
@表(name=“position”)
公共阶级地位{
@身份证
@GeneratedValue(策略=GenerationType.IDENTITY)
@列(name=“POSITION\u ID”,updateable=false)
私人长id;
@列(name=“name”)
私有字符串名称;
@JoinTable(name=“Position\u Employee\u JT”)
@OneToMany(fetch=LAZY,cascade=ALL)
私有集找到了解决方案。
如果您使用fetchlazy,代理将为您工作
Spring数据将不起作用并引发错误:
可选employee=repository.findById(id)
它很好用
public Employee getEmployee(Long id) {
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
Employee employee = em.find(Employee.class,id);
em.getTransaction().commit();
return employee;
}
解释如下:
这是因为您使用了内部联接。请使用左联接,如下所示:
employee = em.createQuery("select e " +
"from Employee e " +
"left join fetch e.position p " +
"where e.employeeId= :id)", Employee.class)
.setParameter("id", id)
.getSingleResult();
为什么需要fetch.LAZY和cascade.ALL?您将它们放在了奇怪的位置,这表明您并不真正了解它们在做什么。重新评估它们是一个好的开始。