gpt4 book ai didi

spring - JPA @OneToMany 从 Join 获取按日期的最新记录

转载 作者:行者123 更新时间:2023-12-01 06:13:37 24 4
gpt4 key购买 nike

试图从 获取最新记录时卡住了加入
我有以下类(class)

作者

    @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 如何帮助我根据出版日期仅从收藏中挑选最新的书。

最佳答案

如果您正在使用休眠,您可以使用 @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;

关于spring - JPA @OneToMany 从 Join 获取按日期的最新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44590334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com