Hibernate:如何将多个连接表映射到 Java 个对象(用户的图书列表)
Hibernate: how to map several join tables to Java objects (user's list of books)
我有这个数据库结构。每年都有读书的用户,整理出他们读过的书单:
users years books----booklists
| | |
------------------------------------
|
userlists
我尝试自己做一些映射,但我认为我不正确。
users:
+-----------+---------+
| id | name |
+-----------+---------+
@Entity
public class User {
@Id @GeneratedValue
private int id;
//?
private List<UserList> booklists = new ArrayList<>();
}
每个用户都有一份他们在某一年读过的书籍的列表:
books:
+-----------+---------+
| id | title |
+-----------+---------+
@Entity
public class Book {
@Id @GeneratedValue
private int id;
}
每个用户的列表都在 booklists table:
中
booklists:
+-----+---------+---------+
| id | list_id | book_id |
+-----+---------+---------+
@Entity
public class BookList {
@Column(name="list_id")
private int id;
@JoinTable(
name = "books",
joinColumns = @JoinColumn(
name = "list_id",
referencedColumnName = "list_id"
),
inverseJoinColumns = @JoinColumn(
name = "book_id",
referencedColumnName = "id"
)
)
@OneToMany
private Collection<Book> books;
}
最终,书单和用户在 userlists:
中合并
years:
+----+------+
| id | year |
+----+------+
userlists:
+-----+---------+---------+---------+
| id | user_id | list_id | year_id |
+-----+---------+---------+---------+
@Entity
public class UserList {
@ManyToOne
@JoinColumn(name = "user_id")
private UserDao user;
@JoinTable(
name = "userlists",
joinColumns = @JoinColumn(
name = "id",
referencedColumnName = "id"
),
inverseJoinColumns = @JoinColumn(
name = "year_id",
referencedColumnName = "id"
)
)
@OneToOne
private String year;
//?
private BookList bookList;
}
我不确定如何在 User
中获取 private List<UserList> booklists = new ArrayList<>();
。我知道一对多可以这样映射:
@OneToMany
@JoinTable(joinColumns=@JoinColumn(name="user_id"),
inverseJoinColumns=@JoinColumn(name="list_id")
List<UserList> booklists = new ArrayList<>();
但我的情况 table 比我见过的任何教程都多。
编辑:有人向我指出,可以去掉 userlists
table 并放置有关 [=24= 的信息] 和 booklists
内的 year_id
。我仍然不完全确定如何正确映射它,因此感谢您的帮助。
好吧,这个特定问题有点独特,因为对于您定义的表,您有一个 list_id
但没有实体。 list_id
只是一种子键或标识列表的东西。正如您在上面的编辑中提到的那样,我会质疑表格的规范化,但首先是第一件事。
基本实体是 User
、Book
和 Year
个实体:
@Entity
@Table(name = "users")
@Data
public class User {
@Id
private int id;
private String name;
}
@Entity
@Table(name = "books")
@Data
public class Book {
@Id
private int id;
private String title;
}
@Entity
@Table(name = "years")
@Data
public class Year {
@Id
private int id;
private int year;
}
正如您所描述的,您可以创建一组 ListId
、Booklist
和 Userlist
关系表列表,因此:
@MappedSuperclass
@Data
@EqualsAndHashCode(of = "id")
public class ListId {
@Column(name="list_id")
private int listId;
@Id
private int id;
}
@Entity
@Table(name = "booklists")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class Booklist extends ListId {
@ManyToOne
private Book book;
}
@Entity
@Table(name = "userlists")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class Userlist extends ListId {
@ManyToOne
private User user;
@ManyToOne
private Year year;
}
肯定有其他方法可以做到这一点,但 none 将解决没有真正的 ListId
实体来建立 JPA 关系的问题。但是,您可以像这样使用此设置:
List<Booklist> bls = em.createQuery("select bl from Booklist bl left outer join Userlist ul on ul.listId = bl.listId where ul.user = :user", Booklist.class)
.setParameter("user", u1)
.getResultList();
bls.forEach(System.out::println);
这需要较新版本的 JPA,可能是 2.2 级别。至少它需要 Hibernate 5.1 或更高版本作为实现。如果要为此模式添加到 User
的双向映射,则:
@OneToMany(mappedBy = "user")
Set<Userlist> booklists;
然后像这样使用它。
List<Booklist> bls3 = em.createQuery("select bl from User u left outer join u.booklists ul left outer join Booklist bl on ul.listId = bl.listId where u = :user and ul.year = :year", Booklist.class)
.setParameter("user", u1)
.setParameter("year", y1)
.getResultList();
bls3.forEach(System.out::println);
假设您在按照工作所需的方式设计架构方面有一些回旋余地,那么是的,您应该更改它。
@Entity
@Table(name = "booklists")
@Data
@ToString(exclude = "user")
public class Booklist {
@Id
private int id;
@ManyToOne
private Book book;
@ManyToOne
private User user;
@ManyToOne
private Year year;
}
使用它更容易,并且不需要非相关实体从 JPA 2.2 或未映射的 ListId
class.
加入
List<Booklist> bls2 = em.createQuery("select bl from Booklist bl where bl.user = :user", Booklist.class)
.setParameter("user", u2)
.getResultList();
bls2.forEach(System.out::println);
您可以将双向映射添加到 User
。
@OneToMany(mappedBy = "user")
Set<Booklist> booklists;
并像这样使用它:
List<Booklist> bls3 = em.createQuery("select bl from User u left outer join u.booklists bl where u = :user and bl.year = :year", Booklist.class)
.setParameter("user", u1)
.setParameter("year", y1)
.getResultList();
bls3.forEach(System.out::println);
后面的架构为您提供与前一个架构相同的结果。如果不是这么晚,我会尝试找出您的第一个模式违反了前 3 个规范化级别中的哪一个,但也许这是 reader.
最好的练习
要求
跟踪 users
阅读的所有 books
,特别是 years
。
year
.
可能还有一些与程序相关的附加信息
数据模型
@Entity
@Table(name = "users")
@Data
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
}
@Entity
@Table(name = "books")
@Data
public class Book {
@Id
@GeneratedValue
private Long id;
private String isbn;
private String title;
}
@Entity
@Table(name = "years")
@Data
public class Year {
@Id
private Integer year;
}
@Entity
@Table(name = "book_lists",
uniqueConstraints = @UniqueConstraint(columnNames = {"user_id", "year"}))
@Data
public class BookList {
@Id
@GeneratedValue
private Long id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "year")
private Year year;
@ManyToMany
@JoinTable(name = "book_lists_books",
joinColumns = @JoinColumn(name = "book_list_id"),
inverseJoinColumns = @JoinColumn(name = "book_id"))
private Set<Book> books = new LinkedHashSet<>();
}
数据库模式 (PostgreSQL)
CREATE TABLE years
(
year integer NOT NULL,
PRIMARY KEY (year)
);
CREATE TABLE users
(
id bigint NOT NULL,
name character varying(255),
PRIMARY KEY (id)
);
CREATE TABLE books
(
id bigint NOT NULL,
isbn character varying(255),
title character varying(255),
PRIMARY KEY (id)
);
CREATE TABLE book_lists
(
id bigint NOT NULL,
user_id bigint,
year integer,
PRIMARY KEY (id),
FOREIGN KEY (year) REFERENCES years (year),
FOREIGN KEY (user_id) REFERENCES users (id),
UNIQUE (user_id, year)
);
CREATE TABLE book_lists_books
(
book_list_id bigint NOT NULL,
book_id bigint NOT NULL,
PRIMARY KEY (book_list_id, book_id),
FOREIGN KEY (book_id) REFERENCES books (id),
FOREIGN KEY (book_list_id) REFERENCES book_lists (id)
);
例子
User johnDoe = new User();
johnDoe.setName("John Doe");
em.persist(johnDoe);
Book poeaaBook = new Book();
poeaaBook.setIsbn("007-6092019909");
poeaaBook.setTitle("Patterns of Enterprise Application Architecture");
em.persist(poeaaBook);
Book eipBook = new Book();
eipBook.setIsbn("978-0321200686");
eipBook.setTitle("Enterprise Integration Patterns");
em.persist(eipBook);
Year year2019 = new Year();
year2019.setYear(2019);
BookList johnDoe2019BookList = new BookList();
johnDoe2019BookList.setUser(johnDoe);
johnDoe2019BookList.setYear(year2019);
johnDoe2019BookList.getBooks().add(poeaaBook);
johnDoe2019BookList.getBooks().add(eipBook);
em.persist(johnDoe2019BookList);
em.find(BookList.class, johnDoe2019BookList.getId())
returns
BookList(id=4, user=User(id=1, name=John Doe), year=Year(year=2019), books=[Book(id=2, isbn=007-6092019909, title=Patterns of Enterprise Application Architecture), Book(id=3, isbn=978-0321200686, title=Enterprise Integration Patterns)])
我有这个数据库结构。每年都有读书的用户,整理出他们读过的书单:
users years books----booklists
| | |
------------------------------------
|
userlists
我尝试自己做一些映射,但我认为我不正确。
users:
+-----------+---------+
| id | name |
+-----------+---------+
@Entity
public class User {
@Id @GeneratedValue
private int id;
//?
private List<UserList> booklists = new ArrayList<>();
}
每个用户都有一份他们在某一年读过的书籍的列表:
books:
+-----------+---------+
| id | title |
+-----------+---------+
@Entity
public class Book {
@Id @GeneratedValue
private int id;
}
每个用户的列表都在 booklists table:
中booklists:
+-----+---------+---------+
| id | list_id | book_id |
+-----+---------+---------+
@Entity
public class BookList {
@Column(name="list_id")
private int id;
@JoinTable(
name = "books",
joinColumns = @JoinColumn(
name = "list_id",
referencedColumnName = "list_id"
),
inverseJoinColumns = @JoinColumn(
name = "book_id",
referencedColumnName = "id"
)
)
@OneToMany
private Collection<Book> books;
}
最终,书单和用户在 userlists:
中合并years:
+----+------+
| id | year |
+----+------+
userlists:
+-----+---------+---------+---------+
| id | user_id | list_id | year_id |
+-----+---------+---------+---------+
@Entity
public class UserList {
@ManyToOne
@JoinColumn(name = "user_id")
private UserDao user;
@JoinTable(
name = "userlists",
joinColumns = @JoinColumn(
name = "id",
referencedColumnName = "id"
),
inverseJoinColumns = @JoinColumn(
name = "year_id",
referencedColumnName = "id"
)
)
@OneToOne
private String year;
//?
private BookList bookList;
}
我不确定如何在 User
中获取 private List<UserList> booklists = new ArrayList<>();
。我知道一对多可以这样映射:
@OneToMany
@JoinTable(joinColumns=@JoinColumn(name="user_id"),
inverseJoinColumns=@JoinColumn(name="list_id")
List<UserList> booklists = new ArrayList<>();
但我的情况 table 比我见过的任何教程都多。
编辑:有人向我指出,可以去掉 userlists
table 并放置有关 [=24= 的信息] 和 booklists
内的 year_id
。我仍然不完全确定如何正确映射它,因此感谢您的帮助。
好吧,这个特定问题有点独特,因为对于您定义的表,您有一个 list_id
但没有实体。 list_id
只是一种子键或标识列表的东西。正如您在上面的编辑中提到的那样,我会质疑表格的规范化,但首先是第一件事。
基本实体是 User
、Book
和 Year
个实体:
@Entity
@Table(name = "users")
@Data
public class User {
@Id
private int id;
private String name;
}
@Entity
@Table(name = "books")
@Data
public class Book {
@Id
private int id;
private String title;
}
@Entity
@Table(name = "years")
@Data
public class Year {
@Id
private int id;
private int year;
}
正如您所描述的,您可以创建一组 ListId
、Booklist
和 Userlist
关系表列表,因此:
@MappedSuperclass
@Data
@EqualsAndHashCode(of = "id")
public class ListId {
@Column(name="list_id")
private int listId;
@Id
private int id;
}
@Entity
@Table(name = "booklists")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class Booklist extends ListId {
@ManyToOne
private Book book;
}
@Entity
@Table(name = "userlists")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class Userlist extends ListId {
@ManyToOne
private User user;
@ManyToOne
private Year year;
}
肯定有其他方法可以做到这一点,但 none 将解决没有真正的 ListId
实体来建立 JPA 关系的问题。但是,您可以像这样使用此设置:
List<Booklist> bls = em.createQuery("select bl from Booklist bl left outer join Userlist ul on ul.listId = bl.listId where ul.user = :user", Booklist.class)
.setParameter("user", u1)
.getResultList();
bls.forEach(System.out::println);
这需要较新版本的 JPA,可能是 2.2 级别。至少它需要 Hibernate 5.1 或更高版本作为实现。如果要为此模式添加到 User
的双向映射,则:
@OneToMany(mappedBy = "user")
Set<Userlist> booklists;
然后像这样使用它。
List<Booklist> bls3 = em.createQuery("select bl from User u left outer join u.booklists ul left outer join Booklist bl on ul.listId = bl.listId where u = :user and ul.year = :year", Booklist.class)
.setParameter("user", u1)
.setParameter("year", y1)
.getResultList();
bls3.forEach(System.out::println);
假设您在按照工作所需的方式设计架构方面有一些回旋余地,那么是的,您应该更改它。
@Entity
@Table(name = "booklists")
@Data
@ToString(exclude = "user")
public class Booklist {
@Id
private int id;
@ManyToOne
private Book book;
@ManyToOne
private User user;
@ManyToOne
private Year year;
}
使用它更容易,并且不需要非相关实体从 JPA 2.2 或未映射的 ListId
class.
List<Booklist> bls2 = em.createQuery("select bl from Booklist bl where bl.user = :user", Booklist.class)
.setParameter("user", u2)
.getResultList();
bls2.forEach(System.out::println);
您可以将双向映射添加到 User
。
@OneToMany(mappedBy = "user")
Set<Booklist> booklists;
并像这样使用它:
List<Booklist> bls3 = em.createQuery("select bl from User u left outer join u.booklists bl where u = :user and bl.year = :year", Booklist.class)
.setParameter("user", u1)
.setParameter("year", y1)
.getResultList();
bls3.forEach(System.out::println);
后面的架构为您提供与前一个架构相同的结果。如果不是这么晚,我会尝试找出您的第一个模式违反了前 3 个规范化级别中的哪一个,但也许这是 reader.
最好的练习要求
跟踪 users
阅读的所有 books
,特别是 years
。
year
.
数据模型
@Entity
@Table(name = "users")
@Data
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
}
@Entity
@Table(name = "books")
@Data
public class Book {
@Id
@GeneratedValue
private Long id;
private String isbn;
private String title;
}
@Entity
@Table(name = "years")
@Data
public class Year {
@Id
private Integer year;
}
@Entity
@Table(name = "book_lists",
uniqueConstraints = @UniqueConstraint(columnNames = {"user_id", "year"}))
@Data
public class BookList {
@Id
@GeneratedValue
private Long id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "year")
private Year year;
@ManyToMany
@JoinTable(name = "book_lists_books",
joinColumns = @JoinColumn(name = "book_list_id"),
inverseJoinColumns = @JoinColumn(name = "book_id"))
private Set<Book> books = new LinkedHashSet<>();
}
数据库模式 (PostgreSQL)
CREATE TABLE years
(
year integer NOT NULL,
PRIMARY KEY (year)
);
CREATE TABLE users
(
id bigint NOT NULL,
name character varying(255),
PRIMARY KEY (id)
);
CREATE TABLE books
(
id bigint NOT NULL,
isbn character varying(255),
title character varying(255),
PRIMARY KEY (id)
);
CREATE TABLE book_lists
(
id bigint NOT NULL,
user_id bigint,
year integer,
PRIMARY KEY (id),
FOREIGN KEY (year) REFERENCES years (year),
FOREIGN KEY (user_id) REFERENCES users (id),
UNIQUE (user_id, year)
);
CREATE TABLE book_lists_books
(
book_list_id bigint NOT NULL,
book_id bigint NOT NULL,
PRIMARY KEY (book_list_id, book_id),
FOREIGN KEY (book_id) REFERENCES books (id),
FOREIGN KEY (book_list_id) REFERENCES book_lists (id)
);
例子
User johnDoe = new User();
johnDoe.setName("John Doe");
em.persist(johnDoe);
Book poeaaBook = new Book();
poeaaBook.setIsbn("007-6092019909");
poeaaBook.setTitle("Patterns of Enterprise Application Architecture");
em.persist(poeaaBook);
Book eipBook = new Book();
eipBook.setIsbn("978-0321200686");
eipBook.setTitle("Enterprise Integration Patterns");
em.persist(eipBook);
Year year2019 = new Year();
year2019.setYear(2019);
BookList johnDoe2019BookList = new BookList();
johnDoe2019BookList.setUser(johnDoe);
johnDoe2019BookList.setYear(year2019);
johnDoe2019BookList.getBooks().add(poeaaBook);
johnDoe2019BookList.getBooks().add(eipBook);
em.persist(johnDoe2019BookList);
em.find(BookList.class, johnDoe2019BookList.getId())
returns
BookList(id=4, user=User(id=1, name=John Doe), year=Year(year=2019), books=[Book(id=2, isbn=007-6092019909, title=Patterns of Enterprise Application Architecture), Book(id=3, isbn=978-0321200686, title=Enterprise Integration Patterns)])