Thùng Rỗng
Thùng Rỗng

Reputation: 3

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

Upvotes: 0

Views: 76

Answers (1)

Henry Martens
Henry Martens

Reputation: 229

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.

Upvotes: 1

Related Questions