-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 posts ] 
Author Message
 Post subject: Not getting latest records using session.createSQLQuery()...
PostPosted: Tue Oct 06, 2009 9:39 am 
Newbie

Joined: Tue Oct 06, 2009 8:51 am
Posts: 2
My problem is --
1. I have a button "View List" on a JSP by clicking it I am displaying records in a select box.Data is coming from let say Table1.
2. I am inserting records into same Table1.
3. Now again If I click on "View List" this time newly inserted record is not coming in the. My code details are as follows:

A) To Insert records in the Table1 : I am using following code:

public static void logTestExecutionStatus(JUnitExecutionStatusDTO jexecDto) {
// TODO Auto-generated method stub
Session session = null;
Transaction transaction = null;
try
{

session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
TestExecution testExecution = new TestExecution();
testExecution.setTestSuitId(jexecDto.getTestSuitId());
testExecution.setExecutionStartTime(jexecDto.getExecutionStartTime());
testExecution.setExecutionEndTime(jexecDto.getExecutionEndTime());
testExecution.setExecutionFlag(jexecDto.getExecutionFlag());
session.saveOrUpdate(testExecution);
transaction.commit();

}
catch(Exception e)
{
transaction.rollback();
e.printStackTrace();
}
finally
{
session.close();
}

}

B) To fetching records from Table1 : I am using following code :


public static List fetchAllTestSuitesForTestReports(){

List testSuiteList = new ArrayList();
Session session = null;
SessionFactory sessionFactory = null;
try{
session = HibernateUtil.getSessionFactory().openSession();
JUnitTestSuiteDTO jTestSuiteDto = new JUnitTestSuiteDTO();

Query query = session.createSQLQuery(JUnitSQLQuery.VIEW_ALL_TESTSUITE);

List evnt = query.list();
for (Iterator iterator = evnt.iterator(); iterator.hasNext();) {
Object[] object = (Object[]) iterator.next();
jTestSuiteDto = new JUnitTestSuiteDTO();
//jTestSuiteDto.setTestSuiteID(Long.valueOf( ((Integer)object[0]).toString() ));
jTestSuiteDto.setTestExecutionId(Long.valueOf( ((Integer)object[1]).toString() ));
jTestSuiteDto.setTestSuiteName((String)object[2]);
jTestSuiteDto.setTestSuitAndExeID((String)object[3]);
jTestSuiteDto.setCreatedOn((Date)object[4]);
testSuiteList.add(jTestSuiteDto);
}
}catch(Exception e){
e.printStackTrace();
}finally{
session.close();
}
return testSuiteList;
}



public static String VIEW_ALL_TESTSUITE = " select tsd.test_suit_id, t.test_exe_id," +
" CONCAT(tsd.test_suit_name, ' --> ', t.exe_start_time ) as suite_name," +
" CONCAT(tsd.test_suit_id, ':', t.test_exe_id ) as suite_id, tsd.DATE_CREATED" +
" from" +
" test_suit_details tsd, test_suit_execution_status t" +
" where" +
" tsd.deleted_flag IS NULL and tsd.test_suit_id = t.test_suite_id";

C) My hibernate-cfg.xml is as follows.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/junit_generator_v1</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="com/jUnitFramework/classes/egs/data/MethodTestcaseDetails.hbm.xml" />
<mapping resource="com/jUnitFramework/classes/egs/data/TestSuitExeReport.hbm.xml" />
<mapping resource="com/jUnitFramework/classes/egs/data/MethodArgument.hbm.xml" />
<mapping resource="com/jUnitFramework/classes/egs/data/ArgumentData.hbm.xml" />
<mapping resource="com/jUnitFramework/classes/egs/data/TestSuitDetails.hbm.xml" />
<mapping resource="com/jUnitFramework/classes/egs/data/PackageDetails.hbm.xml" />
<mapping resource="com/jUnitFramework/classes/egs/data/TestReport.hbm.xml" />
<mapping resource="com/jUnitFramework/classes/egs/data/ClassDetails.hbm.xml" />
<mapping resource="com/jUnitFramework/classes/egs/data/MethodDetails.hbm.xml" />
<mapping resource="com/jUnitFramework/classes/egs/data/TestExecution.hbm.xml" />
</session-factory>

</hibernate-configuration>


I tried some properties like :
<property name="hibernate.cache.use_query_cache">false</property>
<property name="hibernate.cache.use_second_level_cache">false</property>

in hibernate-cfg.xml to disable querycache and second level cache as I thought hibernate is doing querycache thats why latest record is not coming but not able to resolve the problem.
I am using hibernate3.

Please help me out to resolve this problem.

