Spring + JPA + Hibernate配置

<1>persistence.xml放到类路径下的META-INF下面
<persistence 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"    version="1.0">
	<!--事务类型:local的还是global(JTA)的事务 -->
	<persistence-unit name="jpa_test" transaction-type="RESOURCE_LOCAL">

	</persistence-unit>
</persistence>

<2>applicationContext.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:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
	<!-- 自动装配注解Bean后置处理器 -->
	<bean 
		class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
    
    <!-- JPA注解Bean后置处理器 -->
    <bean
        class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

	<!-- 利用Spring的实体管理器工厂来创建JPA实体管理器 -->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean
                class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="database" value="MYSQL" />
                <property name="showSql" value="true" />
                <!-- <property name="generateDdl" value="true" /> -->
            </bean>
        </property>
    </bean>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/test?useUnicode=true&amp;characterEncoding=UTF-8" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>
	
	<!-- 	
	<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> 
		<property name="jndiName">
			<value>java:comp/env/jdbc/jpa_ds</value>
		</property> 
	</bean>
	 -->

	<!-- 声明一个Spring提供的JPA事务管理器,传入的参数是Spring中的实体管理器工厂 --> 
    <bean id="transactionManager"
        class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

	<!-- 开启Spring提供的基于注解的声明式事务管理 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

	<!--  
	<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
        <property name="transactionManager">
            <ref local="transactionManager"/>
        </property>
        <property name="transactionAttributes">
            <props>
                <prop key="insert*">PROPAGATION_REQUIRED</prop>
                <prop key="update*">PROPAGATION_REQUIRED</prop>
                <prop key="save*">PROPAGATION_REQUIRED</prop>
                <prop key="add*">PROPAGATION_REQUIRED</prop>
                <prop key="update*">PROPAGATION_REQUIRED</prop>
                <prop key="remove*">PROPAGATION_REQUIRED</prop>
                <prop key="delete*">PROPAGATION_REQUIRED</prop>
                <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
                <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
                <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
                <prop key="change*">PROPAGATION_REQUIRED</prop>
                <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
            </props>
        </property>
    </bean>
 	
	<bean id="beanNameAutoProxyCreator"
		class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
		<property name="beanNames">
		    <list>
		      	<value>*Service</value>
		       	<value>*Dao</value>
		    </list>
      	</property>
		<property name="interceptorNames">
			<list>
				<value>transactionInterceptor</value>
			</list>
		</property>
    </bean>            
 	-->
 	
 	<!-- 直接使用Spring的 JpaTemplate -->
	<bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>

	<bean id="personDao" class="quickstart.dao.impl.PersonDaoImpl" autowire="byName"/>
	
	<bean id="peopleService" class="quickstart.service.impl.PeopleServiceImpl"/>
</beans>

<3>web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>jpa_test</display-name>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			classpath:applicationContext.xml
		</param-value>
	</context-param>
	
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
	
	<!-- 配置字符编码过滤器 -->   
    <filter>   
        <filter-name>encoding</filter-name>   
        <filter-class>   
            org.springframework.web.filter.CharacterEncodingFilter   
        </filter-class>   
        <init-param>   
            <param-name>encoding</param-name>   
            <param-value>UTF-8</param-value>   
        </init-param>   
    </filter>   
       
    <filter-mapping>   
        <filter-name>encoding</filter-name>   
        <url-pattern>/*</url-pattern>   
    </filter-mapping>   

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

<4>泛型dao定义
public interface GenericDao<T, ID extends Serializable> {
	public T save(T entity);

	public T update(T entity);

	public Integer updateBySql(final String sql);
	
	public void delete(T entity);
	
	public T findById(ID id);
	
	public List findByJPQL(String jpql);
	
	public List findBySQL(String sql);
	
	public List findAll();
	
	public int findRowCount();
}

public class GenericDaoImpl<T, ID extends Serializable> extends JpaDaoSupport
		implements GenericDao<T, ID> {

	private Class persistentClass;

	public GenericDaoImpl() {
		this.persistentClass = (Class) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	public Class getPersistentClass() {
		return persistentClass;
	}

	public T save(Object entity) {
		getJpaTemplate().persist(entity);
		return (T)entity;
	}

	public T update(Object entity) {
		getJpaTemplate().merge(entity);
		return (T)entity;
	}

	public Integer updateBySql(final String sql){
		return (Integer)getJpaTemplate().execute(new JpaCallback(){
			public Integer doInJpa(EntityManager em) throws PersistenceException{
				return em.createNativeQuery(sql).executeUpdate();
			}
		});
	}

	public void delete(Object entity) {
		getJpaTemplate().remove(entity);
	}
	
	public T findById(Serializable id) {
		return (T)getJpaTemplate().find(this.getPersistentClass(), id);
	}

         //要立即抓取时用"JOIN FETCH"
	public List findByJPQL(String jpql) {
		return getJpaTemplate().find(jpql);
	}

	/**
	 * 返回:list中装入的是对象数组(Object[])
	 */
	public List findBySQL(final String sql) {
		return  getJpaTemplate().executeFind(new JpaCallback(){
			public List doInJpa(EntityManager em) throws PersistenceException{
				return em.createNativeQuery(sql).getResultList();
			}
		});
	}

	public List findAll() {
		return getJpaTemplate().executeFind(new JpaCallback() {
			public Object doInJpa(EntityManager em) throws PersistenceException {
				StringBuffer jpql = new StringBuffer("from ");
				jpql.append(getPersistentClass().getName());
				jpql.append(" obj");
				return em.createQuery(jpql.toString()).getResultList();
			}
		});
	}

	
	public int findRowCount() {
		return ((Long) getJpaTemplate().execute(new JpaCallback() {
			public Object doInJpa(EntityManager em) throws PersistenceException {
				StringBuffer strBuff = new StringBuffer("select count(*) from ");
				strBuff.append(getPersistentClass().getName());
				return em.createQuery(strBuff.toString()).getResultList().get(0);
			}
		})).intValue();
	}
	
}

你可能感兴趣的:(spring,sql,Hibernate,配置管理,jpa)