Hibernate cannot access data inserted by phpMyAdmin - java

My question is about hibernate, actually I'm working on a Java EE application using hibernate and mysq.
Everything looks fine. but I still have one problem when I insert data via phpMyAdmin to my database, I cannot access them immediately via hibernate unless I started the server (tomcat) again.

This is because your transaction in phpMyAdmin was not committed.
Try running this query in phpMyAdmin before running commands.
SET ##AUTOCOMMIT = 1;
Or running commit; at the end of your query.
Possible duplicate of:
COMMIT not working in phpmyadmin (MySQL)

I noticed that i've forgot to add transaction.commit(); for every hibernate session.get(); method, so somehow it keeps data in the cache.
public List<User> getAllUsers(User user) throws Exception {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Criteria c = session.createCriteria(User.class).add(Restrictions.ne("idUser", user.getIdUser()));
List<User> users = c.list();
tx.commit();//i forget to add this
return users;
} catch (Exception e) {
if (tx != null) tx.rollback(); throw e;
} finally {
session.close();
}
}

Related

Hibernate getCurrentSession logs (P6SPY) multiple connections?

I have a doubt, using getCurrentSession of a sessionFactory, it generates many connections to the database.
P6Spy logs
when it reaches about 400 the application crashes:
Crash
A typical method of a query by hibernate:
#Autowired
#Qualifier(value = "sessionFactory")
private SessionFactory sessionFactory;
try {
Session s = this.sessionFactory.getCurrentSession();
Query query = s.createQuery("from x where c.numFactura = :numFactura");
query.setParameter("numFactura", numFactura);
return query.uniqueResult();
} catch (Exception ex) {
throw ex;
}
I really don't know, if these events are connected, what do you think?
the problem wasn't there, I had a problem with the Jasper Reports DB Conection, fixed by autoclosing conection on timeout.

Session and Transaction in Hibernate Java

In Java Hibernate, when we need to do something with DB we need:
1. Open session
2. Begin transaction
3. Finish transaction
4. Close session
For example if I want to get Student list:
public static List<Student> getStudentList()
{
List<Student> l = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
String hql = "from Student";
Query query = session.createQuery(hql);
l = query.list();
} catch (HibernateException ex) {
//Log the exception
System.err.println(ex);
} finally {
session.close();
}
return l;
}
Insert a student
public static boolean addStudent(Student s)
{
Session session = HibernateUtil.getSessionFactory().openSession();
if (... /* check if student is already exists*/)
{
return false;
}
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(s);
transaction.commit();
} catch (HibernateException ex) {
//Log the exception
transaction.rollback();
System.err.println(ex);
} finally {
session.close();
}
return true;
}
Why there is no transaction in getStudentList()? Thank in advance
This hibernate article explains the behavior of SELECT operations which are not explicitly executed within a transaction.
The following example is given in the article but it's also true for your query example.
Session session = sessionFactory.openSession();
session.get(Item.class, 123l);
session.close();
A new Session is opened. It doesn’t obtain a database connection at this point.
The call to get() triggers an SQL SELECT. The Session now obtains a JDBC Connection from the connection pool. Hibernate, by default, immediately turns off the autocommit mode on this connection with setAutoCommit(false). This effectively starts a JDBC transaction!
The SELECT is executed inside this JDBC transaction. The Session is closed, and the connection is returned to the pool and released by Hibernate — Hibernate calls close() on the JDBC Connection. What happens to the uncommitted transaction?
The answer to that question is, “It depends!” The JDBC specification doesn’t say anything about pending transactions when close() is called on a connection. What happens depends on how the vendors implement the specification. With Oracle JDBC drivers, for example, the call to close() commits the transaction! Most other JDBC vendors take the same route and roll back any pending transaction when the JDBC Connection object is closed and the resource is returned to the pool.
Obviously, this won’t be a problem for the SELECT [...]
Lets extend the above example to provoke a possible problem.
Session session = sessionFactory.openSession();
Item item = session.get(Item.class, 123l);
item.setPrice(10);
session.close();
Now it depends on the JDBC driver if the new price for the Item is persisted or not.
So you can neglect begin and commit transactions on pure SELECT operations even when your JDBC driver will rollback the transaction as long as you have no database changes.
But anyway I would strongly recommend using transactions on any operation to avoid misunderstanding and problems.