-Ram Shukla


Top
 Profile  
 
 Post subject: Re: Not getting latest records using session.createSQLQuery()...
PostPosted: Tue Oct 06, 2009 11:34 pm 
Newbie

Joined: Tue Oct 06, 2009 11:15 pm
Posts: 3
I am having almost the exact same problem!

IDE: Rational Software Architect for websphere portal v7.5
Server: WebSphere portal v6.1

I set up a JDBC datasource in the admin console that uses a type 4 connection to a remote DB2 database.

I am using JPA annotations. I am injecting the entity manager into my bean that is running in a JSR 286 JSF portlet with request scope. I have a onetomany relationship from Parent to Child, such that a Parent can have many children.
Code:
@Repository
@Transactional
public class JpaParentChildDao implements ParentChildDao {

    //since we are obtaining the entity manager via dependency injection we should not explicitly
    //call close or a runtime exception will result.
    @PersistenceUnit(unitName="PU")
    private EntityManagerFactory m_entityManagerFactory;
    private EntityManager m_entityManager;
   
    private EntityManager getEntityManager(){
        if(this.m_entityManager == null){
            this.m_entityManager = this.m_entityManagerFactory.createEntityManager();
        }
        return this.m_entityManager;
    }
   
    public List<ParentChildren> getItems(int firstItem, int batchSize) {
        EntityManager entityManager = getEntityManager();

        List<ParentChildren> items = null;
       
        //For some reason q1 must be run for q2 to succeed.
        //even though we don't store the result or do anything with it???
        Query q1 = entityManager.createQuery(
                "select parent, child "+
                "from Parent parent " +
                "inner join parent.m_children as child "
                );
       
        q1.setMaxResults(batchSize);
        q1.setFirstResult(firstItem);
        q1.getResultList();
       
        //The point of query 2 is to have a strongly typed query.
        //oddly it will not work without q1 happening first.
        Query q2 = entityManager.createQuery(
                "select new ParentChild(parent, child) "+
                "from Parent parent " +
                "inner join parent.children as child "
            );
               
        q2.setMaxResults(batchSize);
        q2.setFirstResult(firstItem);
       
       
        return q2.getResultList();
    }

// other methods etc...

}



My persistence.xml

Code:
?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <persistence-unit name="PU" transaction-type="RESOURCE_LOCAL">

        <non-jta-data-source>jdbc/Foo</non-jta-data-source>
        <class>Parent</class>
        <class>Child</class>
       
        <properties >
            <!-- cache configuration -->
            <!-- If i uncomment the following it complains that i do not have 2nd-level caching enabled. -->
            <!-- <property name="hibernate.ejb.classcache.Parent" value="read-write"/>-->
           
            <!-- I am not sure if this is the correct way to set query cache to false -->
            <property name="hibernate.cache.use_query_cache" value="false" />
        </properties>
   </persistence-unit>
</persistence>



My application.xml

Code:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
   

    <!-- This is referenced as a managed-property inside a managed bean with request scope in my faces-config.xml -->
    <bean id="parentChildDao" class="JpaParentChildDao" />

    <!--
        Create the JPA EntityManagerFactory
        @see http://static.springframework.org/spring/docs/2.1.x/reference/orm.html#orm-jpa-setup-lcemfb
            http://static.springframework.org/spring/docs/2.1.x/api/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBean.html
     -->     
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="PU"/>
       
        <!-- <property name="dataSource" ref="dataSource"/>-->
        <property name="loadTimeWeaver">
            <!-- <bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver"/>-->
            <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
        </property>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true"/>
                <property name="generateDdl" value="false"/>
                <property name="database" value="DB2"/>
                <!-- See https://www.hibernate.org/hib_docs/v3/api/org/hibernate/dialect/DB2390Dialect.html -->
                <property name="databasePlatform" value="org.hibernate.dialect.DB2390Dialect"/>
            </bean>
        </property>
    </bean>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver"/>
       
        <property name="url" value="jdbc:db2://somedomain.com:50000/DB2FOO"/>
        <property name="username" value="xxxx"/>
        <property name="password" value="1234"/>
    </bean>     
   
    <!-- Process @PersistenceContext to inject entity manager factory
        @see http://static.springframework.org/spring/docs/2.1.x/reference/orm.html#orm-jpa-straight
            http://static.springframework.org/spring/docs/2.1.x/api/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.html
    -->
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
        <!-- <property name="dataSource" ref="dataSource"/>-->
    </bean>   
    <tx:annotation-driven />   
    <bean name="myDummyController" class="MyDummyView" scope="request">
        <property name="parentChildDao">
            <ref bean="parentChildDao"/>
        </property>
    </bean>
