13 Mart 2008 Perşembe

Adding Spring and Hibernate to Our Hello World JSF Application

In this section we will add Spring and Hibernate Capabilities to our sample web application So for this, we will have to add the spring and hibernate libraries and configuration files to the web application.
So, to integrate Hibernate and Spring frameworks with JSF framework we will have to make some changes and copy jar files related with the individual frameworks.

After downloading spring, hibernate and MySQL then installing MySQL we ready to start this section.

copy dom4j.jar from spring-framework-2.5.1\lib\dom4j directory into lib directory.
copy spring.jar from spring-framework-2.5.1\dist directory into lib directory.
copy jta.jar from spring-framework-2.5.1\lib\j2ee directory into lib directory.
copy servlet-api.jar from spring-framework-2.5.1\lib\j2ee directory into lib directory.
copy hibernate3.jar from hibernate-3.2 directory into lib directory of our application.

Finally here is the list of jar files in our application's lib directory:


In the figure below, you can see additional files and directory structure formed after adding spring and hibernate capabilities to our sample project.




Person.java


package pojo;
public class Person {
Integer id;
String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}


As you see our sample pojo has two attribute id and name. Our aim is to add this pojo to the database triggered by a button in the jsp page. Everything is simple now, we will add other required attributes later.

Person.hbm.xml


Create a hibernate mapping for any pojo that must be persisted. This is defined in another XML file (one per persistent object) which has an hbm.xml extension.

jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sampleproject
jdbc.username=sampleproject
jdbc.password=sampleproject
hibernate.dialect=org.hibernate.dialect.MySQLDialect

We use this property file for connecting database.

spring-context.xml



Welcome.java

faces-config.xml



add tags shown below to web.xml.

In this file;

  • The contextConfigLocation parameter defines the Spring configurations files to load, as shown in the servlet context below. If we wanted to load multiple Spring configuration files, we could use a comma as a delimiter in a tag.
  • ContextLoaderServlet will load the Spring configuration files when you start the Web application.