[英]JPA EntityManager find entity by ID
我在使用 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);
}
}
但我收到錯誤消息:
[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.
實體類包含在持久性單元中,我嘗試在 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
任何錯誤可能出在哪里的想法?
當您使用 EntityManager 時,您正在創建 JPQL(Java 持久性查詢語言語句)。 它們被 EntityManager 翻譯成 SQL 語句。
因此,不要使用 SQL 查詢,而是嘗試使用此 JPQL 查詢:
"SELECT t FROM TeamMember t WHERE memberId=1000",
其中“memberId”是您 TeamMember 實體中 MEMBER_ID 的屬性名稱(否則更改)。 對於高級查詢,您不應將參數放入查詢字符串中,而是使用查詢參數。
有關詳細信息,請查找 Java 持久性查詢語言。
如果需要,您還可以使用 EntityManager 執行本機 SQL 查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.