Issue in fetching records from database using Hibernate

The method shown below is not fetching data from db with the criteria strProductId. I'm getting the value of strProductId inside the method. Can anyone please help..Thanks in advance....
public List<ProductServices> getAllServices(String strProductId){
Session session = sessionFactory.getCurrentSession();
Criteria cr = session.createCriteria(ProductServices.class);
cr.add(Restrictions.eq("productId", strProductId));
return (List<ProductServices>) cr.list();
}
Method getAllServices must be in a transaction. Check it, please.
Updated
You must open a transaction, do a request and close a transaction. It can be done by Spring of course.
See this example. UserManagerImpl has a #Transactional annotation on methods.
you can do some thing like this
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Criteria cr = session.createCriteria(ProductServices.class);
cr.add(Restrictions.eq("productId", strProductId));
return (List<ProductServices>) cr.list();
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}

Hibernate session manager for bulk insertion and fetching at the same time

I am new to hibernate. I am facing problems with hibernate session problems. when i am trying to insert a data I will use
session.openSession();
After completing the updation I am using session.flush();session.clear(); and session.close().
I don't how to maintain this. I am getting deadlock exception. At the same time of insertion i am opening another one session to fetch data.
Please help me.. This is my existing sample code
#Autowired
#Qualifier("messageListenerReportSessionFactory")
private SessionFactory messageListenerReportSessionFactory;
Session session = messageListenerReportSessionFactory.openSession();
if(session != null && session.isOpen()){
try{
Transaction tx= session.beginTransaction();
Query q = session.createQuery("Update "+tableName+" set isUser = ? where id = ?");
q.setInteger(0, 2);
q.setLong(1, id);
q.executeUpdate();
tx.commit(); tx = null;
}catch(Exception ex){
PointelTraceLogger.logger.log(Level.ERROR, "[Audit] Error in updateUser() in com.pointel.application.database.pointelreport.MessageListenerReportDao");
PointelTraceLogger.writeStackTrace(ex);
}finally{
session.clear();
session.close();
}
}

Java, Hibernate getList not working

I am attempting to write a website using hibernate for database access. Saving I can get working fine, however when I try and call my getList method upon executing the session.createQuery call the code just drops into the finally method without throwing an exception leaving me a bit confused!
Code is below:
public List<Category> getCategories() {
//insertCategory();
System.out.println("in get categories");
List<Category> result = null;
Session session = HibernateUtil.getSessionfactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Query cats = session.createQuery("from category where is_parent = 1");
result = cats.list();
transaction.commit();
for (java.util.Iterator<Category> it = result.iterator();it.hasNext();){
Category myCategory = it.next();
System.out.println(myCategory);
}
calculateBlueprintSize(result.size());
} catch (HibernateException e) {
// TODO: handle exception
transaction.rollback();
e.printStackTrace();
} catch (Exception ee) {
ee.printStackTrace();
} finally {
session.close();
}
return result;
}
My insert works fine (hardcoded for now just to prove I can connect to the DB)
public void insertCategory() {
Category newCat = new Category();
newCat.setActive(new Integer(1));
newCat.setCategoryDescription("my test category");
newCat.setCategoryName("my cat name");
newCat.setLastUpdatedDate(new Timestamp(new Date().getTime()));
newCat.setParent(new Integer(1));
newCat.setSequence(new Integer(1));
Session session = HibernateUtil.getSessionfactory().getCurrentSession();
try {
session.beginTransaction();
// user.setUserId(new Long(2));
session.save(newCat);
session.getTransaction().commit();
} finally {
session.close();
}
}
Thi is based on accessing a MySQL database.
Any help would be appreciated, I have been unable to find anything that can help me around and I am brand new to Hibernate so beginning to thinking switching back to DAO pattern using native sql with ehcache might be the best thing to do....
Thanks
Matt
I believe that you are getting a RuntimeException from the createQuery call because you are mixing SQL names with HQL names. I assume that your table is named category and that the is_parent column is a field in that table. If you want to use an HQL query, you need to use the name of the property on the Category entity, namely parent, instead of is_parent.

Categories