Delete all objects from database in hibernate Spring java - java

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();
}

Related

Get entity by email in hibernate

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
}

How to execute series of select query in Hibernate?

I am new to Hql. I am facing problem in select query. I am actually doing group rename option. For that first I am looking for pericular Id. next if there is no groupname of new groupname then I am updating old groupname. My method is like this.
private void renameGroup(String ogname, String gname , String clientid) {
//Here ogname="group7"
// gname="group8"
System.out.println("Old group name2="+ogname);
Session hSession = HibernateSession.getHibernateSession();
Transaction transaction = hSession.beginTransaction();
String hql= "select groupname from GroupDetails where clientid=:clientid and groupname=:oldGroupName";
Query query = hSession.createQuery(hql);
query.setParameter("clientid", Integer.valueOf(clientid));
query.setParameter("oldGroupName",ogname );
List<Object[]> groupList = (List<Object[]>) query.list(); // This has groupname [group7]
if(!(groupList.isEmpty()))
{
Session hSession2 = HibernateSession.getHibernateSession();
Transaction transaction2 = hSession.beginTransaction();
String hql2= "select groupname from GroupDetails where clientid =:clientid and groupname=:newGname";
Query query2 = hSession2.createQuery(hql2);
query2.setParameter("clientid", Integer.valueOf(clientid));
query2.setParameter("newGname",gname );
List<Object[]> groupList2 = (List<Object[]>) query2.list();//Here it has to be empty so that I can update but it also has [group7]
if(groupList2.isEmpty())
{// So it never come to this block
String hql3="update GroupDetails set groupname=:newGroupName where clientid=:clientid and groupname=:ogname";
Query query3 = hSession.createQuery(hql2);
query3.setParameter("newGroupName", gname);
query3.setParameter("clientid",Integer.valueOf(clientid));
query3.setParameter("ogname",ogname);
int res = query3.executeUpdate();
System.out.println("Command successfully executed....");
System.out.println("Numer of records effected due to update query"+res);
}
}
}
Observe my comments for better understand of my problem. I think problem is in session and transaction. but I am not getting. Please help me to solve this problem. Thank you

Hibernate execute update with criteria

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.

Why SQLQuery setParameter cannot use LIKE?

I have here:
Session session = getSession();
SQLQuery query = session.createSQLQuery("SELECT * FROM PERSON WHERE NAME LIKE '%?%'");
query.setParameter(0, personName);
I get the following error:
java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based!
But when I try:
Session session = getSession();
SQLQuery query = session.createSQLQuery("SELECT * FROM PERSON WHERE NAME = ?");
query.setParameter(0, personName);
its working.
I need to use LIKE.
You can do like this:
Session session = getSession();
SQLQuery query = session.createSQLQuery("SELECT * FROM PERSON WHERE NAME LIKE ?");
query.setParameter(0, "%" + personName + "%");
User criteria as
Criteria criteria = getSession().createCriteria(Person.class);
criteria.add(Restrictions.like("name", personName, MatchMode.ANYWHERE));
criteria.list();
String strQuery = "SELECT * FROM PERSON WHERE upper(NAME) LIKE '%"
+ personName.trim().toUpperCase() + "%'";
Session session = getSession();
SQLQuery query = session.createSQLQuery(strQuery );

Hibernate Return integer value

I am new to hibernate . I want to pass 2 column values and want hibernate to return primary key of that table.
String queryString = "select perId from Permission where document.docId=1 and user.id=2";
return getHibernateTemplate().find(queryString);
But this method return List.
How can i return int value.
Use the uniqueResult() method in Query. see here for an example or read the api here.
Here is an example. Replace the place holders as need to use them.
sessionFactory = getHibernateTemplate().getSessionFactory();
Session session = sessionFactory.getCurrentSession();
Query query = session
.createQuery("select value from table where ...");
query.setParameters("param1", value1);
result = (Type) query.uniqueResult();
You could do something like:
String sql = "select count(*) from table where ...";
BigDecimal count = (BigDecimal) hibernateTemplate.execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
SQLQuery query = session.createSQLQuery(sql);
return (BigDecimal) query.uniqueResult();
}});
return count;
Here is another way using addScalar:
Query query = session.createQuery("select value from table where param1 = :param1").addScalar("value", Type);
query.setParameters("param1", value1);
result = (Type) query.uniqueResult();
Example of String:
Query query = session.createQuery("select value from table where param1 = :param1").addScalar("value", StandardBasicTypes.STRING);
query.setParameters("param1", value1);
result = (String) query.uniqueResult();

Categories