Reputation: 86747
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
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
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
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
Reputation: 2085
You can use this method from entitymanager. http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#createNativeQuery%28java.lang.String%29
Upvotes: 0