简体   繁体   中英

How to get value from a table referenced from foreign key on Hibernate?

I have two tables in my database, author and book. Here is the structure for both of them:

Book table:

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

    @ManyToOne
    private Author author;

    ...getters and setters...
}

Author table:

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

    ...getters and setters
}    

I would like to get the Author of a specific Book, by the book's title. I've reached this with this sql command on terminal: select author.name as author from author right join book on author.id = book.author_id where book.title='Some title'; . How should I structure the query in my code to achieve this?

This would be the equivalent query

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

in code

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

Guess it was much easier than I thought. Instead of using a complex query, I just fetched the book by its title and then fetched the author by its id, just like this, and it worked just fine:

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM