jpa使用WHERE子句

时间:2011-02-11 09:40:33

标签: jpa one-to-many

我有两个实体:

@Entity
public class Elements implements Serializable {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;

   private Owner owner;

}

@Entity
public class Owner implements Serializable {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;

   @OneToMany(fetch=FetchType.LAZY)
   List<Elements> elements;
}

假设我想从Elements Table中获取所有的elemets,然后使用:

TypedQuery query=em.createQuery("SELECT elem FROM Elements elem WHERE 
                       elem.owner:=elemOwner", Elements.class);

query.setParameter("elemOwner", ownerObjectFetchFromDataBase);

List<TrendUsers> userList=query.getResultList();

但是我收到以下错误:  不支持“BLOB”和“BLOB”之间的比较。类型必须具有可比性。字符串类型还必须具有匹配的排序规则。 如果排序规则不匹配,可能的解决方案是转换操作数以强制它们进入默认排序规则...

有什么方法可以从Elements Table和WHERE子句中选择使用对象(而不仅仅是String,int ......)?

(p.s我也尝试了下面的查询,它不起作用:  TypedQuery query = em.createQuery(“SELECT elem FROM Elements elem WHERE elem.owner.id:=elemOwner”,Elements.class);  query.setParameter(“elemOwner”,ownerObjectFetchFromDataBase.id);  列出userList = query.getResultList();  )

由于

1 个答案:

答案 0 :(得分:3)

您需要将所有者标记为ManyToOne

@Entity public class Elements implements Serializable {
   ...snip ...
   @ManyToOne(fetch=FetchType.LAZY)
   @JoinColumn(name="OWNER_ID")
   private Owner owner;
}

@Entity public class Owner implements Serializable {
   .. snip ...
   @OneToMany(fetch=FetchType.LAZY, mappedBy="owner")
   List<Elements> elements;
}

现在您尝试将序列化所有者存储在Blob中。那不是你想要的; - )

享受

编辑:包含xatavt修复