无法使用带有@OneToMany的 JPA @NativeQuery进行获取。JPA 联接查询在本机查询之后执行



我正在尝试使用本机查询获取数据。但是下面的查询执行。

原生查询:Hibernate: select * from employee emp inner join department dep on emp.id = dep.dp_id where emp.id=? and dep.department=?

Hibernate: select department0_.dp_id as dp_id3_0_0_, department0_.d_id as d_id1_0_0_, department0_.d_id as d_id1_0_1_, department0_.department as departme2_0_1_ from department department0_ where department0_.dp_id=?

如何停止执行第二个查询?

@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;

private String name;
@OneToMany
@JoinColumn(name = "dp_id")
private List<Department> departments;
...
}
@Entity
@Table(name = "department")
public class Department {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long dId;

private String department;

...
}

请让我知道如何只执行本机查询?

尝试将关联更改为

@OneToMany(fetch = FetchType.LAZY)

User User = (User) session.createQuery("FROM User U WHERE U. userName =:userName".setParameter("userName", userName)

.uniqueResult ();在hibernate中,您将编写像这样的本机查询

显然您正在访问departments集合,但正如您在第一个查询中看到的那样,该集合的内容最初没有加载。要么避免访问集合以避免触发延迟加载,要么在原始查询中获取集合。要么使用实体图,要么使用连接抓取。对于连接抓取,您可以使用这样的查询:select e from Employee e join fetch e.departments where e.id = :id

相关内容

  • 没有找到相关文章

最新更新