首页 > 解决方案 > 如何将此本机 SQL 查询转换为我的 java 应用程序的 jpa 查询

问题描述

SELECT b.books_name,b.books_id FROM BOOKS b JOIN AUTHOR a 
ON b.AUTHOR_ID = a.AUTHOR_ID WHERE a.AUTHOR_NAME='WILLIAM';

标签: mysqlspring-data-jpaspring-data

解决方案


您需要创建 Book 和 Author 实体并建立映射。由于您的架构将 author_id 存储在 books 表中...我假设这里有多对一的映射。

@Entity
@Table(name="BOOKS")
Class Books {
    @Id
    Integer booksId;
    String booksName;
    @ManyToOne
    @JoinColumn(name="AUTHOR_ID")
    Author author;
    ... more fields
    public Books(Integer booksId, String booksName) {
        this.booksId = booksId;
        this.booksName = booksName;
    }
}

@Entity
@Table(name="AUTHOR")
Class Author {
    @Id
    String authorId;
    String authorName;
    ... more fields
}

JPA 查询

@Query("Select new Books(b.booksId, b.booksName) from Books b where b.author.authorName = 'WILLIAM'")
List<Books> findMatchingBooks();

推荐阅读