• MyBatis整合Spring


    MyBatis整合Spring

    官方文档

    http://mybatis.org/spring/zh/index.html

    配置:

    https://mybatis.org/mybatis-3/zh/getting-started.html

    原生Mybatis使用

    mybatis.xml配置文件

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <typeAliases>
            <package name="com.yan.mybatis.entity"/>
        </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://172.16.0.5:3306/mybatis"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper class="com.yan.mybatis.mapper.UserMapper"/>
        </mappers>
    </configuration>
    

    mapper包下的接口和xml文件:

    UserMapper.java

    public interface UserMapper {
        List<User> getUsers();
    }
    

    UserMapper.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.yan.mybatis.mapper.UserMapper">
        <select id="getUsers" resultType="user">
        select * from user;
        </select>
    </mapper>
    

    测试

    public class MybatisTest {
        @Test
        public void test() throws IOException {
            String resources="mybatis.xml";
            InputStream resourceAsStream = Resources.getResourceAsStream(resources);
            SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(resourceAsStream);
            SqlSession sqlSession = sessionFactory.openSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> users = mapper.getUsers();
            System.out.println(users);
        }
    }
    

    依赖:

     		<dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.2</version>
            </dependency>
    

    解决java类路径下的xml无法编译到classes下的问题,pom文件中添加

    <build>
    <!--        解决静态资源过滤问题 -->
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
            </resources>
        </build>
    
    整合

    方式一 :Dao继承Mapper接口

    spring-dao.xml

    <!--        dataSource -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
            <property name="url" value="jdbc:mysql://172.16.0.5:3306/mybatis"/>
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        </bean>
    
    <!--    sqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
    <!--        绑定mybatis.xml配置文件(非必须)-->
            <property name="configLocation" value="mybatis.xml"/>
    <!--        扫描mapper -->
            <property name="mapperLocations" value="classpath:com/yan/mybatis/mapper/*.xml"/>
        </bean>
    <!--    sqlSession(构造参数注入)-->
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            <constructor-arg ref="sqlSessionFactory"/>
        </bean>
        <bean id="userDao" class="com.yan.mybatis.dao.UserDao">
            <property name="sqlSession" ref="sqlSession"/>
        </bean>
    

    mybatis.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <typeAliases>
            <package name="com.yan.mybatis.entity"/>
        </typeAliases>
    </configuration>
    

    UserDao类:

    public class UserDao implements UserMapper {
        private SqlSession sqlSession;
        @Override
        public List<User> getUsers() {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            return mapper.getUsers();
        }
    
        public void setSqlSession(SqlSession sqlSession) {
            this.sqlSession = sqlSession;
        }
    }
    

    测试:

       @Test
        public void testSpringMybatis() throws IOException {
            ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
            UserMapper userDao = (UserMapper) context.getBean("userDao");
            System.out.println(userDao.getUsers());
        }
    

    方式二:继承SqlSessionDaoSupport并实现Mapper接口

    改动:

    spring-dao.xml

    	<!--        dataSource -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
            <property name="url" value="jdbc:mysql://172.16.0.5:3306/mybatis"/>
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        </bean>
    
    <!--    sqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
    <!--        绑定mybatis.xml配置文件(非必须)-->
            <property name="configLocation" value="mybatis.xml"/>
    <!--        扫描mapper -->
            <property name="mapperLocations" value="classpath:com/yan/mybatis/mapper/*.xml"/>
        </bean>
    <!--        dao配置 -->	
    	<bean id="userDaoSupport" class="com.yan.mybatis.dao.UserDaoSupport">
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>
    

    UserDaoSupport.java

    public class UserDaoSupport extends SqlSessionDaoSupport implements UserMapper {
        @Override
        public List<User> getUsers() {
            SqlSession sqlSession = getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            return mapper.getUsers();
        }
    }
    

    userDaoSupport可以实现和userDao一样的功能

    声明式事务

    事务:把一组业务放在一起操作,要么都成功,要么都失败,保证数据一致性

    特性:

    ACID

    原子性

    一致性

    隔离性

    持久性

    声明式事务:利用Spring Aop功能进行事务操作

    编程式事务:利用代码处理事务的提交回滚操作

    配置:

    spring-ado.xml

    <!--        dataSource -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
            <property name="url" value="jdbc:mysql://172.16.0.5:3306/mybatis"/>
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        </bean>
    
    <!--    sqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
    <!--        绑定mybatis.xml配置文件(非必须)-->
            <property name="configLocation" value="mybatis.xml"/>
    <!--        扫描mapper -->
            <property name="mapperLocations" value="classpath:com/yan/mybatis/mapper/*.xml"/>
    <!--        注入事务管理器-->
        </bean>
    
    <!--    配置声明式事务管理器-->
        <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="addUser" propagation="REQUIRED"/>
                <tx:method name="deleteUser" propagation="REQUIRED"/>
                <tx:method name="queryUsers" read-only="true"/>-->
                <tx:method name="*" propagation="REQUIRED"/>
            </tx:attributes>
        </tx:advice>
    <!--    织入事务-->
        <aop:config>
            <aop:pointcut id="transactionPoint" expression="execution(* com.yan.mybatis.dao.*.*(..))"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPoint"/>
        </aop:config>
    	<bean id="userDaoSupport" class="com.yan.mybatis.dao.UserDaoSupport">
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>
    

    UserDaoSupport.java

    public class UserDaoSupport extends SqlSessionDaoSupport implements UserMapper {
        @Override
        public List<User> queryUsers() {
            SqlSession sqlSession = getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User user=new User();
            user.setId(3);
            user.setName("yan");
            user.setAge(23);
            addUser(user);
            deleteUser(1);
            return mapper.queryUsers();
        }
    
        @Override
        public void addUser(User user) {
            SqlSession sqlSession = getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            mapper.addUser(user);
        }
    
        @Override
        public void deleteUser(int id) {
            SqlSession sqlSession = getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            mapper.deleteUser(id);
        }
    
    }
    

    修改deleteUser在UserMapper.xml中的实现,故意把delete改为deletes,那么插入操作也不会被执行

  • 相关阅读:
    使用OCR来帮助LR实现认证码识别
    Oracle的AWR报告分析
    oracle创建表空间
    Bug管理工具之Mantis_配置篇
    Selenium学习笔记之外部化相关测试数据---xml
    性能测试学习之二 ——性能测试模型(PV计算模型)
    性能测试学习之三—— PV->TPS转换模型&TPS波动模型
    性能测试学习之一 ——性能测试指标
    性能测试之吞吐量
    记录几个 Android x86 系统的官网
  • 原文地址:https://www.cnblogs.com/yanshaoshuai/p/12944449.html
Copyright © 2020-2023  润新知