Search This Blog

Tuesday 22 July 2014

Configuration of Hibernate session factory and JPA entity manager factory – in standalone and spring applications:




Configuration of Hibernate session factory and JPA entity manager factory – in standalone and spring applications:
 




Note: Place “hibernate.cfg.xml”,“persistence.xml” and etc configuration files under class path.


Creating session factory using Configuration class in standalone application:

private static final SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
        } catch (Throwable exception) {
            System.err.println("Initial SessionFactory creation failed." + exception);
            throw new ExceptionInInitializerError(exception);
        }
    }

Creating session factory using LocalSessionFactoryBean in spring application:

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test_db" />
        <property name="username" value="root" />
        <property name="password" value="root1" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
    </bean>

Creating JPA Entity Manager Factory in standalone application:

        EntityManagerFactory entityManagerFactory=Persistence.createEntityManagerFactory("PersistenceUnitName");
        EntityManager entityManager=entityManagerFactory.createEntityManager();

Creating JPA Entity Manager Factory using LocalContainerEntityManagerFactoryBean in spring application:

        <bean
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        id="entityManagerFactory">
        <property name="dataSource"> <ref local="dataSource" /></property>
    </bean>

        <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test_db" />
        <property name="username" value="root" />
        <property name="password" value="root1" />
    </bean>

No comments:

Post a Comment