JPA搭建

34 篇文章 0 订阅
4 篇文章 0 订阅

spring-jpa配置文件仅参考

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 
	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" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tool="http://www.springframework.org/schema/tool" xmlns:security="http://www.springframework.org/schema/security"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="  
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
     http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool-4.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd  
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd   
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 
     http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd 
     http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
     http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">  
     
     <description>Spring相关配置 </description>

     <context:component-scan base-package="com.qf.wh" />

     <!-- jpaVendorAdapter 配置 -->
     <bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
         <property name="databasePlatform" value="org.hibernate.dialect.OracleDialect" />  
         <property name="generateDdl" value="false"/>
         <property name="showSql" value="true"/>
     </bean>
     
     <!-- Jpa Entity Manager 集成jpa配置 1.LocalEntityManagerFactoryBean 不支持Spring管理的全局事务。不建议使用此方式。这种方法实际上只适用于独立的应用程序和测试环境
     2.从JNDI中获取:用于从Java EE服务器中获取指定的EntityManagerFactory,这种方式在Spring事务管理时一般要使用JTA事务管理 <jee:jndi-lookup id="entityManagerFactory"  jndi-name="persistence/persistenceUnit"/>
     LocalContainerEntityManagerFactoryBean:适用于所有环境的FactoryBean,能全面控制EntityManagerFactory配置,非常适合那种需要细粒度定制的环境-->
 	<bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
        <property name="packagesToScan" value="com.qf.wh.**.vo"/>
		<property name="jpaProperties">
			<props>
				<!-- 命名规则 My_NAME->MyName -->
				<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
				<prop key="hibernate.ejb.entitymanager_factory_name">entityManagerFactory</prop>
			</props>
		</property>
        <property name="jpaPropertyMap">
            <map>
            	<!-- 将Hibernate查询中的符号映射到SQL查询中的符号 (符号可能是函数名或常量名字). 取值 hqlLiteral=SQL_LITERAL, hqlFunction=SQLFUNC -->
                <entry key="hibernate.query.substitutions" value="true 1, false 0"/>
                <!-- 为Hibernate关联的批量抓取设置默认数量 -->
                <entry key="hibernate.default_batch_fetch_size" value="16"/>
                <!-- 为单向关联(一对一, 多对一)的外连接抓取(outer join fetch)树设置最大深度 -->
                <entry key="hibernate.max_fetch_depth" value="2"/>
                <!-- 如果开启, Hibernate将收集有助于性能调节的统计数据 -->
                <entry key="hibernate.generate_statistics" value="true"/>
                <entry key="hibernate.bytecode.use_reflection_optimizer" value="true"/>          
                <entry key="hibernate.format_sql" value="true"/> 
                <!-- 如果开启, Hibernate将在SQL中生成有助于调试的注释信息 -->
                <entry key="hibernate.use_sql_comments" value="true"/> 
            </map>
        </property>		
    </bean>

	<!--事务管理器配置-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    
	<!-- jpa 配置 @NoRepositoryBean 找到则impl找不到则默认-->
	<jpa:repositories base-package="com.qf.wh.**.repository"
	 entity-manager-factory-ref="entityManagerFactory"
	 transaction-manager-ref="transactionManager">
	</jpa:repositories>
     
	<!-- 开启annotation注解事务 -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
	<!-- 最多只能有一个,即如果没找到的情况是否抛出异常。默认false:即抛出异常 -->
   	<context:property-placeholder ignore-unresolvable="false" location="classpath*:/hibernate.properties" />
  	<!-- 数据源配置和DBCP数据库连接池 配置相同,比dbcp单线程 c3p0稳定 proxool 监控 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!--property name="driverClassName" value="${jdbc.driver}"/ jpaAdapter自我发现 -->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="${jdbc.pool.initialSize}" />
        <property name="minIdle" value="${jdbc.pool.minIdle}" />
        <property name="maxActive" value="${jdbc.pool.maxActive}" />
        <!-- 配置获取连接等待超时的时间 --> 
        <property name="maxWait" value="${jdbc.pool.maxWait}" />
        <!-- logAbandoned 连接被泄露时是否打印 -->
        <property name="logAbandoned" value="true"/>
        <!--removeAbandoned: 是否自动回收超时连接-->
        <property name="removeAbandoned"  value="true"/>
        <!--removeAbandonedTimeout: 超时时间(以秒数为单位)--> 
        <property name="removeAbandonedTimeout" value="${jdbc.pool.removeAbandonedTimeout}"/>
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 
        <property name="timeBetweenEvictionRunsMillis" value="${jdbc.pool.timeBetweenEvictionRunsMillis}" />-->
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${jdbc.pool.minEvictableIdleTimeMillis}" />
        <property name="validationQuery" value="SELECT 'x' from dual" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <!-- 开启PreparedStatements池. 当开启时, 将为每个连接创建一个statement池 打开PSCache,并且指定每个连接上PSCache的大小statement池能够同时分配的打开的statements的最大数量 -->
        <property name="poolPreparedStatements" value="true" /> 
        <property name="maxPoolPreparedStatementPerConnectionSize" value="${jdbc.pool.maxPoolPreparedStatementPerConnectionSize}" />
    </bean>
	<!-- 启动对@AspectJ(面向切面)注解的支持  通知spring使用cglib而不是jdk的来生成代理方法 AOP可以拦截到Controller --> 
    <aop:aspectj-autoproxy proxy-target-class="true"/>    
     
    <!-- 注解方式springTask-->  
    <task:annotation-driven/>
</beans>


import java.io.Serializable;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

@Repository
public interface IUserDao  extends JpaRepository<User, Serializable>,JpaSpecificationExecutor<User>{

	public User getUserById(String id);
}

/******JPA******/
@Autowired
private IUserDao iUserDao;//用户信息

单元测试

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.qf.wh.repository.ILoanFeeDao;

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations={"/spring-config-test.xml"}) //加载配置文件
public class TestDao{
	
	@Autowired
	private ILoanFeeDao iLoanFeeDao;	
	
	@Test
	public void testdao(){
		Assert.assertNotNull(iLoanFeeDao);
		System.err.println("单元测试====="+iLoanFeeDao.getByFeeNo("1").getFeeName());		
	}	
}
控制台:
13:18:28.310 [main] DEBUG o.s.t.c.s.DirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@55136092 testClass = TestDao, testInstance = quark.repository.TestDao@6b293ce0, testMethod = testdao@TestDao, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@605bcd16 testClass = TestDao, locations = '{classpath:/spring-config-test.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class dirties context [false], class mode [null], method dirties context [false].
单元测试=====1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值