October 13, 2009

Hibernate Spring Tutorial

« Java FTP Example | Main | Spring Velocity Mail »

If you are developing middleware services with the Springframework, in the majority of cases you will make use of the Hibernate framework to realize the database mapping. The following tutorial describes the standard way to use Hibernate in Spring. Two classes are crucial. First the BasicDataSource, which builds up the connections based on JDBC parameters. And the AnnotationSessionFactoryBean class, which references annotated mapping classes and builds up the database sessions. Depending on the JDBC driver you will set the according Hibernate dialect.

1. Define the database mapping classes

@Entity
public class Order {
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;
  public void setId(Long id) {
    this.id = id;
  }
  public Long getId() {
    return this.id;
  }
  private String customer;
  public void setCustomer(String customer) {
    this.customer = customer;
  }
  public String getCustomer() {
    return this.customer;
  }  
  ...
}
2. Define the Spring instrumentalisation.
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver"/>
    <property name="url" value="jdbc:derby:orderdb"/>
    <property name="username" value=""/>
    <property name="password" value=""/>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
    <property name="annotatedClasses">
        <list>
            <value>org.developers.blog.example.dao.Order</value>
            <value>...</value>
        </list>
    </property>
</bean>
Have fun
Rafael

Technorati Tags:

Posted by rafael.sobek at 8:36 PM in Spring

 

[Trackback URL for this entry]

Comment: Alb at Do, 11 Mrz 4:44 PM

It would be nice to complete the example by showing example java code of how to store and retrieve some Orders.

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
« October »
SunMonTueWedThuFriSat
    123
45678910
11121314151617
18192021222324
25262728293031