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()
Related
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)
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 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);
I want to get distinct values from my db.
I have 10 fields in this db, and when i try to use such query:
SELECT DISTINCT (IMIE)FROM `przychodzace`
I get 26 results, but hibernate returns me just 17...
Here is list function:
List<String> list = new ArrayList<String>();
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
Criteria criteria = session.createCriteria(PrzychodzaceModel.class);
if (i == 0) {
criteria.setProjection(Projections.distinct(Projections.property("imie")));
criteria.addOrder(Order.asc("imie"));
}
list = criteria.list();
System.out.println(list.size() + "size");
return list;
Have anyone idea how to do it properly, i am trying to correct it for long time.
Thanks in advance.
I think an alternative to your problem would be to use a DAO class with a List method, eg:
public List listMenu() {
String hql = "FROM Menu";
org.hibernate.Query query = session.getCurrentSession().createQuery(hql);
query.setFirstResult(0);
query.setMaxResults(5);
List results = query.list();
return results;
}
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);