整合Mybatis

整合Mybatis

一、回忆mybatis

建立数据库
CREATE  DATABASE `mybatis`

USE `mybatis`

CREATE TABLE `user`(
	`id` INT(20) NOT NULL,
	`name` VARCHAR(30) DEFAULT NULL,
	`password` VARCHAR(30) DEFAULT NULL,
	PRIMARY KEY(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `user`(`id`,`name`,`password`)
VALUES (1,'周周','123456'),(2,'莹莹','zxcvbn'),(3,'酱酱','123456');
SELECT * FROM `user`

整合Mybatis_第1张图片

User实体类
//使用注解需要导入lombok仓库
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
     
    private int id;
    private String name;
    private String password;
}
接口
import java.util.List;

public interface UserMapper {
     
    List<User> getUser();

}
mybatis-config.xml


<configuration>


    <typeAliases>
        <package name="com.cm.pojo"/>
    typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            dataSource>
        environment>
    environments>

    <mappers>
        <mapper resource="com/cm/mapper/xml/usermapper.xml"/>
    mappers>

configuration>
usermapper.xml



<mapper namespace="com.cm.mapper.UserMapper">

    <select id="getUser" resultType="User">
        select * from user;
    select>

mapper>
测试
public class MyTest {
     
    @Test
    public void test1() throws IOException {
     

        SqlSessionFactory sqlSession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession session = sqlSession.openSession();

        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> user = mapper.getUser();
        for (User user1 : user) {
     
            System.out.println(user1);
        }
    }
}

运行结果

整合Mybatis_第2张图片

二、Mybatis-spring

1.导入相关jar包

pom.xml

<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.0modelVersion>

    <groupId>com.cmgroupId>
    <artifactId>mybatis-springartifactId>
    <version>1.0-SNAPSHOTversion>

    <dependencies>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.8version>
        dependency>

        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.2version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.47version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.1.10.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.1.10.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.9.4version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.2version>
        dependency>

    dependencies>

    
    <build>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>truefiltering>
            resource>
        resources>
    build>
project>
User实体类不变
接口
public interface UserMapper {
     
    List<User> getUser();

}
编写applicationContext.xml

查看官网http://mybatis.org/spring/zh/index.html

整合Mybatis_第3张图片

整合Mybatis_第4张图片

整合Mybatis_第5张图片


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.cm.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    aop:config>

    
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        
        
		

        <property name="typeAliasesPackage" value="com.cm.pojo"/>
       
        <property name="mapperLocations" value="classpath:com/cm/mapper/xml/usermapper.xml"/>
    bean>

    
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    bean>

    
    <bean id="userMapperImpl" class="com.cm.mapper.impl.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    bean>

beans>
mybatis-config.xml


<configuration>
    
     
    
configuration>
usermapper.xml



<mapper namespace="com.cm.mapper.UserMapper">

    <select id="getUser" resultType="User">
        select * from user;
    select>

mapper>
UserMapperImpl实现类
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements UserMapper {
     

    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
     
        this.sqlSession = sqlSession;
    }

    public List<User> getUser() {
     
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        
        return mapper.getUser();
    }
}
测试
@Test
public void test2() {
     
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

    UserMapper userMapperImpl = (UserMapper) context.getBean("userMapperImpl");

    List<User> user = userMapperImpl.getUser();

    for (User user1 : user) {
     
        System.out.println(user1);
    }
}
运行结果

整合Mybatis_第6张图片

三、实现Mybatis-spring事务

1.事务ACID原则

  • 原子性
  • 一致性
  • 隔离性
    • 多个业务可能操作同一个资源,防止数据损坏
  • 持久性
    • 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器中!
事务注意点:
  • 把一组业务当成一个业务来做;要么都成功,要么都失败!
  • 事务在项目开发中,十分的重要,涉及到数据的一致性问题,不能马虎!
  • 确保完整性和一致性!

2、spring中的事务管理

方式一:不采用声明式事务

User实体类不变
接口
import java.util.List;

public interface UserMapper {
     
    List<User> getUser();

    int addUser(User user);

    int deleteUser(int id);
}
实现类

(注意,这里的添加和删除的操作是在getUser方法中实现的)

import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements UserMapper {
     

    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
     
        this.sqlSession = sqlSession;
    }

    public List<User> getUser() {
     
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = new User(4, "cm", "333333");

        mapper.addUser(user);
        mapper.deleteUser(3);
        return mapper.getUser();
    }

    public int addUser(User user) {
     
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        return mapper.addUser(user);
    }

    public int deleteUser(int id) {
     
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        return mapper.deleteUser(id);
    }
}
usermappper.xml

(这里会故意将删除的sql语句写错)




<mapper namespace="com.cm.mapper.UserMapper">

    <select id="getUser" resultType="User">
        select * from user;
    select>

    <insert id="addUser" parameterType="User">
        insert into user(id, name, password) value (#{id}, #{name}, #{password});
    insert>

    <delete id="deleteUser" parameterType="int">
        deletes from user where id = #{id};
    delete>

mapper>
applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.cm.mapper.*.*(..))"/>
        
    aop:config>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.cm.pojo"/>
        <property name="mapperLocations" value="classpath:com/cm/mapper/xml/usermapper.xml"/>
    bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    bean>

    <bean id="userMapperImpl" class="com.cm.mapper.impl.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    bean>

beans>
测试
@Test
public void test2() {
     
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

    UserMapper userMapperImpl = (UserMapper) context.getBean("userMapperImpl");

    List<User> user = userMapperImpl.getUser();

    for (User user1 : user) {
     
        System.out.println(user1);
    }
}

运行结果

图7】】】】】】

虽然报错了,但是添加的操作确实实现了。

整合Mybatis_第7张图片

我们应该避免这种情况,满足事务的ACID性,就需要使用声明式事务了。

方式二:使用声明式事务

这里只需要改变applicationContext.xml和实现类即可

applicationContext.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource" />
    bean>

    
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            
            <tx:method name="*" propagation="REQUIRED"/>
        tx:attributes>
    tx:advice>


    
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.cm.mapper.*.*(..))"/>
        
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    aop:config>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.cm.pojo"/>
        <property name="mapperLocations" value="classpath:com/cm/mapper/xml/usermapper.xml"/>
    bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    bean>

    <bean id="userMapperImpl" class="com.cm.mapper.impl.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    bean>

beans>
实现类(就是换了一下参数数值)
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements UserMapper {
     

    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
     
        this.sqlSession = sqlSession;
    }

    public List<User> getUser() {
     
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = new User(5, "cm", "333333");

        mapper.addUser(user);
        mapper.deleteUser(4);
        return mapper.getUser();
    }

    public int addUser(User user) {
     
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        return mapper.addUser(user);
    }

    public int deleteUser(int id) {
     
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        return mapper.deleteUser(id);
    }
}

运行后会报相同的错误,但是添加数据并没有成功。

整合Mybatis_第8张图片

这就非常符合事务的ACID要求。

只有当我们把usermapper.xml文件中的sql语句修改正确了,事务才会提交成功,我们对数据库的操作才会成功!

以上就是Mybatis-spring的核心内容。

你可能感兴趣的:(mysql,mybatis,spring,java,acid)