gpt4 book ai didi

java - Hibernate 标准多选查询与连接

转载 作者:行者123 更新时间:2023-12-01 18:16:23 24 4
gpt4 key购买 nike

下面是我的实体类,我使用条件生成器检索该实体,但我只需要获取 idtitletags

问题.java

@Entity
@Table(name = "QUESTION_TITLE")
public class Question {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "title")
private String title;

@OneToOne(mappedBy = "question", cascade = CascadeType.ALL)
private Body body;

@ManyToMany
@JoinTable(name = "QUESTION_TAGS", joinColumns = @JoinColumn(name = "question_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "tag_id", referencedColumnName = "id"))
private Collection<Tags> tags;

@ManyToOne(targetEntity = Registration.class, fetch = FetchType.LAZY)
@JoinColumn(nullable = false, name = "user_id", referencedColumnName = "id")
private Registration registration;
}

下面是我要获取的代码。我不知道如何项目标签表。

javax.persistence.criteria.CriteriaQuery<Question> query = getCriteriaBuilder().createQuery(Question.class);
Root<Question> question = query.from(Question.class);
query.multiselect(question.get("id"), question.get("title"), question.get("tags"));
List<Question> questionList = entityManager.createQuery(query).getResultList();

最佳答案

您可以使用 tuple criteria query :

CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Tuple> criteria = builder.createTupleQuery();
Root<Question> root = criteria.from(Question.class);
Path<Long> qId = root.get("id");
Path<String> qTitle = root.get("title");
Join<Question, Tag> qTag = root.join("tags", JoinType.INNER);

criteria.multiselect(qId, qTitle, qTag);
List<Tuple> tuples = session.createQuery(criteria).getResultList();
for (Tuple tuple : tuples)
{
Long id = tuple.get(qId);
String title = tuple.get(qTitle);
Tag tag = tuple.get(qTag);
}

Another alternative选择多个值就是选择一个将“包裹”多个值的对象。对于这种方法,您应该声明一个包装类:

public class QuestionTag
{
private final Long id;
private final String title;
private final Tag tag;

public QuestionTag(Long id, String title, Tag tag)
{
this.id = id;
this.title = title;
this.tag = tag;
}

public Long getId()
{
return id;
}

public String getTitle()
{
return title;
}

public Tag getTag()
{
return tag;
}
}

然后在查询中使用它:

CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<QuestionTag> criteria = builder.createQuery(QuestionTag.class);
Root<Question> root = criteria.from(Question.class);
Path<Long> qId = root.get("id");
Path<String> qTitle = root.get("title");
Join<Question, Tag> qTag = root.join("tags", JoinType.INNER);
criteria.select(builder.construct(QuestionTag.class, qId, qTitle, qTag));

List<QuestionTag> wrappers = session.createQuery(criteria).getResultList();

关于java - Hibernate 标准多选查询与连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60356537/

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