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?
Related
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);
HQL
Query query = getSession()
.createQuery(
"select com from News as news " +
"join news.comments as com " +
"where news.id = :id " +
"order by com.addDate desc"
);
query.setParameter("id", id);
HQL above works fine. Want to change in the criteria api. I can not make. Please help
I suppose you can try something like this.
Criteria c = createCriteria(News.class);
c.add(Restrictions.idEq(id));
Criteria cComment = c.createCriteria("comments",c);
cComment.addOrder(Order.desc("addDate"));
ProjectionList projections = Projections.projectionList();
projections.add(Projections.property("c.id"),"id");
projections.add(Projections.property("c.addDate"),"addDate");
//Other Properties...
c.setProjection(projections)
c.setResultTransformer(Transformers.aliasToBean(Comment.class))
List<News> list = c.list();
Please mind that the Hibernate Criteria API is being deprecated in favor of the JPA Criteria API
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);
I have a namedQuery like this:
#NamedQueries ({ ...
#NamedQuery(name = "myUpdate", query = "update User set country = 'EN' where user.id = :id")
...
})
In dao layer
getHibernateTemplate().bulkUpdate(...?)
UPDATE
Query query = sessionFactory.getCurrentSession.getNamedQuery("myUpdate");
getHibernateTemplate.bulkUpdate(query.getQueryString(), id);
I get an error:
Hibernate: update User, set country=EN where id = 2343 ORA-00971: missing SET keyword
Anybody now how can resolve this problem?
UPDATE 2
#NamedQuery(name = "myUpdate", query =
"update User set country = 'EN' where
user.profile.id = ?")
OK
#NamedQuery(name = "myUpdate", query =
"update User set country = 'EN' where
user.profile.name = ?")
NOT OK :(
Unfortunately, that feature is missing in spring, as the named queries are supposed to be used only to retrieve data. One thing you can do is (this is a bit of a work around)
Session session = getHibernateTemplate().getSession();
Query query = session.getNamedQuery("myUpdate");
String update = query.getQueryString();
getHibernateTemplate().bulkUpdate(update, [params]);
I would put that in some kind of helper, so your DAO logic doesn't have to go around spring too.
edit
there's a dangling comma between User and set "update User , set country=EN where"
Actually this is a very old question but I had the same problem today. I realized that the update does not work since you cannont have a join inside of a simple UPDATE. That is also the reason why the comma is added. Hibernate tries to rewrite the query like this:
UPDATE User u, Profile p SET u.country = 'EN' where p.name = ? AND p.id = u.profile.id
To solve the issue you need to select the ids from the second table yourself.
#NamedQuery(name = "myUpdate", query = ""
+ " UPDATE User u "
+ " SET country = 'EN' "
+ " WHERE u.profile.id IN ( "
+ " SELECT p.id "
+ " FROM Profile p "
+ " WHERE p.name = ? "
+ " )"
I want to execute a query using hibernate where the requirment is like
select * from user where regionname=''
that is select all the users from user where region name is some data
How to write this in hibernate
The below code is giving result appropraitely
Criteria crit= HibernateUtil.getSession().createCriteria(User.class);
crit.add(Restrictions.eq("regionName", regionName));
Well as you alaready said you can either use the Criteria API or create a HQL query:
// Criteria
List<User> users = HibernateUtil.getSession().createCriteria(User.class);
crit.add(Restrictions.eq("regionName", regionName)).list();
// HQL
String query = "SELECT FROM User WHERE regionName = :region";
List<User> users = HibernateUtil.getSession().createQuery(query).setString("region", regionName).list();
String hql = "SELECT u FROM User u WHERE regionName=:regionName";
Query q = session.createQuery(hql);
q.setParameter("regionName", regionName);
List result = q.list();