简体   繁体   English

当主键为“自动递增”时,如何使用JPA(EclipseLink)从数据库获取特定的“行”?

[英]How to get a specific “row” from a DB using JPA (EclipseLink) when the primary key is Auto Incremented?

Say I have this table 说我有这张桌子

CREATE TABLE person(
    person_id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    x_cordinates INT,
    y_cordinates INT
);

In the past I have used 过去我用过

Person person = EntityManager.find(Person.class, primaryKey);

But the primary key in this instance is auto incremented, is it possible to get a row back using the other colums such as first_name and last_name to get the primary key along with the other values ? 但是在这种情况下,主键是自动递增的,是否可以使用其他列(例如first_name和last_name)返回行以获取主键以及其他值?

You can create a NamedQuerry like that : 您可以这样创建一个NamedQuerry:

@NamedQuery(name="person.findAll", query="SELECT p FROM Person p WHERE like :first_name") 

And can assign a value to "first_name" like that : 并且可以像这样为“ first_name”分配一个值:

query.setParamter("fist_name", "%name%");

You can read this documentation . 您可以阅读本文档

Use method createQuery or createNativeQuery of entityManager. 使用entityManager的方法createQuerycreateNativeQuery

With createQuery you have to use JPQL syntax and with createNativeQuery , you've to use the standard SQL syntax. 对于createQuery您必须使用JPQL语法,对于createNativeQuery ,您必须使用标准的SQL语法。

For example : 例如 :

Query query = EntityManager.createQuery("select * from person p where p.first_name = :fname");
17.
query.setParameter("fname", firstName);
Person p = query.getSingleResult();

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

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