membersound
membersound

Reputation: 86747

How to create native queries in Spring?

I have a spring application that should connect to an existing database and just query an entity for existence based on some attributes.

I don't want to create a @Entity class for this. But I still want to use the spring managed EntityManager etc.

When using Spring, what is the best approach to just query a select for that entity? Using em.createNamedQuery(QUERY); with String QUERY = "SELECT count(*) from my_table where username =: username AND email := email)";?

Upvotes: 0

Views: 5350

Answers (4)

SpringLearner
SpringLearner

Reputation: 13844

simple example of native query

@PersistenceContext
    EntityManager em;

public String test(Integer id)
{
Query query =   em.createNativeQuery("SELECT name FROM Accounts  where id=?");
query.setParameter(1,id);
return query.getSingleResult();
}

Upvotes: 1

Trynkiewicz Mariusz
Trynkiewicz Mariusz

Reputation: 2772

Answers from @predrag-maric and @pL4Gu33 are both correct but if you use JPA in your project (for example, Hibernate) you might consider using @NamedNativeQuery annotation as well.

More about named native queries.

Upvotes: 1

Predrag Maric
Predrag Maric

Reputation: 24423

Use em.createNativeQuery(QUERY). Also, you'll have to use positional parameters (?1) instead of named parameters (:email), because only positional parameters are supported by JPA in native queries.

Upvotes: 0

Related Questions