Kim*_*m L 6 java hibernate jpa criteria criteria-api
我必须遵循实体对象
@Entity
public class Foobar {
...
private List<String> uuids;
...
}
现在我想制作一个条件查询来获取所有Foobar pojos,其uuids列表包含字符串"abc123",我只是不确定如何制定适当的标准.
我假设您使用的是实现JPA 2.0的Hibernate版本.这是一个JPA 2.0解决方案,可以与任何兼容的实现一起使用.
请uuids使用JPA的@ElementCollection注释进行注释.不要@CollectionOfElements像其他一些答案评论中提到的那样使用Hibernate .后者具有相同的功能,但已被弃用.
Foobar.java 看起来大致如下:
@Entity
public class Foobar implements Serializable {
// You might have some other id
@Id
private Long id;
@ElementCollection
private List<String> uuids;
// Getters/Setters, serialVersionUID, ...
}
Run Code Online (Sandbox Code Playgroud)
以下是如何构建一个CriteriaQuery选择包含"abc123"的所有Foobars的方法uuids.
public void getFoobars() {
{
EntityManager em = ... // EM by injection, EntityManagerFactory, whatever
CriteriaBuilder b = em.getCriteriaBuilder();
CriteriaQuery<Foobar> cq = b.createQuery(Foobar.class);
Root<Foobar> foobar = cq.from(Foobar.class);
TypedQuery<Foobar> q = em.createQuery(
cq.select(foobar)
.where(b.isMember("abc123", foobar.<List<String>>get("uuids"))));
for (Foobar f : q.getResultList()) {
// Do stuff with f, which will have "abc123" in uuids
}
}
Run Code Online (Sandbox Code Playgroud)
在玩这个游戏的过程中,我制作了一个独立的概念验证程序.我现在不能把它推出去.如果您希望将POC推送到github,请发表评论.
| 归档时间: |
|
| 查看次数: |
13942 次 |
| 最近记录: |