如何从Hibernate外键引用的表中获取值?

时间:2019-01-15 15:54:33

标签: java mysql hibernate

我的数据库中有两个表,作者和书。这是它们两个的结构:

书桌:

@Entity
public class Book {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String title;

    @ManyToOne
    private Author author;

    ...getters and setters...
}

作者表:

@Entity
public class Author {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;

    ...getters and setters
}    

我想通过该书的标题来获得特定书的作者。我已经在终端select author.name as author from author right join book on author.id = book.author_id where book.title='Some title';上使用此sql命令达到了此目的。如何在代码中构造查询以实现此目的?

2 个答案:

答案 0 :(得分:0)

这将是等效的查询

select a.name as author from author a right join book b where b.title = 'Some title'

用代码

entityManager.createQuery("select a.name as author from author a right join book b where b.title = ? ").setParameter(1, "Some title");

答案 1 :(得分:0)

猜猜这比我想象的要容易得多。与其使用复杂的查询,我只是按照书名来获取这本书,然后按照其ID来获取作者,就像这样,它工作得很好:

Query query = manager.createQuery("select b from book b where b.title = :myTitle")
            .setParameter("myTitle", "Some title");

Book book = (Book) query.getSingleResult();
Author author = manager.find(Author.class, book.getAuthor().getId());

System.out.println(author.getName());