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();
}
Related
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();
}
}
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();
}
}
I'm trying to write DAOs for my database models using the transaction pattern like such,
Session session = null;
Transaction tx = null;
try{
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
tx.setTimeout(5);
//doSomething(session);
tx.commit();
}catch(RuntimeException e){
try{
tx.rollback();
}catch(RuntimeException rbe){
log.error("Couldn’t roll back transaction", rbe);
}
throw e;
}finally{
if(session!=null){
session.close();
}
}
What's a good approach to encapsulate this pattern in a method with
//doSomething(session);
as an argument to be performed as part of the transaction? Sometimes I run a query, sometimes I operate on session.saveOrUpdate, etc. I have many DAOs to write and this pattern of code duplication is bothering me.
EDIT
Is there a direct mapping between session operations and HQL (saveOrUpdate, delete, etc) so all I need to pass into this method is just a query?
Thanks for the insights.
Something like this might be what you're after
public void doSomething(MyQuery myQuery) {
...
Transaction tx = null;
try {
...
myQuery.execute(tx);
...
} catch (...) {
} finally {
}
}
public class MyQuery {
public void execute(Transaction tx) {
// run queries on transaction
}
}
Either create a new MyQuery instance or a new MyQuery subclass for each query or set of queries you want to execute
I have way too many threads being used. I keep running out of memory in my unit tests. Do I need to close my session if I'm using sessionFactory. Won't the commit below end the session?
Session session = sessionFactory.getCurrentSession();
Transaction transaction = null;
try
{
transaction = session.beginTransaction();
transaction.commit();
}
catch (Exception e)
{
if (transaction != null)
{
transaction.rollback();
throw e;
}
}
finally
{
//Is this close necessary?
session.close();
}
No, it won't end the session. One session can span any number of transactions. Close the session explicitly. BTW such things are clearly documented.
In yout catch, verify if the transaction isActive() too.
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.