</beans>


I have a JSP page that contains a table that has a value attribute set to a collection from a backing bean that is set from the result returned by getItems. I can page through all of the data just fine. I Have an ajax refresh button which reloads the collection that the table pages through by calling getitems again. If i change a field value of one of the records (directly via winsql) and subsequently refresh the table, I can see that getitems gets called and that hibernate generates the sql from my query and fetches the results, but the results do not reflect the recent change to the table. Logging out and logging back in also does not cause the query to fetch the recent results. The only thing that allows the portlet to get the latest results is restarting websphere portal server. I have been reading up on session cacing, query cacing and second-level caching. I do not have any of these caching options configured.

At first I thought that this was a WebSphere portal issue, but then I started reading about query cache in hibernate and thought that this may be the cause. Now I have no idea.

Offtopic: does anyone have a clue as to why q1 must be called before q2? See getItems code above.

Sincerely,
bugincode


Top
 Profile  
 
 Post subject: Re: Not getting latest records using session.createSQLQuery()...
PostPosted: Wed Oct 07, 2009 7:57 pm 
Newbie

Joined: Tue Oct 06, 2009 11:15 pm
Posts: 3
I found a solution that works for me.
I found that I had to call this.m_entityManager.clear(); before making the query. I have not yet read up on exactly what clear does. I am assuming that it is calling clear on an internal collection. I am assuming that this collection is probably a cache of query results. I find it odd that such a cache would exist, since I have not turned on query cache. Can anyone explain the correct way for us to get the behaviour that we are looking for? If not calling clear means that the results will be returned from a cache, but the query cache functionality is turned off, then I do not understand the thinking behind such an implemintation.

Oohh.. I hope the above is readable. I have been getting very little sleep for over a month now.

Sincerely,

bugincode.


Top
 Profile  
 
 Post subject: Re: Not getting latest records using session.createSQLQuery()...
PostPosted: Fri Oct 09, 2009 10:01 am 
Newbie

Joined: Tue Oct 06, 2009 11:15 pm
Posts: 3
Okay, so I have done a lot more research on this issue and i have discovered the proper solution. calling clear on the entity manager worked, but it is certainly not the proper solution. I found that with the above configuraiton none of my entities were being persisted, even if I explicitly called persist from the entitymanager, which I should not have to do while using jpa in this way. What i found is that since my bean is request scoped, and I require attached entities accross multiple requests, I must create a persistence context that is of type extended if this is to work with a container managed entity manager. So, to make it so that i no longer had to call

Code:
m_entityManager.clear()

I changed
Code:
@PersistenceUnit(unitName="PU")
    private EntityManagerFactory m_entityManagerFactory;
    private EntityManager m_entityManager;

to
Code:
@PersistenceContext(unitName = "PU", type = PersistenceContextType.EXTENDED)
   private EntityManager m_entityManager;
and got rid of the EntityManagerFactory all together. Note that if you use the EntityManagerFactory to create a entity manager then you are creating an application type entity manager, which is not what i wanted in this case.

I hope that helps.


Top
 Profile  
 
 Post subject: Re: Not getting latest records using session.createSQLQuery()...
PostPosted: Mon Oct 12, 2009 2:43 am 
Newbie

Joined: Tue Oct 06, 2009 8:51 am
Posts: 2
Hi,
I am getting probelm while I am using hibernate APIs for native query.I am getting stale data.
Probelm statement is:
1. Let say I have two table : Table1 and Table2
2. In jsp I have two buttons: "Insert" and "Show List"
3. For example let say both table have 2 rows and if I click on "Show List" it is fetching data using hibernate native query API's so at this point it is showing two records thats fine for me.
4. Now if I click on "Insert" button it is inserting 1 record in both the table (Table1 and Table2).
5. Now I check into the database both the tables are updated with new inserted record, and at this point if I click on "Show List" button then it is fetching only 2 records not the third one which is inserted recently.
6. To fetching data from Table1 and Table2 I am using session.createSQLQuery("QueryString").
here I am using simple join in SQL Query.
7. This problem I am getting if I use joins in sql query for single table it is working fine.I am not able to resolve this problem.

