我坚持使用JPA 2.0中的CriteriaBuilder构建动态查询.我的应用程序是Spring 3.0,基于Hibernate 3.6.0 JPA 2.0.其实我有两个实体,一个是taUser,另一个是taContact,在我的taUser类中有一个属性,与taContact有多对一关系我的pojo类是(示例)
public class TaUser implements java.io.Serializable {
private int userId;
private TaContact taContact;
public int getUserId() {
return this.userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public TaContact getTaContact() {
return taContact;
}
public void setTaContact(TaContact taContact) {
this.taContact = taContact;
}
}
public class TaContact implements java.io.Serializable {
private int contactId;
public int getContactId() {
return this.contactId;
}
public void setContactId(int contactId) {
this.contactId = contactId;
}
private int contactNumber;
public int getContactNumber() {
return contactNumber;
}
public void setContactNumber(int contactNumber) {
this.contactNumber = contactNumber;
}
}
和我的orm .xml
如何使用条件创建构建动态查询实际上这是我的jpql查询我想将其更改为使用标准构建动态查询.
String jpql =
"select * from Tauser user where user.userId = "1" and user.taContact.contactNumber="8971329902";
我怎样才能检查第二个条件?
user.taContact.contactNumber=”8971329902″
Rootcreatequery(TaUser.class);
rootEntity = criteriaQuery.from(TaUser.class);
criteriaQuery.where(criteriaBuilder.equal(rootEntity.get("userId"),"1"));
criteriaQuery.where(criteriaBuilder.equal(rootEntity.get("taContact.contactNumber"),"8971329902")); --- here i m getting error
at
org.hibernate.ejb.criteria.path.AbstractPathImpl.unkNownAttribute(AbstractPathImpl.java:110)
at org.hibernate.ejb.criteria.path.AbstractPathImpl.locateAttribute(AbstractPathImpl.java:218)
at org.hibernate.ejb.criteria.path.AbstractPathImpl.get(AbstractPathImpl.java:189)
at com.evolvus.core.common.dao.CommonDao.findByCriteria(CommonDao.java:155)
我该怎么解决这个问题?
最佳答案
有许多人在JPA EntityManagerFactory中使用该动态查询.
>如果您使用JPA Entity类和Use Hibernate 3 JPA注释,则可以使用@NamedQuery Annotation定义查询.
>您可以使用javax.persistence.Query来创建动态查询.
Query q1=em.createquery("SELECT TaUser AS tu WHERE tu.userId = :USERID");
//em is entityManager object
q1.setInteger("USERID",34);
//here 34 is the dynamic value or if there is any relationship with
// another entity then set the object reference of the other entity.
q1.getResultList(); //return list of data.
>您可以使用Hibernate Criteria API.
但问题是,如果你想创建标准,你需要初始化会话对象.因此,要获取会话对象使用您的实体管理器对象.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。