JSF1.2+JPA2.0+Spring3.1整合开发

导入必须的Jar包

 

JSF1.2的依赖包

${jsf_home}\mojarra-1.2_15-b01-FCS\lib
jsf-api.jar
jsf-impl.jar
额外
jstl.jar

 

JPA用Hibenrate3.6.0实现的依赖包

 

${hibernate_home}\hibernate-distribution-3.6.0.Final\hibernate3.jar
${hibernate_home}\hibernate-distribution-3.6.0.Final\lib\required\*
${hibernate_home}\hibernate-distribution-3.6.0.Final\lib\jpa\*
${hibernate_home}\hibernate-distribution-3.6.0.Final\lib\optional\c3p0\* (加入C3P0)
${hibernate_home}\hibernate-distribution-3.6.0.Final\lib\optional\ehcache\* (加入缓存)

slf4j-nop-1.6.1.jar(可选)
backport-util-concurrent.jar (缓存依赖包)


Spring3.1.0的依赖包

 

${spring_home}\spring-framework-3.1.0.RELEASE\dist\
org.springframework.aop-3.1.0.RELEASE.jar
org.springframework.asm-3.1.0.RELEASE.jar
org.springframework.aspects-3.1.0.RELEASE.jar
org.springframework.beans-3.1.0.RELEASE.jar
org.springframework.context-3.1.0.RELEASE.jar
org.springframework.core-3.1.0.RELEASE.jar
org.springframework.expression-3.1.0.RELEASE.jar
org.springframework.jdbc-3.1.0.RELEASE.jar
org.springframework.orm-3.1.0.RELEASE.jar
org.springframework.test-3.1.0.RELEASE.jar
org.springframework.transaction-3.1.0.RELEASE.jar
org.springframework.web-3.1.0.RELEASE.jar

com.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.junit-4.7.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

 

MySQL驱动
mysql-connector-java-5.1.7-bin.jar

 

因为开发很简单,就是CRUD...

所以能省略的就尽量省略了。。。

 

package org.monday.app.domain;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "user_table")
public class User {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;

	@Column(name = "name")
	private String name;

	@Column(name = "phone")
	private String phone;

	@Temporal(TemporalType.DATE)
	@Column(name = "birthday")
	private Date birthday;

	//......

}

  

3. Dao实现类

 

package org.monday.app.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.monday.app.dao.UserDao;
import org.monday.app.domain.User;
import org.springframework.stereotype.Repository;

@Repository(value = "userDao")
public class UserDaoImpl implements UserDao {

	/**
	 * Spring3.1推荐使用原生的EntityManager 
	 * 而JpaDaoSupport和JpaTemplate被标记为过时
	 */
	@PersistenceContext(unitName = "jpa")
	private EntityManager entityManager;

	@Override
	public void save(User user) {
		entityManager.persist(user);
	}

	@Override
	public void update(User user) {
		entityManager.merge(user);
	}

	@Override
	public void delete(Integer id) {
		entityManager.remove(findById(id));
	}

