如何基于成员对象的字段值而不是成员对象ID获取实体

时间:2018-10-10 14:50:22

标签: java hibernate orm hibernate-mapping hibernate-criteria

我有三个类,相同的代码显示在下面

查询类别

@Entity
public class Enquiry 
{
  @Id
  @GeneratedValue
  private int id;

  private String name;

  private String discription;

  private int status;

  @Temporal(TemporalType.DATE)
  private Date enquiryDate;
}

用户类别

 @Entity
 public class User 
 {
   @Id
   @GeneratedValue
   private int id;

   private String name;

   private String userId;

   private String password;
 }

UserEnquiryUserEnquiryMapping类

@Entity
public class UserEnquiryMapping 
{
   @Id
   @GeneratedValue
   private int id;

   @ManyToOne
   private User user;

   @ManyToOne
   private Enquiry enquiry;
}

现在假设,如果我们想为特定的Enquiry(s)获取User,那么我们可以通过传递User对象来轻松获取它,并且休眠将使用id生成查询User对象中的“字段”,以及下面提到的用于同一场景的代码。

EntityManager entityManager = session.getEntityManagerFactory().createEntityManager();
CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<UserEnquiryMapping> criteria = builder.createQuery(UserEnquiryMapping.class);
Root<UserEnquiryMapping> root = criteria.from(UserEnquiryMapping.class);
criteria.select(root);
criteria.where(builder.equal(root.get("user"), user));

userEnquiries = entityManager.createQuery(criteria).getResultList();

但是我的要求是我想根据用户名获取用户查询,或者可以说我想生成这样的查询

 Select * from UserEnquiryMapping inner join Enquiry on UserEnquiryMapping.Enquiry_ID = Enquiry.ID inner join User on UserEnquiryMapping.User_ID = User.ID where User.name="Test";

我该怎么做?

1 个答案:

答案 0 :(得分:0)

ListenerA

很高兴能为您提供帮助!