Examples of JSF 2.0 + spring + hibernate Integration

Source: Internet
Author: User
Examples of JSF 2.0 + spring + hibernate Integration

Here, jsf2.0, spring, and hibernate will be used for integration. At the end of the article, the project will create a JSP page to display a customer object and add an Add button, save the new object entered by the user to the database. PS: the database used in this project is MySQL and the tomcat6 application server.
1. Project Structure

Directory structure of this example

2. Table script

Create a customer table and insert 2 dummy records.

DROP TABLE IF EXISTS `mkyongdb`.`customer`;CREATE TABLE  `mkyongdb`.`customer` (  `CUSTOMER_ID` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,  `NAME` VARCHAR(45) NOT NULL,  `ADDRESS` VARCHAR(255) NOT NULL,  `CREATED_DATE` datetime NOT NULL,  PRIMARY KEY (`CUSTOMER_ID`)) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8; INSERT INTO mkyongdb.customer(customer_id, name, address, created_date)VALUES(1, 'mkyong1', 'address1', now());INSERT INTO mkyongdb.customer(customer_id, name, address, created_date)VALUES(2, 'mkyong2', 'address2', now());

3. hibernate stuff

A model class and hibernate Mapping File for customer table.

File: customer. Java

package com.mkyong.customer.model; import java.util.Date; public class Customer{ public long customerId;public String name;public String address;public Date createdDate; //getter and setter methods }

File: customer. 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">

4. Spring stuff

Spring's Bo and Dao classes for business logic and database interaction.

File: customerbo. Java

package com.mkyong.customer.bo; import java.util.List; import com.mkyong.customer.model.Customer; public interface CustomerBo{ void addCustomer(Customer customer); List<Customer> findAllCustomer(); }

File: customerboimpl. Java

package com.mkyong.customer.bo.impl; import java.util.List;import com.mkyong.customer.bo.CustomerBo;import com.mkyong.customer.dao.CustomerDao;import com.mkyong.customer.model.Customer; public class CustomerBoImpl implements CustomerBo{ CustomerDao customerDao; public void setCustomerDao(CustomerDao customerDao) {this.customerDao = customerDao;} public void addCustomer(Customer customer){ customerDao.addCustomer(customer); } public List<Customer> findAllCustomer(){ return customerDao.findAllCustomer();}}

File: customerdao. Java

package com.mkyong.customer.dao; import java.util.List; import com.mkyong.customer.model.Customer; public interface CustomerDao{ void addCustomer(Customer customer); List<Customer> findAllCustomer(); }

File: customerdaoimpl. Java

package com.mkyong.customer.dao.impl; import java.util.Date;import java.util.List; import com.mkyong.customer.dao.CustomerDao;import com.mkyong.customer.model.Customer;import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class CustomerDaoImpl extends        HibernateDaoSupport implements CustomerDao{ public void addCustomer(Customer customer){ customer.setCreatedDate(new Date());getHibernateTemplate().save(customer); } public List<Customer> findAllCustomer(){ return getHibernateTemplate().find("from Customer"); }}

File: customerbean. 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.5.xsd">    <bean id="customerBo"          class="com.mkyong.customer.bo.impl.CustomerBoImpl" >   <property name="customerDao" ref="customerDao" />   </bean>    <bean id="customerDao"          class="com.mkyong.customer.dao.impl.CustomerDaoImpl" >   <property name="sessionFactory" ref="sessionFactory" />   </bean> </beans>
5. Spring + database

Configure database detail in spring.

File: DB. Properties

jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mkyongdbjdbc.username=rootjdbc.password=password

File: datasource. xml

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  <bean    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">   <property name="location"><value>WEB-INF/classes/config/database/db.properties</value>   </property></bean>   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="${jdbc.driverClassName}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" />  </bean> </beans>
6. Spring + hibernate

Integrate Hibernate and springLocalSessionFactoryBean.

File: hibernatesessionfactory. 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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- Hibernate session factory --><bean id="sessionFactory"      class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">     <property name="dataSource">      <ref bean="dataSource"/>    </property>     <property name="hibernateProperties">       <props>         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>         <prop key="hibernate.show_sql">true</prop>       </props>    </property>     <property name="mappingResources"><list>          <value>com/mkyong/customer/hibernate/Customer.hbm.xml</value></list>     </property> </bean></beans>
7. The JSF 2.0

JSF managed bean to call Spring's Bo to add or get customer's records from database.

File: customerbean. Java

package com.mkyong; import java.io.Serializable;import java.util.List; import com.mkyong.customer.bo.CustomerBo;import com.mkyong.customer.model.Customer; public class CustomerBean implements Serializable{ //DI via SpringCustomerBo customerBo; public String name;public String address;//getter and setter methods public void setCustomerBo(CustomerBo customerBo) {this.customerBo = customerBo;} //get all customer data from databasepublic List<Customer> getCustomerList(){return customerBo.findAllCustomer();} //add a new customer data into databasepublic String addCustomer(){ Customer cust = new Customer();cust.setName(getName());cust.setAddress(getAddress()); customerBo.addCustomer(cust); clearForm(); return "";} //clear form valuesprivate void clearForm(){setName("");setAddress("");} }

A jsf page to display existing customer recordsh:dataTableAnd a few text components to allow user to insert new customer record into database.

File: default.xhtml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">8. JSF 2.0 + spring

Integrate JSF 2.0 with spring, see detail explanation here

File: applicationcontext. xml

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- Database Configuration --><import resource="classes/config/spring/beans/DataSource.xml"/><import resource="classes/config/spring/beans/HibernateSessionFactory.xml"/> <!-- Beans Declaration --><import resource="classes/com/mkyong/customer/spring/CustomerBean.xml"/> </beans>

File: faces-config.xml

<?xml version="1.0" encoding="UTF-8"?><faces-config    xmlns="http://java.sun.com/xml/ns/javaee"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"    version="2.0"> <application>    <el-resolver>    org.springframework.web.jsf.el.SpringBeanFacesELResolver    </el-resolver>  </application> <managed-bean><managed-bean-name>customer</managed-bean-name><managed-bean-class>com.mkyong.CustomerBean</managed-bean-class><managed-bean-scope>session</managed-bean-scope><managed-property><property-name>customerBo</property-name><value>#{customerBo}</value></managed-property></managed-bean> </faces-config>

File: Web. xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">   <display-name>JavaServerFaces</display-name>   <!-- Add Support for Spring -->  <listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <listener><listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>  </listener>   <!-- Change to "Production" when you are ready to deploy -->  <context-param>    <param-name>javax.faces.PROJECT_STAGE</param-name>    <param-value>Development</param-value>  </context-param>   <!-- Welcome page -->  <welcome-file-list>    <welcome-file>faces/default.xhtml</welcome-file>  </welcome-file-list>   <!-- JSF mapping -->  <servlet>    <servlet-name>Faces Servlet</servlet-name>    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>    <load-on-startup>1</load-on-startup>  </servlet>   <!-- Map these files with JSF -->  <servlet-mapping>    <servlet-name>Faces Servlet</servlet-name>    <url-pattern>/faces/*</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>Faces Servlet</servlet-name>    <url-pattern>*.jsf</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>Faces Servlet</servlet-name>    <url-pattern>*.faces</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>Faces Servlet</servlet-name>    <url-pattern>*.xhtml</url-pattern>  </servlet-mapping> </web-app>
9. Demo

Run it, fill in the customer data and click on the "submit" button.


Please download the packages used in this project in my space

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.