简体   繁体   English

JPA EntityManager 通过 ID 查找实体

[英]JPA EntityManager find entity by ID

I'm having trouble working with the JPA EntityManager, when trying a simple query like:我在使用 JPA EntityManager 时遇到问题,当我尝试一个简单的查询时:


import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javax.persistence.*;
import tables.TeamMember;

public class BoburvikDatabase extends Application {

    public EntityManagerFactory emf;
    public EntityManager em;
    public BoburvikDatabase BD;
    public Stage primaryStage;

    @Override
    public void start(Stage primaryStage) {
        this.primaryStage = primaryStage;
        emf = Persistence.createEntityManagerFactory("BoburvikDatabasePU");    
        em = emf.createEntityManager();
        this.BD = this;
        TypedQuery<TeamMember> q1 = em.createQuery(
                "SELECT * FROM \"TeamMember\" WHERE \"MEMBER_ID\"=1000;",
                TeamMember.class

        );
        TeamMember result = q1.getSingleResult();
        System.out.println(result);

        em.close();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

But I'm getting errors saying:但我收到错误消息:

    [27, 27] A select statement must have a FROM clause.
    [7, 7] The left expression is missing from the arithmetic expression.
    [9, 27] The right expression is not an arithmetic expression.
    [47, 52] '1000;' is not a valid numeric value.

The entity classes are included in the persistence unit, I tried to run the SQL command in pgAdmin and it worked and I think I am connecting to the database judging from this line in output:实体类包含在持久性单元中,我尝试在 pgAdmin 中运行 SQL 命令并且它起作用了,我想我正在连接到数据库,从 output 中的这一行判断:

    [EL Info]: connection: 2020-05-28 13:58:17.977--ServerSession(927866519)-- 
    file:/D:/Java/boburvik/BoburvikDatabase/dist/run285579090/BoburvikDatabase.jar_BoburvikDatabasePU 
    login successful

Any ideas where the fault could be?任何错误可能出在哪里的想法?

When you're working with EntityManager you're creating JPQL (Java Persistence Query Language statements).当您使用 EntityManager 时,您正在创建 JPQL(Java 持久性查询语言语句)。 They are translated to SQL Statements by the EntityManager.它们被 EntityManager 翻译成 SQL 语句。

So instead of your SQL query try this JPQL query:因此,不要使用 SQL 查询,而是尝试使用此 JPQL 查询:

"SELECT t FROM TeamMember t WHERE memberId=1000",

Where "memberId" ist the propertyName for MEMBER_ID in your TeamMember entity (change if otherwise).其中“memberId”是您 TeamMember 实体中 MEMBER_ID 的属性名称(否则更改)。 For advanced queries you shouldn't put parameters inside your query string and use query parameters instead.对于高级查询,您不应将参数放入查询字符串中,而是使用查询参数。

For more information look up Java Persistence Query Language.有关详细信息,请查找 Java 持久性查询语言。

You can also do native SQL queries with EntityManager if you need this.如果需要,您还可以使用 EntityManager 执行本机 SQL 查询。

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

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