简体   繁体   English

JPA中的SQL查询

[英]SQL-query in JPA

We have this school project where we are creating a book library system where the main purpose is to use a database connection. 我们有一个学校项目,正在创建一个图书图书馆系统,其主要目的是使用数据库连接。 In this case JPA and ObjectDB. 在这种情况下,JPA和ObjectDB。

Our problem is that we have 3 tables. 我们的问题是我们有3个表。 One that describes a book (title, author and published year), the second a borrower (first name, last name, address, email and phonenumber) and the last table the lending-function that gets the primary ID-key from the other two tables. 一个描述书籍(书名,作者和出版年份),第二个描述借书人(名字,姓氏,地址,电子邮件和电话号码),最后一个表描述借贷功能,该功能从另外两个获取主要ID密钥表。

The problem is that when we are using the list borrowed book-function it prints out only the IDs from the two other tables. 问题是,当我们使用列表借书功能时,它仅打印出其他两个表中的ID。 We think the problem is the SQL-query and we haven't gotten the chance to learn SQL properly. 我们认为问题出在SQL查询,我们还没有机会正确学习SQL。

So our question is, how do we create a SQL query that gets the title from the book-table and the first and last name from the borrower table and not the IDs. 因此,我们的问题是,我们如何创建一个SQL查询,该查询从书本表中获取标题,并从借款人表中获取名字和姓氏,而不是ID。

The SQL-query where we have only managed to work is this: 我们只能设法工作的SQL查询是这样的:

TypedQuery<BokLån> q = em.createQuery("SELECT bookborrow FROM BookBorrow BookBorrow", BookBorrow.class);

IT is problem of fetch and fetch type mechanism. IT是获取和获取类型机制的问题。 currently your entities are loaded lazy, you can load these eagerly in entity class 当前您的实体被延迟加载,您可以在实体类中积极地加载它们

You need to write a proper JOIN statement to combine the lending-table to the other tables, and retrieve the info from there. 您需要编写适当的JOIN语句,以将贷款表与其他表合并,然后从那里检索信息。

Something along the lines of: 类似于以下内容:

SELECT 
    book.title, 
    person.firstname, 
    person.lastname 
FROM
   borrower
     JOIN book ON book.bookid = borrower.bookID
     JOIN person ON person.personid = borrower.personid

The way it works is the ON condition specifies how to tie the tables together. 它的工作方式是“打开”条件,该条件指定如何将表捆绑在一起。 In your case, the borrower table has a personID which relates to the PersonID column in the person table. 在您的情况下,借用者表具有与该人员表中的“人员ID”列相关的人员ID。 Establishing the link with the JOIN, you can then access the other columns in the Person table. 通过JOIN建立链接,然后可以访问Person表中的其他列。

The exact same method works for the book table. 完全相同的方法适用于书桌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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