I'm trying to delete all the records from a MySQL table (46 records).
The code I have tried. Any suitable answer?
Session hs = connection.NewHibernateUtil.getSessionFactory().openSession();
Criteria cr = hs.createCriteria(Bookmark.class);
Bookmark b;
List<Bookmark> li = cr.list();
for (Bookmark s : li) {
b = new Bookmark();
b.setId(s.getId());
Transaction tr = hs.beginTransaction();
hs.delete(b);
tr.commit();
hs.flush();
hs.close();
}
Error
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [mypojos.Bookmark#7]
You cant delete objects like that. You would first have to get the object from db and then you can delete using hs.delete(b); this is usually used when you have to cascade changes to associated objects.
Best approach in this case is to use HQL query something like this.
String stringQuery = "DELETE FROM tablename";
Query query = session.createQuery(stringQuery);
query.executeUpdate();
Related
Is it possible to retrieve data from a query straight into the EmployeeForm?
Query as stored procedure empdata
SELECT a.name,b.username,b.password FROM Tbemployee left join Tbuser
Code
List<EmployeeForm> form = new ArrayList<EmployeeForm>();
EmpDB service = (EmpDB) RuntimeAccess.getInstance().getServiceBean(
service.begin();
Session session = service.getDataServiceManager().getSession();
SQLQuery query = session.createSQLQuery("EXEC empdata");
List list = query.list();
formList = list;
This gives me an error:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.emp.form.EmployeeForm
You need to use a ResultTransformer
The other option is to cast to List<Object[]> which contains rows with columns from the query result, and then iterate and extract data(more work).
The transformer could be something like:
query.setResultTransformer(Transformers.aliasToBean(EmployeeForm.class));
I have created three tables in Oracle SQL Developer namely
1.Test_Employee2
2.Test_Project2
3.Employee_Project2.
The table Employee_Project2 is the join table as the relation between Test_Project2 and Employee_Project2 is Many-To-Many.
In hibernate I created to two hibernate classes TestEmployee and TestProject for Test_Project2 and Employee_Project2 tables respectively,
and the table Employee_Project2 was defined in TestProject hibernate class as follows:
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "Employee_Project2", joinColumns = #JoinColumn(name = "proj_id"), inverseJoinColumns = #JoinColumn(name = "emp_id"))
private Set<TestEmployee> employeesList;
I populated the tables Test_Project2 and Employee_Project2 with some records, and the join table Employee_Project2 automatically got populated with some records.
now the problem I am facing currently is, I want to use a simple select statement on the join table Employee_Project2 using hiberante as follows:
String hql = "FROM Employee_Project2";
Query query = session.createQuery(hql);
List results = query.list();
for (Object row : results) {
//what to do here
}
how can I do that despite the join table 'Employee_Project2' is not a hibernate class.?
update:
I would like to retrieve all the records in the hibernate table "TestProject", so i wrote the following code
String hql = "FROM TestProject";
Query query = session.createQuery(hql);
List results = query.list();
System.out.println("results.get(0)" + results.get(0).toString());
now the problem is, at run time i receive something like the following
results.get(0)msc.hibernate.persistence.TestProject#12ec9534
how can i get the values contained in the each row??
What you want to do is to create typed query. With proper mapping you can get related objects as well - no need to query join tables as ORM will do this for you:
Query query = session.createQuery(hql);
List<TestProject> results = query.list();
for (TestProject row : results) {
//what to do here
// do whatever you want
}
And with propper relation mapping you can get relations like this:
for (TestProject row : results) {
Set<TestEmployee> employees=row.getEmployeesList();
// do more work.
}
As for "how to"s - the topic is too broad to cover it in single answer etc. but you should be able to start from here - http://hibernate.org/orm/documentation/5.1/
I have 2 tables, I want to fetch data from these tables where their foreign key is same. I have written a sql query first by using union:
SELECT jw.widget_name,jw.user_id FROM dashboard.jira_widget as jw WHERE jw.user_id = '1'
UNION ALL
SELECT uw.widget_name,uw.user_id FROM dashboard.unit_test_widget as uw WHERE uw.user_id = '1'
But Jpa doesn't support UNION at all.
Is there any other way to write this query in jpa?
I would suggest to try this query :
EntityManager em;
Query query = em.createQuery('SELECT jw, uw FROM JiraWidget as jw, UnitTestWidget as uw WHERE jw.userId = uw.userId AND jw.userId=:user');
query.setParameter('user', user);
Since multiple Select expression are used, the result is of type Object[]:
List<Object[]> results query.getResultList();
for (Object[] myUnion: results) {
JiraWidget jw = (JiraWidget) myUnion[0];
UnitTestWidget uw = (UnitTestWidget) myUnion[1];
//etc...
}
I understand some might simply answer this question with "Why didn't you just Google it"... But I did, and the more I researched this the more confused I got. I'm trying to query my database with Hibernate, the query has a 'where' clause.
Now creating a database entry is easy enough, in the case where I have a 'User' class, I simply do this:
// Gets a new session
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
// Creates a new User object
User user = new User("John", "p#55w0rd*", "john#doe.com");
// Save and commit
session.save(user);
session.getTransaction().commit();
But what do I do when I what to for instance
select * from Users where id = '3';
My Google searches pointed to something called HQL, which makes me wonder why I couldn't of just used straight JDBC then. Also it doesn't seem very object oriented. And then there's something like
session.createCriteria(.......
But I'm not sure how to use this.. Any help? Thanks guys.
When you use Native Query (non HQL ) you need to tell hibernate explicitely to handle it like below :
In below query createSQLQuery is special function to handle native sql's
String sql = "SELECT * FROM EMPLOYEE WHERE id = :employee_id";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(User.class);
query.setParameter("employee_id", 3);
List<User> results = query.list();
This can be done using criteria as well for that following is good starting point:
Criteria criteria = sess.createCriteria( User.class);
List<User> users= criteria.list();
http://www.developerhelpway.com/framework/hibernate/criteria/index.php
First of all, you need a hibernate.cfg.xml which contains properties for hibernate. This is e.g url, username and password, the driver and dialect. This file is placed in a package called resources.
You have to choose between using Hibernate Annotations example
or using hbm.xml files example
This is how you tell hibernate what your database is like. It wil automatically create queries for you based on how you annotates or defines in e.g user.hbm.xml.
Create a HibernateUtil.java class which holds the session factory.
You can fetch data from the database with
Criteria crit = getSessionFactory().getCurrentSession().createCriteria(User.class);
Example using queries:
List<?> hibTuppleResultList = currentSession.createQuery(
"from Person p, Employment e "
+ "where e.orgno like ? and p.ssn = e.ssn and p"
+ ".bankno = ?")
.setString(0, orgNo).setString(1, bankNo).list();
for (Object aHibTuppleResultList : hibTuppleResultList)
{
Object[] tuple = (Object[]) aHibTuppleResultList;
Person person = (Person) tuple[0];
hibList.add(person);
}
In the end all I really wanted was to know that if you don't want to use HQL you get something called 'Criteria Queries', and that in my case I'd do something like this:
Criteria cr = session.createCriteria(User);
cr.add(Restrictions.eq("id", 3));
List results = cr.list();
Me: "Thanks!"
Me: "No problem :)"
PS - we can really delete this question.
Query q = session.createQuery("from User as u where u.id = :u.id");
q.setString("id", "3");
List result = q.list();
Query with Criteria:
Criteria cr = session.createCriteria(User.class);
List results = cr.list();
Restrictions with Criteria:
Criteria cr = session.createCriteria(User.class);
cr.add(Restrictions.eq("id", 3));
// You can add as many as Restrictions as per your requirement
List results = cr.list();
You could also use it like this
List results = session.createCriteria(User.class).add(Restrictions.eq("id", 3)).list();
Some example for Crieteria Rsetriction query
Criteria cr = session.createCriteria(Employee.class);
// To get records having salary more than 2000
cr.add(Restrictions.gt("salary", 2000));
// To get records having salary less than 2000
cr.add(Restrictions.lt("salary", 2000));
// To get records having fistName starting with zara cr.add(Restrictions.like("firstName", "zara%"));
// Case sensitive form of the above restriction.
cr.add(Restrictions.ilike("firstName", "zara%"));
// To get records having salary in between 1000 and 2000
cr.add(Restrictions.between("salary", 1000, 2000));
// To check if the given property is null
cr.add(Restrictions.isNull("salary"));
// To check if the given property is not null
cr.add(Restrictions.isNotNull("salary"));
// To check if the given property is empty
cr.add(Restrictions.isEmpty("salary"));
// To check if the given property is not empty
cr.add(Restrictions.isNotEmpty("salary"));
You can create AND or OR conditions using LogicalExpression restrictions as follows:
Criteria cr = session.createCriteria(Employee.class);
Criterion salary = Restrictions.gt("salary", 2000);
Criterion name = Restrictions.ilike("firstNname","zara%");
// To get records matching with OR condistions
LogicalExpression orExp = Restrictions.or(salary, name);
cr.add( orExp );
// To get records matching with AND condistions
LogicalExpression andExp = Restrictions.and(salary, name);
cr.add( andExp );
List results = cr.list();
I think this will help you
I want to update a specific field in the database Persons table by using HibernateTemplate. I am trying to do like this but this not working.
public void updateDate(int Id,Date receivedDate) {
Id = 10;
receivedDate = 2012-11-12;
String queryString = "update Persons set recievedDate=? where Id=? ";
getHibernateTemplate().update(queryString, new Object[] { Id, receivedDate });
}
I am getting an exception "UnkownEntity" when I run this query. Can I do update of a specific field at all by using HibernateTemplate? Is there any other alternate to do specific field update?
update method in getHibernateTemplate does not allow hql query to execute. It only allows hibernate entity object.
See link hibernate template update method
In your case Hibernate tries to resolve update Persons set recievedDate=? where Id=? as an entity.
Solution:
Query q = s.createQuery("update Persons set recievedDate=:recievedDate where Id=:Id");
q.setString("recievedDate", "some date");
q.setString("Id", "54");
q.executeUpdate();
Hope its clear.
You have to list your classes in your session factory configuration.
I assume your entity named Person
in HQL you must use java class name, not db table name
if HibernateTemplate is using, here is my solution.
// EntityName is the table to be updated
EntityName entity = hibernateTemplate.find("from EntityName where id=?" , id);
//set the value which has to be updated
entity.setValue(yourNewValue);
hibernateTemplate.SaveOrUpdate(entity);
// above updated the existing Entity table without duplicates