休眠标准一对多问题
我正在尝试使用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语句(还没有尝试过)......但我正在尝试学习Criteria我希望任何人都可以回答我的问题。
@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;
}
和我已经映射TOPICS
TOPIC_USERS
实体
@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;
您的主题类应如下所示:
@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)您只投影topicname:
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.
}
链接地址: http://www.djcxy.com/p/37085.html上一篇: Hibernate Criteria One to Many issues
下一篇: How to query two SQL tables with the same structure using criteria api?