I'm using Hibernate to delete the records from a table,but this giving an exception, could anyone know how to overcome this problem in the below query?
Session ses = HibernateUtil.getSessionFactory().openSession();
Transaction tx = ses.beginTransaction();
Query q = ses.createQuery("from RegisterPojo where email =:email");
q.setParameter("email", sl_no);
RegisterPojo pojo = (RegisterPojo) q.list().get(0);
ses.delete(pojo);
tx.commit();
ses.close();
Why not ?
Query q = ses.createQuery("delete from RegisterPojo where email =:email");
q.setParameter("email", sl_no);
q.executeUpdate();
Learn HQL
Before proceeding please learn more about hql. That reduces large amount of code.
Related
I am very new in hibernate I have an MySQL Query and I want to achive same output using Hibernate criteria
MySQL Query:
SELECT *,
(case when status = 'Active'
then 'Can Login'
else 'Not able to login' end) as LoginStatus
FROM UserLoginTable;
My Hibernate Code:
SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
Session session_hiber = sessionFactory.openSession();
session_hiber.beginTransaction();
Criteria criteria;
criteria = session_hiber.createCriteria(UserLoginTable.class);
List<UserLoginTable> myUserList = (List<UserLoginTable>)
criteria.list();
How I can add the Case criteria in the above code.
Is there any way ?
Thanks
Although I did not test this snippet, you may try to use CriteriaBuilder something like this:
CriteriaBuilder cb = session_hiber.getCriteriaBuilder();
cb.selectCase()
.when(cb.equal(path.get("status"), "Active"), "Can Login")
.otherwise("Not able to login")
.alias("LoginStatus");
Some help/info can be found here:
CASE statement in HQL or Criteria
Using the 'case...when...then...else...end' construct in the 'having' clause in JPA criteria query
https://docs.oracle.com/javaee/6/api/javax/persistence/criteria/CriteriaBuilder.html
SQL statement:
UPDATE table SET column = 'new_value' WHERE column = 'old_value'
(same column name)
How to do this in Hibernate?
You may use EntityManager.merge() which can lead to NonUniqueObjectException if there are multiple results are found with same column name.
Better to use NamedQuery ot NativeNamedQuery to achieve this.
My understanding is that you would want to perform batch updates.
I suggest you refer to this link
You can make use of the below code in order to get this done.
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlUpdate = "update Customer c set c.name = :newName where c.name = :oldName";
int updatedEntities = s.createQuery( hqlUpdate )
.setString( "newName", newName )
.setString( "oldName", oldName )
.executeUpdate();
tx.commit();
session.close();
Do note the below point mentioned in the link.
Joins, either implicit or explicit, are prohibited in a bulk HQL query. You can use sub-queries in the WHERE clause, and the sub-queries themselves can contain joins.
Well, I do not understand why me code does not work. Could Someone please take a look. It does not provide any error messages but the Customer will not be deleted. Other methods are working well (getCustomerbyId, getAllCustomers and so)
Thanks
public void deleteCustomerById(long id) {
EntityManager em = null;
try {
em = JpaUtil.getFactory().createEntityManager();
em.getTransaction().begin();
Query query = em.createQuery("Delete from Customer c where c.id = :id");
query.setParameter("id", id);
em.getTransaction().commit();
} finally {
JpaUtil.closeQuietly(em);
}
}
You need to execute queries to have SQL issues to the database; in this case you will want to use executeUpdate() and get the modified row count to verify something was deleted or not.
em.getTransaction().begin();
Query query = em.createQuery("Delete from Customer c where c.id = :id");
query.setParameter("id", id);
int rows = query.executeUpdate();
em.getTransaction().commit();
You are creating a query but not executing it.
You should add
query.executeUpdate();
before committing
Use jpa APis find(Customer.class) to find the customer object then use romove(object)
I have the following query in Hibernate.I got Hibernate Exception and I don't understand why Hibernate throws this exception. Could anyone help me?
Session session = this.sessionFactory.openSession();
session.createQuery("delete from Laboratory l where l.id=:laboratoryId")
.setParameter("laboratoryId", laboratoryId).executeUpdate();
session.close();
Try to add some spaces between the = sign and the bind name :laboratoryId and remove the alias:
Session session = this.sessionFactory.openSession();
session.createQuery("delete from Laboratory where id = :laboratoryId")
.setParameter("laboratoryId", laboratoryId)
.executeUpdate();
session.close();
Are you sure that laboratoryID has value? For my query builder I used something like this:
if (!laboratoryId.isEmpty()) {
query.setParameter("laboratoryId", laboratoryId());
}
also same thing for query
"delete o from Laboratory o"
if(!laboratoryId.isEmpty()){
query.append("where o.id = (:laboratoryId)")
}
But I used it for String values
Please show code for laboratoryId - is it user input or what?
You can try this one.
DELETE Clause
The DELETE clause can be used to delete one or more objects. Following is the simple syntax of using DELETE clause:
String hql = "DELETE FROM Employee " +
"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);
hi am very new to hibernate and could anybody plz help me out how to use update query to upadte the record of the table ...i am using like this in dao class
Session ses = HibernateUtil.getSessionFactory().openSession();
Transaction tx = ses.beginTransaction();
Query q = ses.createQuery("from RegisterPojo where email =:email");
q.setParameter("email", bean.getEmail());
RegisterPojo pojo = (RegisterPojo) q.list().get(0);
pojo.setUname(bean.getUname());
ses.update(pojo);
tx.commit();
ses.flush();
ses.close();
Hi i have edited my code from this am getting exception as, Could not execute JDBC batch update
thanks in advance
You need to call update on the hibernate session
Observe the following example
Query q = session.createQuery("from RegisterPojo where email =:email");
q.setParameter("email", "Fred#Example.com");
RegisterPojo pojo= (RegisterPojo)q.list().get(0);
pojo.setName("Fred");
session.update(pojo);