簡體   English   中英

Hibernate 標准一對多問題

[英]Hibernate Criteria One to Many issues

我正在嘗試使用 Hibernate Criteria api 僅獲取基於USER_ID的主題,但不知道如何使用標准來執行此操作。

我的表是“topic_users”(如下)

在此處輸入圖片說明

和“主題”表(如下)

在此處輸入圖片說明

我知道如何使用 SQL 做到這一點,這將是這樣的:

SELECT TOPICNAME 
FROM topic_users INNER JOIN topics on topic_users.TOPICS_TOPICS_ID = topics.TOPICS_ID 
WHERE topic_users.USER_ID = 1

這將返回USER_ID 1 的所有TOPICNAME ,這正是我想要的,但是我如何使用 Hibernate Criteria 做到這一點。 到目前為止,我的 Repository 類中有這個(見下文),但這只會返回一個高度嵌套的 JSON 數組。 我可以遍歷對象,使用 DTO 並構建我的響應或嘗試 Hibernate createSQLQuery方法,該方法將讓我直接調用本機 SQL 語句(尚未嘗試過)...但我正在嘗試學習標准我希望任何人都可以回答我的問題。

@Repository("userTopicsDao")
public class UserTopicsDaoImpl extends AbstractDao<Integer, UserTopics>implements UserTopicsDao {

    @Override
    public List<UserTopics> findMyTopics(int userId) {
        Criteria crit = createEntityCriteria();
        crit.add(Restrictions.eq("userId", userId));
        List<UserTopics> userTopicsList = (List<UserTopics>)crit.list();
        return userTopicsList;
    }

和我的TOPIC_USERS實體,我在其中映射了TOPICS

@Entity
@Table(name="TOPIC_USERS")
public class UserTopics {

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

    @Column(name="USER_ID")
    private Integer userId;

    @OneToMany(fetch = FetchType.EAGER)
    @JoinColumn(name = "TOPICS_ID")
    private Set<Topics> topicsUser;

   //getter and setters

好的,從頭開始……你的實體類應該是這樣的:

@Entity
@Table(name="TOPIC_USERS")
public class UserTopics {

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

    @Column(name="USER_ID")
    private Integer userId;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "TOPICS_TOPICS_ID")
    private Topics topics;

您的 Topics 類應如下所示:

@Entity
@Table(name="TOPICS")
public class Topic {

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

    @Column(name="TOPICNAME")
    private Integer topicName;

    @OneToMany(mappedBy = "topics")
    private Set<UserTopics> userTopics;

最后是標准:

版本 1)你得到整個實體:

Criteria c = session.createCriteria(Topics.class, "topics");
c.createAlias("topics.userTopics", "userTopics");
c.add(Restrictions.eq("userTopics.userId", userId));
return c.list(); // here you return List<Topics>

版本 2)您只投影主題名稱:

Criteria c = session.createCriteria(Topics.class, "topics");
c.createAlias("topics.userTopics", "userTopics");
c.add(Restrictions.eq("userTopics.userId", userId));
c.setProjection(Projections.property("topics.topicName"));
List<Object[]> results =  (List<Object[]>)c.list(); 

// Here you have to manually get the topicname from Object[] table.

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM