I am trying to get the user from his email , the email is unique in the database.
I write this code :
session.beginTransaction();
User user = (User) session.createQuery("select * from `user` where email = '"+email+"'");
session.getTransaction().commit();
Is this code right ? or there is some function in hibernate to get entity by column value ?
I see two problems with your current code. First, you appear to be running a native SQL query, not HQL (or JPQL). Second, your query is built using string concatenation, leaving it prone to attack by SQL injection
Consider the following code:
Query query = session.createQuery("from User u where u.email = :email ");
query.setParameter("email", email);
List list = query.list();
Without writting any SQL:
public static Person getPersonByEmail(String email) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Person> cr = cb.createQuery(Person.class);
Root<Person> root = cr.from(Person.class);
cr.select(root).where(cb.equal(root.get("email"), email)); //here you pass a class field, not a table column (in this example they are called the same)
Query<Person> query = session.createQuery(cr);
query.setMaxResults(1);
List<Person> result = query.getResultList();
session.close();
return result.get(0);
}
example of use:
public static void main(String[] args) {
Person person = getPersonByEmail("test#mail.com");
System.out.println(person.getEmail()); //test#mail.com
}
Related
I want to delete all those rows from xyz table where id = 1 using hibernate spring.
I have tried following code but its not giving error but not deleting rows -
Session session = (Session) getEm().getDelegate();
String sql ="Delete from xyz where id=:id" ;
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("id", "1");
int flg = query.executeUpdate();
Can you please help me to delete all rows using hibernate query.
Try wrapping your code within a transaction like this:
Session session = (Session) getEm().getDelegate();
Transaction tx = session.beginTransaction();
String sql ="Delete from xyz where id=:id" ;
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("id", "1");
int flg = query.executeUpdate();
tx.commit();
Try
query.setParameter("id", Long.valueOf(1));
if your entity is of type Long (which ideally should be).
Reference: http://www.codejava.net/frameworks/hibernate/hibernate-basics-3-ways-to-delete-an-entity-from-the-datastore
Note: The link is just for your reference.
public void deleteById(Class clazz,Integer id) {
String hql = "delete " + clazz.getName() + " where id = :id";
Query q = session.createQuery(hql).setParameter("id", id);
q.executeUpdate();
}
Code:
public void getDetails() {
try {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";
Query query = session.createQuery(hql);
List<CrbtSubMasterDemo> itr = query.list();
session.getTransaction().commit();
for (CrbtSubMasterDemo pojo : itr) {//excepion line
System.out.println("[" + pojo.getMobile() + "]");
}
} catch (Exception e) {
e.printStackTrace();
}
}
CrbtSubMasterDemo is pojo mapped with the db.
When I try to run it, it gives following Exception:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.telemune.demoPojo.CrbtSubMasterDemo
at com.telemune.demoHibernate.QueryTester.getDetails(QueryTester.java:57)
at com.telemune.demoHibernate.QueryTester.main(QueryTester.java:23)
The question is query.list() is returning the list of objects of pojo class. Then why is this Exception. I am new to Hibernate, sorry if its a silly question.
When you write this:
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";
Your result set is not a List of CrbtSubMasterDemo
Try to write:
String hql = "select FROM CrbtSubMasterDemo c where rownum<20";
Another way is define a new constructor of CrbtSubMasterDemo where you pass only two fields c.mobile, c.password
so your query becomes:
String hql = "select new " + CrbtSubMasterDemo.class.getName() + "(c.mobile, c.password) FROM CrbtSubMasterDemo c where rownum<20";
If you follow this solution, remeber to add a default constructor too (without parameters), so in your pojo you have:
public CrbtSubMasterDemo(String mobile, String password) {
this.mobile = mobile;
this.password = password
}
and
public CrbtSubMasterDemo() {
}
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";
Query query = session.createQuery(hql);
Result of this will be List<Object[]>
List<Object[]> itr = query.list();
for (Object[] row : itr) {
System.out.println(String.format("mobile:%s, password:%s", row[0], row[1]));
}
if mobile and password are strings, of course. You can use a transformer to transform results directly to CrbtSubMasterDemo.
Hibernate 3.2: Transformers for HQL and SQL
FluentHibernateResultTransformer
Sir, Many times user faces this kinda requirements . Hibernate has ResultTransformer to convert a hql/sql in Object.
public CrbtSubMasterDemo{
private Stirng mobile;
private String password;
public CrbtSubMasterDemo(){
--------------
}
#####after setting the transation set whichever columns you are selecting should be given as name of property of your object
String hql = "select c.mobile as mobile, c.password as password FROM CrbtSubMasterDemo c where rownum<20";
Query query = session.createQuery(hql);
List<CrbtSubMasterDemo> itr = query.setResultTransformer(Transformers.aliasToBean(CrbtSubMasterDemo.class) ).list();
##No need to commit the transaction.
}
It will convert you query into the CrbtSubMasterDemo
Do not directly cast the result of "query.list();" to List of CrbtSubMasterDemo. As query.list() return object list. Iterate over the object list received and cast one by one to put in list List of CrbtSubMasterDemo
I have a table by name Person and it has only one row data. I dont want to take it in list(). Can I get the data of Object type. Below is my code snippet
Session session = this.sessionFactory.openSession();
String sql = "SELECT * FROM PERSON";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Person.class);
List<Person> list = query.list();
===================================
I want the above code snippet to work as below:
Session session = this.sessionFactory.openSession();
String sql = "SELECT * FROM PERSON";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Person.class);
Person p = query;
which is throwing error. Please help me out on fixing the issue.
query is result of your session select. query.list() is your results. and you can get with query.list().get(0);
You can cast query list to personList;
List<Person> list = query.list();
return list.get(0);
You can just cast your result to person;
Person p = (Person) query.list().get(0);
Is it possible to execute an update while using Criteria in Hibernate? For example:
Session session = getSession();
Criteria crit = session.createCriteria(User.class);
crit.add(Restrictions.eq("token", sessionToken));
User user= new User();
Transaction tx = session.getTransaction();
try
{
tx.begin();
session.updateWithCriteria(user, crit); //my imaginary function
tx.commit();
}
catch (Exception e)
{
e.printStackTrace();
tx.rollback();
}
session.close();
There is a very powerful feature called:
15.4. DML-style operations
small cite from doc:
... However, Hibernate provides methods for bulk SQL-style DML statement execution that is performed through the Hibernate Query Language...
So, while this is not about criteria - we still can use our domain model for querying, because it is about HQL. This is a snippet showing the power:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlUpdate = "update Customer c set c.name = :newName where c.name = :oldName";
// or String hqlUpdate = "update Customer set name = :newName where name = :oldName";
int updatedEntities = s.createQuery( hqlUpdate )
.setString( "newName", newName )
.setString( "oldName", oldName )
.executeUpdate();
tx.commit();
session.close();
SUMMARY: Having that in place:
we can use query to filter results
we can apply bulk update on it
we won't need to load these rows in memory, into the session...
Now we can do something like this for bulk update and delete. New api's released for criteriaUpdate and CriteriaDelete
CriteriaBuilder cb = this.em.getCriteriaBuilder();
// create update
CriteriaUpdate<Order> update = cb.createCriteriaUpdate(Order.class);
// set the root class
Root e = update.from(Order.class);
// set update and where clause
update.set("amount", newAmount);
update.where(cb.greaterThanOrEqualTo(e.get("amount"), oldAmount));
// perform update
this.em.createQuery(update).executeUpdate();
First you should get the object then modify and update:
Query q = session.createQuery("from StockTransaction where tranId = :tranId ");
q.setParameter("tranId", 11);
StockTransaction stockTran = (StockTransaction)q.list().get(0);
stockTran.setVolume(4000000L);
session.update(stockTran);
If you want to use partial/dynamic update feature then put
#org.hibernate.annotations.Entity(
dynamicUpdate = true
)
annotation on top of the dao class.
Example from: http://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/
Note: The Question is "with criteria" but the accepted answer is NOT "with criteria" but SQL.
I am a bit lost when it comes to retrieving results from the database.
My MemberModel consists of 4 fields: id, username, password and email. I have been able to successfully save it to database.
Now I need to retrieve an id of a member who's username equals "Test".
I tried something along the lines:
SQLQuery query = session.createSQLQuery("SELECT id FROM members WHERE username = :username");
query.setString("username", username);
List<MemberModel> returnedMembers = query.list();
MemberModel member = returnedMembers.get(0);
int id = member.getId();
However I get an error that member.getId() cannot be converted to int, since it is MemberModel... But the getter getId() returns int.
I am quite confused. The question is: what would be the easiest and fastes way to retrieve member id based on condition (value of username)?
You are using a native SQL query, but should use HQL query. That means you have to change the query to:
session.createQuery("SELECT m FROM MemberModel m WHERE m.username = :username")
I would change your code into something like this:
public MemberModel getMember(String username) {
Query query = sessionFactory.getCurrentSession().createQuery("from " + MemberModel.class.getName() + " where username = :username ");
query.setParameter("username", username);
return (MemberModel) query.uniqueResult();
}
Then you should be able to do:
MemberModel model = someInstance.getMember("someUsername");
int id = model.getId();
You can also use criteria and restrictions api.
Criteria criteria = session.createCriteria(MemberModel.class);
criteria.add(Restrictions.eq("username", username));
MemberModel member=(MemberModel)criteria.uniqueResult();