Announcement Announcement Module
Collapse
No announcement yet.
Spring and Hibernate Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring and Hibernate

    I'm trying to integrate Spring and Hibernate.

    package tradeservice;

    import java.sql.SQLException;
    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.springframework.orm.hibernate.HibernateCallbac k;
    import org.springframework.orm.hibernate.HibernateTemplat e;

    public class BookDao {

    private HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate){
    this.hibernateTemplate = hibernateTemplate;
    }

    public HibernateTemplate getHibernateTemplate(){
    return hibernateTemplate;
    }

    public Book getBook(final int id){
    HibernateCallback callback = new HibernateCallback() {
    public Object doInHibernate(Session session)
    throws HibernateException,SQLException {
    return session.load(Book.class, id);
    }
    };
    return (Book)hibernateTemplate.execute(callback);
    }


    public void saveOrUpdate(final Book book){
    HibernateCallback callback = new HibernateCallback() {
    public Object doInHibernate(Session session)
    throws HibernateException,SQLException {
    session.saveOrUpdate(book);
    return null;
    }
    };
    hibernateTemplate.execute(callback);
    }
    }

    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

    <hibernate-mapping>
    <class name="tradeservice.Book" table="book">
    <id name="id" column="idBook">
    <generator class="increment"/>
    </id>
    <property name="bookName" column="BookName"/>
    </class>
    </hibernate-mapping>

    package tradeservice;

    import org.springframework.beans.factory.BeanFactory;
    import org.springframework.beans.factory.xml.XmlBeanFacto ry;
    import org.springframework.core.io.FileSystemResource;
    import org.springframework.core.io.Resource;
    import org.springframework.orm.hibernate3.LocalSessionFac toryBean;

    public class SpringHibernateTest {

    public static void main(String[] args) {

    Resource resource = new FileSystemResource("src/spring-hibernate.xml");
    BeanFactory factory = new XmlBeanFactory(resource);

    Book objBook = new Book();
    objBook.setId(123);
    objBook.setBookName("ABC");

    BookDao bookDao = (BookDao)factory.getBean("bookDao");
    bookDao.saveOrUpdate(objBook);

    Book bookResult = bookDao.getBook(123);
    System.out.println(bookResult);
    }
    }

    <?xml version="1.0" encoding="UTF-8"?>

    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" >
    <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDrive r"/>
    <property name="url" value="jdbc:sqlserver://GBLOND088SFL\SQLSERVER2005;DatabaseName=TradeServi ce;SelectMethod=cursor"/>
    <property name="username" value="root"/>
    <property name="password" value="pwForRoot"/>
    <property name="username">tradeservice</property>
    <property name="password">abnamro1</property>
    <property name="autocommit">true</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.SQLServerDial ect</property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>

    <!-- Disable the second-level cache -->
    <property name="cache.provider_class">org.hibernate.cache.No CacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <!--<property name="hbm2ddl.auto">create</property>-->
    </bean>

    <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSes sionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="mappingResources">
    <value>tradeservice/Book.hbm.xml</value>
    </property>
    <property name="hibernateProperties">
    <value>hibernate.dialect=org.hibernate.dialect.HSQ LDialect</value>
    </property>
    </bean>

    <bean id="hibernateTemplate"
    class="org.springframework.orm.hibernate3.Hibernat eTemplate">
    <property name="sessionFactory">
    <ref bean="mySessionFactory"/>
    </property>
    </bean>

    <bean id="bookHibernate" class="tradeservice.Book">
    <property name="hibernateTemplate">
    <ref bean="hibernateTemplate"/>
    </property>
    </bean>

    </beans>

    Above are my files. But I'm getting the following error.

    [javac] Compiling 6 source files to C:\Hibernate\bin
    [javac] C:\Hibernate\src\tradeservice\BookDao.java:6: package org.springframework.orm.hibernate does not exist
    [javac] import org.springframework.orm.hibernate.HibernateCallbac k;
    [javac] ^
    [javac] C:\Hibernate\src\tradeservice\BookDao.java:7: package org.springframework.orm.hibernate does not exist
    [javac] import org.springframework.orm.hibernate.HibernateTemplat e;
    [javac] ^
    [javac] C:\Hibernate\src\tradeservice\BookDao.java:11: cannot find symbol
    [javac] symbol : class HibernateTemplate
    [javac] location: class tradeservice.BookDao
    [javac] private HibernateTemplate hibernateTemplate;
    [javac] ^
    [javac] C:\Hibernate\src\tradeservice\BookDao.java:13: cannot find symbol
    [javac] symbol : class HibernateTemplate
    [javac] location: class tradeservice.BookDao
    [javac] public void setHibernateTemplate(HibernateTemplate hibernateTemplate){
    [javac] ^
    [javac] C:\Hibernate\src\tradeservice\BookDao.java:17: cannot find symbol
    [javac] symbol : class HibernateTemplate
    [javac] location: class tradeservice.BookDao
    [javac] public HibernateTemplate getHibernateTemplate(){
    [javac] ^
    [javac] C:\Hibernate\src\tradeservice\SpringHibernateTest. java:3: package org.springframework.beans.factory does not exist
    [javac] import org.springframework.beans.factory.BeanFactory;
    [javac] ^
    [javac] C:\Hibernate\src\tradeservice\SpringHibernateTest. java:4: package org.springframework.beans.factory.xml does not exist
    [javac] import org.springframework.beans.factory.xml.XmlBeanFacto ry;
    [javac] ^
    [javac] C:\Hibernate\src\tradeservice\SpringHibernateTest. java:5: package org.springframework.core.io does not exist
    [javac] import org.springframework.core.io.FileSystemResource;
    [javac] ^
    [javac] C:\Hibernate\src\tradeservice\SpringHibernateTest. java:6: package org.springframework.core.io does not exist
    [javac] import org.springframework.core.io.Resource;
    [javac] ^
    [javac] C:\Hibernate\src\tradeservice\SpringHibernateTest. java:7: package org.springframework.orm.hibernate3 does not exist
    [javac] import org.springframework.orm.hibernate3.LocalSessionFac toryBean;
    [javac] ^
    [javac] C:\Hibernate\src\tradeservice\BookDao.java:22: cannot find symbol
    [javac] symbol : class HibernateCallback
    [javac] location: class tradeservice.BookDao
    [javac] HibernateCallback callback = new HibernateCallback() {
    [javac] ^
    [javac] C:\Hibernate\src\tradeservice\BookDao.java:22: cannot find symbol
    [javac] symbol : class HibernateCallback
    [javac] location: class tradeservice.BookDao
    [javac] HibernateCallback callback = new HibernateCallback() {
    [javac] ^
    [javac] C:\Hibernate\src\tradeservice\BookDao.java:33: cannot find symbol
    [javac] symbol : class HibernateCallback
    [javac] location: class tradeservice.BookDao
    [javac] HibernateCallback callback = new HibernateCallback() {
    [javac] ^
    [javac] C:\Hibernate\src\tradeservice\BookDao.java:33: cannot find symbol
    [javac] symbol : class HibernateCallback
    [javac] location: class tradeservice.BookDao
    [javac] HibernateCallback callback = new HibernateCallback() {
    [javac] ^
    Total time: 2 seconds

    I've included spring.jar and spring-hibernate.jar in the classpath.

    Can anyone pls help.

    Thnx in advance.

    Cheers
    aaa

  • #2
    Please use [ code][/code ] tags when posting code, that way it remains readable.

    1) Use an FileSystemXmlApplicationContext instead of a BeanFactory
    2) Don't use HibernateTemplate but use the SessionFactory directly (that is the recommended approach.
    3) Don't include spring-hibernate.jar it is already in the spring.jar
    4) Why are you setting hibernate properties on your datasource
    5) don't set the current_session_context_class, only set that in the case of JTA.
    6) Configure a HibernateTransactionManager

    If you are using spring 2.0/2.5 there is no o.s.o.hibernate package there is a o.s.o.hibernate3 package!
    Last edited by Marten Deinum; May 14th, 2008, 11:43 AM.

    Comment


    • #3
      Integration of Spring and Hibernate

      Hi All,

      I'm very new to Hibernate and Spring. I'm using hibernate-3.2 and spring-framework-2.0.7. My db is SQLServer 2005. I've a small application which tries to insert 2 columns (Id and BookName) into a Table BOOK.

      I was able to insert data using hibernate. Now I want to use spring also. Pls find my code below.

      <CODE>

      -----------------
      hibernate.cfg.xml
      -----------------

      <?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>
      <!-- Database connection settings -->
      <property name="connection.driver_class">com.microsoft.sqlse rver.jdbc.SQLServerDriver </property>
      <property name="connection.url">jdbc:sqlserver://GBLOND088SFL\SQLSERVER2005;DatabaseName=TradeServi ce;SelectMethod=cursor</property>
      <property name="connection.username">tradeservice</property>
      <property name="connection.password">abnamro1</property>
      <property name="connection.autocommit">true</property>

      <!-- JDBC connection pool (use the built-in) -->
      <property name="connection.pool_size">1</property>

      <!-- SQL dialect -->
      <property name="dialect">org.hibernate.dialect.SQLServerDial ect</property>

      <!-- Enable Hibernate's automatic session context management -->
      <property name="current_session_context_class">thread</property>

      <!-- Disable the second-level cache -->
      <property name="cache.provider_class">org.hibernate.cache.No CacheProvider</property>

      <!-- Echo all executed SQL to stdout -->
      <property name="show_sql">true</property>

      <!-- Drop and re-create the database schema on startup -->
      <!--<property name="hbm2ddl.auto">create</property>-->

      <!-- Mapping file -->
      <mapping resource="tradeservice/Book.hbm.xml"/>

      </session-factory>

      </hibernate-configuration>

      ------------
      Book.hbm.xml
      ------------

      <?xml version="1.0"?>
      <!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

      <hibernate-mapping>
      <class name="tradeservice.Book" table="book">
      <id name="id" column="idBook">
      <generator class="increment"/>
      </id>
      <property name="bookName" column="BookName"/>
      </class>
      </hibernate-mapping>

      ---------
      Book.java
      ---------

      package tradeservice;

      // Class for the BOOK table

      public class Book{
      private int id;
      private String bookName;

      public Book(){
      }

      public int getId() {
      return id;
      }

      public void setId(int id) {
      this.id = id;
      }

      public String getBookName() {
      return bookName;
      }

      public void setBookName(String strBookName){
      this.bookName = strBookName;
      }
      }

      ------------------
      HibernateUtil.java
      ------------------

      package util;

      import org.hibernate.*;
      import org.hibernate.cfg.*;

      public class HibernateUtil
      {

      private static final SessionFactory sessionFactory;

      static
      {
      try
      {
      // Create the SessionFactory from hibernate.cfg.xml
      sessionFactory = new Configuration().configure().buildSessionFactory();
      }
      catch (Throwable ex)
      {
      // Make sure you log the exception, as it might be swallowed
      System.err.println("Initial SessionFactory creation failed." + ex);
      throw new ExceptionInInitializerError(ex);
      }
      }

      public static SessionFactory getSessionFactory()
      {
      return sessionFactory;
      }

      }

      -------------------------------
      My main class TradeManager.java
      -------------------------------

      package tradeservice;

      //Importing the required packages

      import org.hibernate.Session;
      import java.util.List;
      import java.util.Date;
      import util.HibernateUtil;

      //Main class

      public class TradeManager {

      public static void main(String[] args) {

      TradeManager mgr = new TradeManager();
      mgr.createAndStoreEvent("Book");
      HibernateUtil.getSessionFactory().close();
      }

      // Method to store data into DB

      private void createAndStoreEvent(String strTable) {

      // Creating the session

      Session session = HibernateUtil.getSessionFactory().getCurrentSessio n();
      session.beginTransaction();

      // Inserting into the BOOK table

      if(strTable.equalsIgnoreCase("Book")){
      System.out.println("Inside BOOK");
      Book objBook = new Book();
      objBook.setBookName("AA pricing");
      System.out.println("SAVINGGGG");
      session.save(objBook);
      }

      session.getTransaction().commit();
      }
      }


      </CODE>

      The above code is working fine with hibernate. Now when I try to use spring also I've done the following.

      1) Created spring-hibernate.xml

      --------------------
      spring-hibernate.xml
      --------------------

      <?xml version="1.0" encoding="UTF-8"?>

      <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

      <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" >
      <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDrive r"/>
      <property name="url" value="jdbc:sqlserver://GBLOND088SFL\SQLSERVER2005;DatabaseName=TradeServi ce;SelectMethod=cursor"/>
      <property name="username" value="tradeservice"/>
      <property name="password" value="abnamro1"/>
      </bean>

      <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSes sionFactoryBean">
      <property name="dataSource" ref="myDataSource"/>
      <property name="mappingResources">
      <value>tradeservice/Book.hbm.xml</value>
      </property>
      </bean>

      </beans>


      I've the following doubts. It may be very silly to you experts but I dont have no other option other than posting here

      1) As I've given the db connection details here can I delete those from hibernate.cfg.xml?
      2) I tried the above part but I was getting the error "hibernate config file is missing and should have a db connection defined".
      3) Do I need to change the java files or can I keep my old code?
      4) I dont understand the link between the spring and hibernate

      Pls help. Any help will be highly appreciated.

      Thnx in advance.

      Cheers,
      aaa

      Comment

      Working...
      X