简体   繁体   中英

How to get Entity based on member object's field value rather than member objects ID

I have three classes and code for the same is displayed below

Enquiry Class :

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

  private String name;

  private String discription;

  private int status;

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

User Class :

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

   private String name;

   private String userId;

   private String password;
 }

UserEnquiryUserEnquiryMapping Class :

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

   @ManyToOne
   private User user;

   @ManyToOne
   private Enquiry enquiry;
}

Now suppose if we want to get Enquiry(s) for a particular User than we can easily get it by passing a User object and hibernate will generate query by using id field from User object, and code for the same scenario is mentioned below.

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();

But my requirement is I want to get User enquiries on the basis of user's name or we can say that I want to generate query like this

 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";

How can I do this?

builder.equal(root.get("user").get("name"),user.getName()); 

很高兴能为您提供帮助!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM