【问题标题】:How to get value from a table referenced from foreign key on Hibernate?如何从 Hibernate 上的外键引用的表中获取值?
【发布时间】:2019-01-16 00:55:39
【问题描述】:

我的数据库中有两个表,author 和 book。以下是它们的结构:

书桌:

@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
}    

我想通过书名获取特定书的作者。我已经在终端上使用了这个 sql 命令:select author.name as author from author right join book on author.id = book.author_id where book.title='Some title';。我应该如何在我的代码中构造查询来实现这一点?

【问题讨论】:

    标签: java mysql hibernate


    【解决方案1】:

    这将是等效的查询

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

    【讨论】:

    • 它不起作用。它正在抛出一个SQLSintaxErrorException
    • 仍然无法正常工作,同样的异常。我想也许我应该改变关系的类型
    【解决方案2】:

    我想这比我想象的要容易得多。我没有使用复杂的查询,而是按书名获取书,然后按 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());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-02
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      • 2016-07-10
      相关资源
      最近更新 更多