Hibernate : load and

Posted by Albert Kam on Stack Overflow See other posts from Stack Overflow or by Albert Kam
Published on 2010-12-31T06:43:16Z Indexed on 2010/12/31 6:53 UTC
Read the original article Hit count: 723

Filed under:
|

According to the tutorial : http://jpa.ezhibernate.com/Javacode/learn.jsp?tutorial=27hibernateloadvshibernateget,

If you initialize a JavaBean instance with a load method call, you can only access the properties of that JavaBean, for the first time, within the transactional context in which it was initialized.

If you try to access the various properties of the JavaBean after the transaction that loaded it has been committed, you'll get an exception, a LazyInitializationException, as Hibernate no longer has a valid transactional context to use to hit the database.

But with my experiment, using hibernate 3.6, and postgres 9, it doesnt throw any exception at all. Am i missing something ?

Here's my code :

import org.hibernate.Session;


public class AppLoadingEntities {
    /**
    * @param args
    */
    public static void main(String[] args) {
        HibernateUtil.beginTransaction();
        Session session = HibernateUtil.getSession();

        EntityUser userFromGet = get(session);
        EntityUser userFromLoad = load(session);

        // finish the transaction
        session.getTransaction().commit();

        // try fetching field value from entity bean that is fetched via get outside transaction, and it'll be okay
        System.out.println("userFromGet.getId() : " + userFromGet.getId());
        System.out.println("userFromGet.getName() : " + userFromGet.getName());

        // fetching field from entity bean that is fetched via load outside transaction, and it'll be errornous
        // NOTE : but after testing, load seems to be okay, what gives ? ask forums
        try {
            System.out.println("userFromLoad.getId() : " + userFromLoad.getId());
            System.out.println("userFromLoad.getName() : " + userFromLoad.getName());
        } catch(Exception e) {
            System.out.println("error while fetching entity that is fetched from load : " + e.getMessage());
        }
    }

    private static EntityUser load(Session session) {
        EntityUser user = (EntityUser) session.load(EntityUser.class, 1l);
        System.out.println("user fetched with 'load' inside transaction : " + user);
        return user;
    }

    private static EntityUser get(Session session) {
        // safe to set it to 1, coz the table got recreated at every run of this app
        EntityUser user = (EntityUser) session.get(EntityUser.class, 1l);
        System.out.println("user fetched with 'get' : " + user);
        return user;
    }

}

And here's the output :

88 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
93 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.6.0.Final
94 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
96 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
98 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
139 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
139 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
172 [main] WARN org.hibernate.util.DTDEntityResolver - recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
191 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
237 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: EntityUser
263 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity EntityUser on table MstUser
293 [main] INFO org.hibernate.cfg.Configuration - Hibernate Validator not found: ignoring
296 [main] INFO org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
300 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
300 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20
300 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false
309 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: org.postgresql.Driver at URL: jdbc:postgresql://localhost:5432/hibernate
309 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=sofco, password=****}
354 [main] INFO org.hibernate.cfg.SettingsFactory - Database ->
       name : PostgreSQL
    version : 9.0.1
      major : 9
      minor : 0
354 [main] INFO org.hibernate.cfg.SettingsFactory - Driver ->
       name : PostgreSQL Native Driver
    version : PostgreSQL 9.0 JDBC4 (build 801)
      major : 9
      minor : 0
372 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.PostgreSQLDialect
382 [main] INFO org.hibernate.engine.jdbc.JdbcSupportLoader - Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
383 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Transaction strategy: org.hibernate.transaction.JDBCTransactionFactory
384 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
384 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
384 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
384 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
384 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
384 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
384 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
384 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto
385 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
385 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
385 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
385 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
385 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
385 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
385 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
385 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled
385 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
385 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled
385 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
386 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
386 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
388 [main] INFO org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout
389 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled
389 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
389 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
389 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled
389 [main] INFO org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): enabled
402 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
549 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
Hibernate: select entityuser0_.id as id0_0_, entityuser0_.name as name0_0_, entityuser0_.password as password0_0_ from MstUser entityuser0_ where entityuser0_.id=?
user fetched with 'get' : 1:Albert Kam xzy:abc
user fetched with 'load' inside transaction : 1:Albert Kam xzy:abc
userFromGet.getId() : 1
userFromGet.getName() : Albert Kam xzy
userFromLoad.getId() : 1
userFromLoad.getName() : Albert Kam xzy

© Stack Overflow or respective owner

Related posts about java

Related posts about hibernate