Code details:

Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
      "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/junit_generator_v1</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.cache.use_query_cache">false</property>
        <property name="hibernate.cache.use_second_level_cache">false</property>
        <mapping resource="com/jUnitFramework/classes/egs/data/MethodTestcaseDetails.hbm.xml" />
        <mapping resource="com/jUnitFramework/classes/egs/data/TestSuitExeReport.hbm.xml" />
        <mapping resource="com/jUnitFramework/classes/egs/data/MethodArgument.hbm.xml" />
        <mapping resource="com/jUnitFramework/classes/egs/data/ArgumentData.hbm.xml" />
        <mapping resource="com/jUnitFramework/classes/egs/data/TestSuitDetails.hbm.xml" />
        <mapping resource="com/jUnitFramework/classes/egs/data/PackageDetails.hbm.xml" />
        <mapping resource="com/jUnitFramework/classes/egs/data/TestReport.hbm.xml" />
        <mapping resource="com/jUnitFramework/classes/egs/data/ClassDetails.hbm.xml" />
        <mapping resource="com/jUnitFramework/classes/egs/data/MethodDetails.hbm.xml" />
          <mapping resource="com/jUnitFramework/classes/egs/data/TestExecution.hbm.xml" />
    </session-factory>
   
</hibernate-configuration>



Code:
/*
* Created on Oct 7, 2009
*
* To change the template for this generated file go to
* Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
*/
package com.jUnitFramework.classes.egs.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
* @author ramranjan.shukla
*
* To change the template for this generated type comment go to
* Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
*/
public class HibernateSession {
   
   private static SessionFactory sessionFactory;
   public static final ThreadLocal session = new ThreadLocal();
   
   public static Session currentSession()
      throws HibernateException {

     Session s = (Session) session.get();
     if (s == null) {

      // Don't get from JNDI, use a static SessionFactory
      if (sessionFactory == null) {

         // Use default hibernate.cfg.xml
         sessionFactory = new Configuration().configure().buildSessionFactory();

      }

       s = sessionFactory.openSession();
       session.set(s);
     }
     return s;
   }

   public static void closeSession()
      throws HibernateException {
       
      Session s = (Session) session.get();
      session.set(null);
      if (s != null) s.close();
   }
   
}




Code:
Here is my DAO Code:
/**
    * This method will fetch all the existing test suite id and name to be displayed for update or viewing purposes
    *
    * @return List of JUnitTestSuiteDTO objects containing only test suite id and test suite name
    */
   public static List fetchAllTestSuitesForTestReports(){
   
   List testSuiteList = new ArrayList();
   Session session = null;
   
   try{


   session = HibernateSession.currentSession();
   session.beginTransaction();
   session.flush();
   session.clear();
   JUnitTestSuiteDTO jTestSuiteDto = new JUnitTestSuiteDTO();
   //session.setCacheMode(CacheMode.IGNORE);
   session.setFlushMode(FlushMode.AUTO);
   session.setCacheMode(CacheMode.REFRESH);
   if((session instanceof SessionImpl)){       
      ((SessionImpl)session).setAutoClear(true);
   }
         
   Query query = session.createSQLQuery(JUnitSQLQuery.VIEW_ALL_TESTSUITE).setCacheable(false);
   query.setCacheMode(CacheMode.REFRESH);
   query.setFlushMode(FlushMode.AUTO);
   List evnt = query.list();
   for (Iterator iterator = evnt.iterator(); iterator.hasNext();) {
      Object[] object = (Object[]) iterator.next();
      jTestSuiteDto = new JUnitTestSuiteDTO();
      //jTestSuiteDto.setTestSuiteID(Long.valueOf( ((Integer)object[0]).toString() ));
      jTestSuiteDto.setTestExecutionId(Long.valueOf( ((Integer)object[1]).toString() ));
      jTestSuiteDto.setTestSuiteName((String)object[2]);
      jTestSuiteDto.setTestSuitAndExeID((String)object[3]);
      jTestSuiteDto.setCreatedOn((Date)object[4]);
      testSuiteList.add(jTestSuiteDto);
   }
   session.getTransaction().commit();
   }catch(Exception e){
      e.printStackTrace();
   }finally{
      //session.close();
      //sessionFactory.close();
         
      session.disconnect();
      try {
         session.connection().close();
      } catch (HibernateException e1) {
   
         e1.printStackTrace();
      } catch (SQLException e1) {
      
         e1.printStackTrace();
      }
   HibernateSession.closeSession();
   }
return testSuiteList;
}

Query String:

public static String VIEW_ALL_TESTSUITE = "   select tsd.test_suit_id, t.test_exe_id," +
      " CONCAT(tsd.test_suit_name, ' --> ', t.exe_start_time ) as suite_name," +
      " CONCAT(tsd.test_suit_id, ':',  t.test_exe_id ) as suite_id, tsd.DATE_CREATED" +
      "   from" +
      "   test_suit_details tsd,   test_suit_execution_status t" +
      "   where" +
      "   tsd.deleted_flag IS NULL   and tsd.test_suit_id = t.test_suite_id";



Please help me out to resolve this problem.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.