Hibernate Criteria一对多问题

时间:2017-01-20 20:41:59

标签: java hibernate jpa hibernate-criteria criteria-api

我正在尝试使用Hibernate Criteria api来仅根据USER_ID获取主题,但不知道如何使用条件来执行此操作。

我的表格是“topic_users”(下方)

enter image description here

和“主题”表(下方)

enter image description here

我知道如何使用SQL,这将是:

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

这将返回TOPICNAME 1的所有USER_ID,这正是我想要的,但我如何使用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

1 个答案:

答案 0 :(得分:1)

好的从头开始..你的实体类应该是这样的:

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

您的话题类应如下所示:

@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.

}