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);
Related
I'm trying to understand better how Hibernate works...
I've a problem I cannot resolve.
When the application starts, it makes a query
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
int result;
String query = "SELECT count(*) as posti_disponibili from occupazione t inner join ";
query += "(select id_posto_park, max(date_time) as MaxDate from occupazione group by id_posto_park) tm on ";
query += "t.id_posto_park = tm.id_posto_park and t.date_time = tm.Maxdate and t.isOccupied = 0";
BigInteger bi = (BigInteger) session.createSQLQuery(query).uniqueResult();
result = bi.intValue();
HibernateUtil.shutdown();
At the end I close the current session.
Then, after it, I have a second query to be accomplished:
I open a new session (the first one was closed with the method HibernateUtil.shutdown();)
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Client client = new Client();
client.setIdClient(clientId);
String queryString ="from it.besmart.models.Client where clientId = :c)";
List<?> list = session.createQuery(queryString).setProperties(client).list();
but I got, now,
org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.cache.spi.RegionFactory]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:184)
at org.hibernate.cfg.Settings.getRegionFactory(Settings.java:300)
at org.hibernate.internal.SessionFactoryImpl$SessionBuilderImpl.openSession(SessionFactoryImpl.java:1322)
at org.hibernate.internal.SessionFactoryImpl.openSession(SessionFactoryImpl.java:677)
at it.besmart.parkserver.SocketClientHandler.run(SocketClientHandler.java:78)
at java.lang.Thread.run(Thread.java:744)
I cannot understand why, I closed the first session, but then opened a new one..
Is it correct to close the session on each query
EDIT
I'm trying to solve this problem, but with no result.
Now I have the first select query, which goes well. It's at the startup of the application.
try {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
String query = "SELECT count(*) as posti_disponibili from occupazione t inner join ";
query += "(select id_posto_park, max(date_time) as MaxDate from occupazione group by id_posto_park) tm on ";
query += "t.id_posto_park = tm.id_posto_park and t.date_time = tm.Maxdate and t.isOccupied = 0";
BigInteger bi = (BigInteger) session.createSQLQuery(query).uniqueResult();
result = bi.intValue();
}
I do not commit or flush it.
Then, going up with the application, I have the second query, so I getCurrentSession and try to do the select
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Client client = new Client();
client.setIdClient(clientId);
String queryString ="from it.besmart.models.Client c where c.clientId = :c";
logger.debug(queryString);
// logger.debug(session);
Query theQuery = session.createQuery(queryString).setProperties(client);
List<?> list = theQuery.list();
The application stops, nothing comes out, I don't know what's going on also because I cannot setup hibernate to log with pi4j...
Is there something wrong in how I use hibernate sessions?
If you use sessionFactory.getCurrentSession(), you'll obtain a "current session" which is bound to the lifecycle of the transaction and will be automatically flushed and closed when the transaction ends (commit or rollback).
If you decide to use sessionFactory.openSession(), you'll have to manage the session yourself and to flush and close it "manually".
For more info go to Hibernate transactions.
Im working with hibernate and java. I have an Group class and a User class. They share a many-to-many relationship as shown in this ERD .
What Im trying to achieve is that I want to retrieve a list of groups with the condition that they contain a User with a certain User_id.
In the GroupDao I have defined a function retrieveForUser in which I tried to retrieve the list using hibernate query language:
public List<Group> retrieveForUser(int userid){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
String hql = "select distinct g from Group g " +
"join g.allGroupMembers u " +
"where u.id = :id";
Query query = session.createQuery(hql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
query.setParameter("id", userid);
List<Group> list = query.list();
session.getTransaction().commit();
return list;
}
When I try to loop throught the resulting list using:
for(Group g : groupDao.retrieveForUser(user1.getId())){
System.out.println(g.getName());
}
I get the following errormessage:
java.lang.ClassCastException: java.util.HashMap cannot be cast to nl.hu.jelo.domain.group.Group
Question
How can I achieve it so that I end up with an List<Group> with only groups that contain a User with an certain User_id
You do not need to set result transformer. ALIAS_TO_ENTITY_MAP is for other purpose.
Simply do
String hql = "select distinct g from Group g " +
"join g.allGroupMembers u " +
"where u.id = :id";
Query query = session.createQuery(hql);
query.setParameter("id", userid);
is good enough.
Something off topic, are you sure you want to handle transaction manually like that?
I am using following method to update data in database.
String hql = "UPDATE EmployeeSalary set salary = :sl,"
+ "monthYr=:dt "
+ "WHERE id =:id and client.id=:cid";
for (EmployeeSalary e : eList) {
Query query = session.createQuery(hql);
query.setParameter("sl", e.getSalary());
query.setParameter("dt", e.getMonthYr());
query.setParameter("id", e.getId());
query.setParameter("cid", e.getClient().getId());
int result = query.executeUpdate();
System.out.println("result is " + result);
if (eAttList.size() % 20 == 0) {
session.flush();
session.clear();
}
}
Is there any problem with code.
On execution it is showing
result is 0
How to resolve above problem.
The documentation about update queries says:
No "Forms of join syntax", either implicit or explicit, can be specified in a bulk HQL query. Sub-queries can be used in the where-clause, where the subqueries themselves may contain joins.
Your query seems to violate this rule: client.id=:cid is an implicit join to the client entity.
Note that you're making your life difficult. You could simply get the entity by ID from the session (using Session.get()), and update it. Update queries are useful to update many rows at once.
I'm still a newbie at Hibernate and am trying to retrieve the results from a simple SELECT query. I keep getting a ClassCastException however. Can anyone tell me what I'm doing wrong here?
Here's the code:
public Wo getWoById(int id) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<Wo> result = (List<Wo>) session.createQuery("from Wo where woid = " + id);
if (result!=null && result.size()==1)
return result.get(0);
else return null;
}
...and the error message:
Exception in thread "main" java.lang.ClassCastException:
org.hibernate.internal.QueryImpl cannot be cast to java.util.List
at implDAO.WoImplDAO.getWoById(WoImplDAO.java:16)
at logic.Logic.deleteWo(Logic.java:72)
at nl.hanze.funda.admin.main.Main.<init>(Main.java:20)
at nl.hanze.funda.admin.main.Runner.main(Runner.java:16)
session.createQuery() returns a Query. It doesn't return the list of its results. You forgot to execute the query:
List<Wo> result = (List<Wo>) session.createQuery("from Wo where woid = " + id)
.list();
Also, you should use parameters instead of String concatenation:
List<Wo> result = (List<Wo>) session.createQuery("from Wo where woid = :id")
.setParameter("id", id)
.list();
Or, even simpler (and more efficient) since you're querying by ID:
return ((Wo) session.get(Wo.class, id));
Please change the query to
List<Wo> result = (List<Wo>) session.createQuery("from Wo where woid = " + id).list()
I am using the following query to fetch data from db in hibernate
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query q = session.createSQLQuery("select name,addr1,addr2,postal_code,country,email," +
"tel1,tel2,HeadOffice_id,Subscription_id from Restaurant " +
"where id=" +id);
session.getTransaction().commit();
Restaurant rest = (Restaurant)result.get(0);
But this is returning exception
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.hibernate.model.Restaurant
I also tried this way as well not sure whats doing
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Restaurant.class);
SessionFactory factory= config.configure().buildSessionFactory();
Session session =factory.getCurrentSession();
session.beginTransaction();
Query q = session.createSQLQuery("select name,addr1,addr2,postal_code,country,email," +
"tel1,tel2,HeadOffice_id,Subscription_id from Restaurant " +
"where id=" +id);
java.util.List<Restaurant> result = (List<Restaurant>)q.list();
session.getTransaction().commit();
Restaurant rest = (Restaurant)result.get(0);
Again I am getting the same exception. How can i do this with hibernate?
Thanks
Your query doesn't return instances of the Restaurant entity. It returns individual fields from this entity. The result of such a query is a List<Object[]>, each Object[] containing all the selected fields.
See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#queryhql-select:
Queries can return multiple objects and/or properties as an array of type Object[]:
If you want your query to returninstances of Restaurant, it should be
select r from Restaurant r where id = :id
And please, don't use concatenation to pass your parameter. Use named parameters as the above query.
as simple as:
Restaurant rest = (Restaurant)session.get(Restaurant.class, id);