试图从加入获取最新记录时遇到困难 我有以下课程
作者
@Entity
@Table(name = "author")
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "name")
private String name;
@OneToMany
@JoinColumn(name = "author_id", referencedColumnName = "id")
@OrderBy("id Desc")
private List<Book> books;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
书
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "author_id")
private Integer authorId;
@Column(name = "date_published")
private Date datePublished;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Integer getAuthorId() {
return authorId;
}
public void setAuthorId(Integer authorId) {
this.authorId = authorId;
}
public Date getDatePublished() {
return datePublished;
}
public void setDatePublished(Date datePublished) {
this.datePublished = datePublished;
}
}
存储库
@Repository
public interface AuthorRepository extends
JpaRepository<Author, Long> {
public Page<Author> findALL(int id, Pageable pageable);
}
当前结果
{
"id": 1,
"name": "James",
"books":[
{
"id": 1,
"name": "book1",
"datePublished": '12/12/2012'
},
{
"id": 1,
"name": "book2",
"datePublished": '01/02/2013'
}]
},
{
"id": 2,
"name": "Tim",
"books":[
{
"id": 5,
"name": "book5",
"datePublished": '12/12/2014'
},{
"id": 6,
"name": "book6",
"datePublished": '01/02/2015'
}]
}
预期结果
{
"id": 1,
"name": "James",
"books":[
{
"id": 1,
"name": "book2",
"datePublished": '01/02/2013'
}]
},
{
"id": 2,
"name": "Tim",
"books":[
{
"id": 6,
"name": "book6",
"datePublished": '01/02/2015'
}]
}
此处将返回作者列表及其各自的图书。
问题是JPA如何帮助我根据发布的日期从集合中挑选最新的书籍。
答案 0 :(得分:4)
如果您正在使用休眠,则可以使用@JoinFormula
来实现此目的,以按日期映射最新记录。类似的东西:
@ManyToOne(fetch = FetchType.LAZY)
@JoinFormula("(" +
"SELECT b.id " +
"FROM book b " +
"WHERE b.author_id = id " +
"ORDER BY b.date_published DESC " +
"LIMIT 1" +
")")
private Book latestBook;
答案 1 :(得分:1)
我有类似的问题。另一个解决方案是使用@Where
批注:
@OneToMany
@JoinColumn(name = "author_id", referencedColumnName = "id")
@Where(clause = "date_published = (SELECT MAX(book.date_published) " +
"FROM book" +
"where author_id = book.author_id)")
@OrderBy("datePublished Desc")
private List<Book> books;
答案 2 :(得分:0)
如果您想为每位作者获取最后一本书,可以添加瞬态字段来获取它:
@Entity
@Table(name = "author")
public class Author {
.......
@Transient
private Book lastBook;
@PostLoad
private void setLastBook() {
if(books==null || books,isEmpty())
this.lastBook=null;
}else{
this.lastBook=books.get(0);
}
}
或一对一地将其保存在db中,使用@PostPersist和@PostUpdate注释的相同方法。它会在上一本书中自动保存在db中