gpt4 book ai didi

java - 如何根据成员对象的字段值而不是成员对象ID获取实体

转载 作者:太空宇宙 更新时间:2023-11-04 10:07:42 27 4
gpt4 key购买 nike

我有三个类,其代码显示在下面

查询类:

@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;
}

现在假设我们想要获取特定UserEnquiry(s),那么我们可以通过传递User对象轻松获取它,并且hibernate将使用User对象中的id字段生成查询,下面提到相同场景的代码。

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

我该怎么做?

最佳答案

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

很高兴能帮到你!

关于java - 如何根据成员对象的字段值而不是成员对象ID获取实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52743005/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com