简体   繁体   中英

JPA Spring Query sql

I have a query in sql . I want to write it in JPA Spring.

How can i do it ?

SELECT * FROM user WHERE user.id=3 and user.enabled=1

To perform a native SQL query in JPA you have to do the following:

EntityManager manager = getEntityManager(); 
Query query = manager.createNativeQuery("SELECT * FROM user WHERE user.id = :id AND user.enabled = :enabled;");
query.setParameter("id", 3);
query.setParameter("enabled", 1);
Object[] user = query.getSingleResult();

If you want a JPQL query:

EntityManager manager = getEntityManager();
TypedQuery<User> query = manager.createQuery("SELECT u FROM User u WHERE u.id = :id AND user.enabled = :enabled;", User.class);
query.setParameter("id", 3);
query.setParameter("enabled", 1);
User user = query.getSingleResult();

Using the JPQL query is the better style because it is type-safe. You can perform the statement directly on the entity without knowing the specific table structure of your database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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