关闭

Spring data jpa 的事务与缓存优化

标签: spring事务缓存jpa优化
2113人阅读 评论(1) 收藏 举报
分类:

各配置文件如下:

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:context="http://www.springframework.org/schema/context"   
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"    
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd  
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd  
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"  
    default-lazy-init="true">

    <!--第一步-->
    <!--定义服务层代码存放的包扫描路径-->
	<context:component-scan base-package="com.jike.usermanage.service" />

    <!--第二步-->
    <!--定义实体的工厂bean-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="userPU" />
        <property name="persistenceXmlLocation" value="classpath:persistence.xml"></property>
    </bean>

    <!--第三步-->
    <!--定义事务管理器-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <!--第四步-->
    <!--定义repository接口的存放目录-->
    <!--定义接口实现的后缀,通常用Impl-->
    <!--定义实体工厂的引用-->
    <!--定义事务管理器的引用-->
   	<jpa:repositories base-package="com.jike.usermanage.repository"
   					  repository-impl-postfix="Impl" 
   					  entity-manager-factory-ref="entityManagerFactory" 
   					  transaction-manager-ref="transactionManager"/>




    <!--第五步-->
    <!--声明采用注解的方式申明事务-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
   
	
	
	<tx:advice id="userAdvice" transaction-manager="transactionManager">	
	    <tx:attributes>	
	      <tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" read-only="false" rollback-for="UserNotFoundException" timeout="-1"/>	
	      <tx:method name="del*" propagation="REQUIRED"/>	
	      <tx:method name="update*" propagation="REQUIRED"/>	
	      <tx:method name="add*" propagation="REQUIRED"/>	
	      <tx:method name="find*" propagation="REQUIRED"/>	
	      <tx:method name="get*" propagation="REQUIRED"/>	
	      <tx:method name="apply*" propagation="REQUIRED"/>	
	    </tx:attributes>	
	</tx:advice>
	<aop:config>	
		<aop:pointcut id="userServiceMethod" expression="execution(* com.jike.usermanage.service.*.*(..))"/>	
		<aop:advisor pointcut-ref="userServiceMethod" advice-ref="userAdvice" />	
	</aop:config>



</beans>


persistence.xml


<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
	<persistence-unit name="userPU" transaction-type="RESOURCE_LOCAL">
        <!--jpa的提供者-->
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<properties>
            <!--声明数据库连接的驱动-->
			<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <!--jdbc数据库的连接地址-->
			<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/user_manage"/>
			<property name="hibernate.connection.username" value="root"/>
			<property name="hibernate.connection.password" value="123456"/>
            <!--配置方言-->
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
            <!--激活查询日志功能-->
			<property name="hibernate.show_sql" value="true"/>
            <!--优雅地输出Sql-->
			<property name="hibernate.format_sql" value="true"/>
			
            <!--添加一条解释型标注-->
			<property name="hibernate.use_sql_comments" value="false"/>
            <!--配置如何根据java模型生成数据库表结构,常用update,validate-->
			<property name="hibernate.hbm2ddl.auto" value="update"/>
		
			<property name="hibernate.cache.use_query_cache" value="true"/>
      		<property name="hibernate.cache.use_second_level_cache" value="true"/>
      		<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider"/>
      		<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
      		<property name="hibernate.cache.provider_configuration" value="classpath:ehcache.xml"/>


		
		</properties>
	</persistence-unit>
</persistence>

spring-mvc.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
	<context:component-scan base-package="com.jike.usermanage.controller" />


    <mvc:annotation-driven />

	<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/pages/" p:suffix=".jsp" />


</beans>


ehcache.xml

<?xml version="1.0" encoding="UTF-8" ?>

<ehcache>
    <defaultCache
        maxElementsInMemory="50000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="false"/>
        
     <cache name="entityCache" eternal="false" maxElementsInMemory="10000"
     	timeToIdleSeconds="60" timeToLiveSeconds="120" overflowToDisk="true" />

    <!-- settings per class -->
  <!--   <cache name="com.danielme.demo.springjpahib.Country"
        maxElementsInMemory="1000"
        eternal="false"
        timeToIdleSeconds="180"
        timeToLiveSeconds="180"
        overflowToDisk="false"/>--> 
</ehcache>

处理事务一般有两种方式:


1. xml配置 如上。


2. 注解

@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED)
	@Override
	public User updateUser(User user) throws UserNotFound {
		User userUpdate = userRepository.findOne(user.getId());
		if (userUpdate==null)
			throw new UserNotFound();
		if (user.getName()!=null)
			userUpdate.setName(user.getName());
		
		if (user.getPhone()!=null)
			userUpdate.setPhone(user.getPhone());
		userRepository.save(userUpdate);
		return userUpdate;
	}

缓存的xml配置如上。

代码书写如下:

1. 实体类缓存:


@Cache(usage=CacheConcurrencyStrategy.READ_WRITE,region="entityCache")
@Cacheable(true)
@Entity
@Table(name="t_user")
public class User {


	@Id
	@GeneratedValue
	@Column(name="id_")
	private Integer id;	
	
	@Column(name="name_", length=60)
	private String name;
	
	@Column(name="phone_", length=11)
	private String phone;
	
	@Column(name="inCome_", precision=12, scale=2)
	private BigDecimal inCome;
	
	@Column(name="old_")
	private Integer old;
	
	@Column(name="worktimes_")
	private Integer worktime;	
	
	@OneToMany(fetch=FetchType.EAGER)
	private List<Interest> interests;
	
	public User(){
		
	}
	
	public User(Integer id, String name){
		
		this.id = id;
		this.name = name;
		
	}
  	
	public Integer getWorktime() {
		return worktime;
	}
	public void setWorktime(Integer worktime) {
		this.worktime = worktime;
	}
	public Integer getOld() {
		return old;
	}
	public void setOld(Integer old) {
		this.old = old;
	}
	public List<Interest> getInterests() {
		return interests;
	}
	public void setInterests(List<Interest> interests) {
		this.interests = interests;
	}
	public BigDecimal getInCome() {
		return inCome;
	}
	public void setInCome(BigDecimal inCome) {
		this.inCome = inCome;
	}
	
	
	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;
	}

	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
	
	
}



2. 常用的查询语句缓存:


public interface UserRepository extends JpaRepository<User,Integer>,JpaSpecificationExecutor<User>{
		

	public void add(User user);//添加	
	public User update(User user);//修改	
	public User addOrUpdate(User user);//添加或修改	
	public void delete(User user);//删除
	public User findOne(Integer id);//查询单个实体
	public List<User> findAll();//查找所有实体
	
	@Query(value="select u from User u where u.name like :name")
	@QueryHints(value={@QueryHint(name="org.hibernate.cacheable",value="true")})
	public List<User> findUserByName(@Param("name")String name);
	


 	
}




0
0

猜你在找
【直播】机器学习&数据挖掘7周实训--韦玮
【套餐】系统集成项目管理工程师顺利通关--徐朋
【直播】3小时掌握Docker最佳实战-徐西宁
【套餐】机器学习系列套餐(算法+实战)--唐宇迪
【直播】计算机视觉原理及实战--屈教授
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之矩阵--黄博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之凸优化--马博士
【套餐】Javascript 设计模式实战--曾亮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:23004次
    • 积分:598
    • 等级:
    • 排名:千里之外
    • 原创:36篇
    • 转载:0篇
    • 译文:0篇
    • 评论:4条
    最新评论