0

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

2
  • 1
    there is already mistake in sql query = ) Commented Jul 7, 2017 at 7:56
  • Do you want a jpql query or do you want to execute the sql? Commented Jul 7, 2017 at 7:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Glad I could help. Please mark the anwere as correct. So your question will be displayed as anwered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.