	@Override
	public User findById(Integer id) {
		return entityManager.find(User.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> findAll() {
		Query query = entityManager.createQuery("from User");
		// 转换为HibernateQuery
		// if (query instanceof org.hibernate.ejb.QueryImpl) {
		// ((org.hibernate.ejb.QueryImpl) query).getHibernateQuery().setCacheable(true);
		// }
		return query.getResultList();
	}

}

 

 

 

3.Service实现类

 

就到对Dao的简单调用

 

 

现在,除了Web层组件,其他的组件都准比完毕。接下来,整合JPA+Spring

 

在“源文件”的目录下建立一个META-INF文件夹,里面建立一个persistence.xml文件。这个就不解释了。

 

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
	http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

	
	<!-- Spring整合JPA只要指定持久化单元的名称就可以了 -->
	<persistence-unit name="jpa"/>

</persistence>

 

 

 

下面,编写Spring的配置文件.beans.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" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

	<!-- 引入注解扫描器 -->
	<context:annotation-config />

	<!-- 引入属性文件 -->
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	<!-- 配置要扫描的包 -->
	<context:component-scan base-package="org.monday.app.dao.impl"/> 
	<context:component-scan base-package="org.monday.app.service.impl"/> 

	<!-- 配置数据源 -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
		<property name="targetDataSource">
			<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
				<property name="driverClass" value="${jdbc.driverClass}"/>
				<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
				<property name="user" value="${jdbc.user}"/>
				<property name="password" value="${jdbc.password}"/>
				<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
				<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
				<property name="initialPoolSize" value="${c3p0.initialPoolSize}"/>
				<property name="maxIdleTime" value="${c3p0.maxIdleTime}"/>
			</bean>
		</property>
	</bean>
	
	<!-- 配置EntityManagerFactory -->
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="persistenceUnitName" value="jpa" />
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="database" value="MYSQL" /> 
				<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
				<property name="generateDdl" value="true" />
				<property name="showSql" value="true" />
			</bean>
		</property>
		<property name="jpaProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
				<!-- 配置二级缓存 -->
				<prop key="hibernate.cache.use_second_level_cache">true</prop>
				<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
			</props>
		</property>
		<!-- 配置要扫描的实体类 -->
		<property name="packagesToScan">
			<list>
				<value>classpath*:org.monday.app.domain.*</value>
			</list>			
		</property>
	</bean>
	
	<!-- 配置事务 -->
	<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory"/>
	</bean>
	<tx:annotation-driven transaction-manager="txManager"/>
	
	
</beans>

 

 

 

自此,JPA+Spring 整合完毕。

 

 

 下面也是重点JSF+Spring 整合

 

配置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">

	<!-- 指定Spring的配置文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:beans.xml</param-value>
	</context-param>

	<!-- 注册Spring的WEB监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- JSF+Spring整合必须的 -->
	<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>

	<!-- 配置JSF -->
	<context-param>
		<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
		<param-value>client</param-value>
	</context-param>
	<context-param>
		<param-name>com.sun.faces.validateXml</param-name>
		<param-value>true</param-value>
	</context-param>

	<servlet>
		<servlet-name>jsf</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>jsf</servlet-name>
		<!-- <url-pattern>/faces/*</url-pattern> -->
		<url-pattern>*.faces</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	
</web-app>

 

  

这样JSF+Spring就配置好了。

 

但是,还有一个问题,JSF的托管bean(类似于Struts的Action)怎么取得Service组件。

 

首先,在代码中取得Service组件是这样的。

package org.monday.app.web.action;

import java.util.List;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.monday.app.domain.User;
import org.monday.app.service.UserService;

public class ListAction {

	private List<User> list;

	private UserService userService;

	/** 注入Service,不要使用注解注入 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/** 列表 */
	public List<User> getList() {
		list = userService.getAll();
		return list;
	}

	public void setList(List<User> list) {
		this.list = list;
	}

	/** 删除 */
	public void delete() throws Exception {
		// 取得id参数
		ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
		Integer id = Integer.parseInt(ctx.getRequestParameterMap().get("id"));

		userService.delete(id);
	}
}

  

 

 

但是,这样还不够,因为,JSF还不知道Sprig容器管理的Service组件。

所以,还要在JSF的配置文件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_1_2.xsd" version="1.2">

	<!-- 整合JSF+Spring -->
	<application>
		<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
	</application>


	<!-- 配置托管Bean -->
	<managed-bean>
		<managed-bean-name>listBean</managed-bean-name>
		<managed-bean-class>org.monday.app.web.action.ListAction</managed-bean-class>
		<managed-bean-scope>request</managed-bean-scope>
		<!-- 注入Service -->
		<managed-property>
			<property-name>userService</property-name>
			<value>#{userService}</value>
		</managed-property>
	</managed-bean>

	<!-- 配置导航规则 -->
</faces-config>

 

 

 使用的是setter的设值注入。

 

 这样就将Service组件注入到托管Bean中了。

 

终于其他的...可以参考附件

 


===============================注意===============================

JpaDaoSupport在Spring3.1中过时

 

@deprecated as of Spring 3.1, in favor of native EntityManager usage
(typically obtained through <code>@PersistenceContext</code>)

 

JpaTemplate在Spring3.1中过时

@deprecated as of Spring 3.1, in favor of native EntityManager usage
(typically obtained through <code>@PersistenceContext</code>)
Note that this class did not get upgraded to JPA 2.0 and never will.

 

两者都推荐使用
@PersistenceContext(unitName = "jpa")
private EntityManager entityManager;

 

但是Hibenrate3.X的却没有过时,而Spring整合Hibenate4.X的时候,却没有了HibernateDaoSupport和HibernateTemplate的支持,却推荐使用SessionFactory,即使用Hibenate原生的API。


呵呵,编辑器真的好了。。。

 

 

 

 

 

 

你可能感兴趣的:(spring,JSF,jpa,整合)