我有两个实体:具有多对多关系的项目和角色。我尝试使用Criteria API选择包含特定角色的项目,但我的代码不起作用。我使用Hibernate和Spring-boot。我没有使用Metamodel。
以下是我的实体: 项目:
@Entity
public class Project
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Column
private String name;
@ManyToMany
@JoinTable(joinColumns = @JoinColumn(name = "project_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private List<Role> roles;
//Constructors getters and setters omitted
}
作用:
@Entity
public class Role
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Column
private String name;
//constructors getters and setters omitted
}
这里是查询:
public List<Project> findByRole(Role role)
{
Session session = sessionFactory.openSession();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Project> criteria = builder.createQuery(Project.class);
Root<Project> root = criteria.from(Project.class);
Path<List<Role>> roles = root.get("roles");
Expression<Role> roleParameter = builder.parameter(Role.class, "role");
criteria.select(root).where(roleParameter.in(roles));
TypedQuery<Project> query = session.createQuery(criteria)
.setParameter("role", role);
List<Project> projects = query.getResultList();
return projects;
}
无论数据库中包含哪种数据,此查询都返回null。我显然做错了什么,但我对Criteria API很新,我无法理解它。我很感激你的帮助。