What is the sql equivalent of hibernate query
I need to use the following query but i am not able to use spring injection so i need to make the query in simple sql.
How can i make the command that don't uses sessionfactory and any other beans
where registration is my entity class with username and password
public Registration findUserByEmail(String email) {
try {
Session session = sessionFactory.getCurrentSession();
开发者_StackOverflow社区 String query = "FROM Registration WHERE email =:email";
Query query2 = session.createSQLQuery(query);
query2.setString("email",email);
return (Registration) query2.uniqueResult();
} catch (Exception e) {
System.out.println(e);
throw new RuntimeException("DAO failed", e);
}
}
There's no Spring-specific code in your example. SessionFactory
is a Hibernate interface and you will need Hibernate for mapping your entity to/from the database. The SQL query executed by Hibernate will be something like
select * from registration where email = 'email'
with *
being the mapped columns and the email as given in the parameter.
If you really require to get rid of Hibernate, including all mapping logic and session handling, you could build the mapping yourself using plain JDBC for issuing the SQL query and mapping the ResultSet
to a new Registration()
yourself. Of course, this is a lot more cumbersome than using an ORM like Hibernate.
Set
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
in your hibernate.cfg.xml
It prints every query executed by it on the console.
First of all there is no need to make sql query since you have an entity. Hibernate is not dependent on Spring to get the SessionFactory so you don't have to think about "beans"
Depending on your configuration (I assume its annotation based), you can create a session factory like -
SessionFactory sessionFactory = new AnnotationConfiguration()
.configure("classpath/hibernate.cfg.xml")
.buildSessionFactory();
and if it is not annotation based then you can use
sessionFactory = new Configuration().configure().buildSessionFactory();
this link may help.
As a side note - if you're still willing to fire sql (will not recommend though) then do it in plain JDBC.
精彩评论