本文介绍了如何只从多对多映射表加载ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 在两张表之间的多对多关系中,我怎样才能为第二个实体加载id。 以下是示例解释我想在这里实现的目标。 下面是一个示例模式 create table user( id int PrimaryKey, name文本)创建表页( id int PrimaryKey, page_name text )创建表user_page( id_user int, id_page int, PrimaryKey(id_user,id_page)) :在用户和页面表格中还有其他列,我没有在这里简单列出。 用户实体: @Entity @Table(name =user) public class User { @id @column(name = ID)私人整数ID; @column(name =name)私人字符串名称; ... ... } @Entity @Table(name =page) public class Page { @id @column(name =id)私人整数ID; @column(name =page_name)私人字符串名称; ... ... } 想要做的是添加另一个属性 Set< Integer> User 类中的pageIds ,并为此集合中的用户映射所有页面id。 在 User class: @ManyToMany @JoinTable( name =user_page, joinColumns = @JoinColumn(name =id_user), inverseJoinColumns = @JoinColumn(name =id_page)) public Set< Page>页; 您可以遍历返回的集合来获取id。默认情况下,收藏是懒惰(即只有ids)加载。 编辑:如果您不想映射 Page 由于某种原因,您可以使用 @ElementCollection ,例如: @ElementCollection @CollectionTable(name =user_page,joinColumns = @ JoinColumn(name =id_user)) @Column(name =id_page) public Set< Long> pageIds; In a Many to Many relation between two table with a Mapping table in between, how can I only load ids for the second entity.Following is the example to explain what I want to achieve here.Below is a sample schemacreate table user( id int PrimaryKey, name text)create table pages ( id int PrimaryKey, page_name text)create table user_page ( id_user int, id_page int, PrimaryKey (id_user, id_page))Note: there are additional columns in user and page tables which i have not included here for brevity.User entity:@Entity@Table(name = "user")public class User { @id @column(name="id") private Integer id; @column(name="name") private String name; ... ...}@Entity@Table(name = "page")public class Page { @id @column(name="id") private Integer id; @column(name="page_name") private String name; ... ...}What I want to do is add another attribute Set<Integer> pageIds in User class and have all page ids mapped for a user in this collection.How can this be done using Hibernate? 解决方案 In User class:@ManyToMany@JoinTable( name="user_page", joinColumns = @JoinColumn(name="id_user"), inverseJoinColumns = @JoinColumn(name="id_page"))public Set<Page> pages;You can get the id's by iterating over the returned set. By default collections are lazily (i.e. only ids) loaded.EDIT: If you don't want to map Page for some reason, you can use @ElementCollection like this:@ElementCollection@CollectionTable(name="user_page", joinColumns=@JoinColumn(name="id_user"))@Column(name="id_page")public Set<Long> pageIds; 这篇关于如何只从多对多映射表加载ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-21 04:44