spring data事務

事務在spring data中的使用java

1:事務通常在service層。由於一個service方法可能會屢次調用不一樣的dao,爲了保證事務的完整性,那麼屢次的dao都放到一個方法裏面mysql

2:讀的時候能夠不要事務,可是修改數據庫的信息必定須要事務spring

3:@Query、@Modifying、@Transactional的綜合使用sql

 

pom.xml數據庫

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.imooc</groupId>
    <artifactId>springdata</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>
        <!--MySQL Driver-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>

        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.5.RELEASE</version>
        </dependency>

        <!--spring data jpa-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.8.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.6.Final</version>
        </dependency>

    </dependencies>
</project>

com.gx.entity.Userapache

package com.gx.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/*
 * 這個Entity的註解會告訴配置文件這是一個實體類
 * 配置文件會根據EntityManagerFactory來判斷是否有這個表
 * 若是沒有回字段生成
 */
@Entity
public class User {
    /*最好使用封裝以後的類型
     * 
     */
    private Integer id;
    private String name;
    private Integer age;
    @GeneratedValue//這個註解是告訴配置文件這個id是自增的
    @Id//這個註解是告訴配置文件這是一個id
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    /*這個註解是設置表user裏面的name字段的長度爲20,默認不爲空
     * 若是不設置的話默認是255
     */
    @Column(length=20,nullable=false)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
    
}

com.gx.repository.UserRepositorydom

package com.gx.repository;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.RepositoryDefinition;
import org.springframework.data.repository.query.Param;

import com.gx.entity.User;

@RepositoryDefinition(domainClass = User.class, idClass = Integer.class)
public interface UserRepository{
    /*根據用戶id更新用戶年齡
     * @Modifying 容許修改
     */
    @Modifying
    @Query("update User u set u.age = :age where u.id = :id")
    public void update(@Param("id")Integer id,@Param("age")Integer age);
}

配置文件spring-data-beans.xmlmaven

<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: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.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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 配置數據源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <property name="url" value="jdbc:mysql://localhost:3307/test" />
    </bean>
    
    <!-- 配置EntityManagerFactory -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 設置jpa適配器 -->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <!-- 採用註解的方式,掃描包下面的java類 -->
        <property name="packagesToScan" value="com.gx"/>
        <!-- jpa的相關配置 -->
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.show_sql">true</prop><!--執行的時候是否顯示SQL-->
                <prop key="hibernate.format_sql">true</prop><!--執行的時候SQL是否格式化-->
                <prop key="hibernate.hbm2ddl.auto">update</prop><!--若是沒有是否建立-->
            </props>
        </property>
    </bean>
    
    <!--配置事務管理器-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <!--配置支持註解的事務-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--配置spring data 須要掃描的包-->
    <jpa:repositories base-package="com.gx" entity-manager-factory-ref="entityManagerFactory"/>

    <!--在這個配置裏面的內容spring都可以自動找到,更方便-->
    <context:component-scan base-package="com.gx"/>

</beans>

com.gx.service.UserServiceide

package com.gx.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gx.repository.UserRepository;

@Service
public class UserService {
    /*自動將UserRepository注入進來
     *前提是spring-data-beans.xml裏面有:
     *
     *<!--在這個配置裏面的內容spring都可以自動找到,更方便-->
     *<context:component-scan base-package="com.gx"/>
     */
    @Autowired
    private UserRepository userRepository;
@Transactional
public void updateUser(Integer id,Integer age){ userRepository.update(id, age); } }

建立測試類com.gx.service.test.ServiceUserTest測試

package com.gx.service.test;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.gx.service.UserService;

public class ServiceUserTest {
    //獲取上下文
        private ApplicationContext ctx = null;
        private UserService userService = null;
        @Before
        public void setup(){
            System.out.println("setup is working......");
            ctx = new ClassPathXmlApplicationContext("spring-data-beans.xml");
            userService = ctx.getBean(UserService.class);
        }
        @After
        public void destory(){
            ctx = null;
            System.out.println("destory is working......");
        }
        
        @Test
        public void testUpdate(){
            userService.updateUser(1, 55);
        }
}

測試結果

相關文章
相關標籤/搜索