Mytabis-Spring整合

前言

    上次我们简单的介绍了一下动态sql的几个标签,这次我们讲解一下foreach标签的使用,话不多说。

动态sql之foreach

    foreach本次介绍的背景是运用在插入语句中,foreach一共有三个类型,分别为List,[] (array),Map三种,下面先介绍一下它的属性:
    **item:**循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。 具体说明:在list和数组中是其中的对象,在map中是value。 该参数为必选。
    **collection:**要做foreach的对象,作为入参时,List<?>对象默认用list代替作为键,数组对象有array代替作为键,Map对象用map代替作为键。 当然在作为入参时可以使用@Param(“keyName”)来设置键,设置keyName后,list,array,map将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子: 如果User有属性List ids。入参是User对象,那么这个collection = “ids” 如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = “ids.id” 上面只是举例,具体collection等于什么,就看你想对那个元素做循环。 该参数为必选。
    separator: 元素之间的分隔符,例如在in()的时候,separator=",“会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
    open: foreach代码的开始符号,一般是(和close=”)“合用。常用在in(),values()时。该参数可选。
    close: foreach代码的关闭符号,一般是)和open=”("合用。常用在in(),values()时。该参数可选。
    index: 在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。
    下面先介绍常规的插入方法(数据库边查询边往sql语句拼接),代码如下:
先建一个pojo类:

public class Teacher {
    private Integer id;
    private String tname;
    private Integer age;
    private List<Student> students;

    public Teacher (){}

    public Teacher(String tname) {
        this.tname = tname;
    }

    @Override
    public String toString() {
        return "{" +
                "id:" + id +
                ", tname:'" + tname + '\'' +
                ", age:'" + age + '\'' +
                ", 所教学生:[" + students + '\'' +
                "]}\n";
    }
}

随后建立接口定义方法,再在xml文件中映射后创建sql语句:

接口代码:
public interface TeacherDao {
    int batchInsertByNormal(List<Teacher> teacherList);
xml文件代码:
    <mapper namespace="com.xxx.mybatis.dao.TeacherDao">
    <resultMap id="teacher" type="Teacher">
        <id column="t_id" property="id" />
        <result column="tname" property="tname" />
        <result column="age" property="age" />
        <collection property="students" ofType="Student">
            <id column="s_id" property="id" />
            <result property="sname" column="sname" />
            <result property="nickName" column="nick_name" />
        </collection>
    </resultMap>
    <!-- 常规方式批量插入 -->
    <insert id="batchInsertByNormal" parameterType="Teacher">
        insert into teacher (tname, age) values
        <foreach collection="list" item="teacher" separator="," close=";">
            (#{teacher.tname}, #{teacher.age})
        </foreach>
    </insert>
</mapper>

还是要在mybatis_conf.xml中连接数据库,随后注册mapper,这个xml文件我们已经介绍多次,此次不再介绍直接上代码:

<configuration>
    <!-- 引入外部的properties文件,只能引入一个 -->
    <properties resource="jdbc.properties" />
   <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings> 
    <!-- 定义类型别名(全局),在所有的Mapper.xml中都可以用 -->
    <typeAliases>
        <typeAlias type="com.xxx.mybatis.bean.Teacher" alias="Teacher" />
    </typeAliases>
    <!-- 配置多套环境的数据库连接参数(如:开发环境、生产环境) -->
    <environments default="yanfa5">
    <environment id="yanfa5">
        <!-- 事务管理器:
            MANAGED: 这个配置就是告诉mybatis不要干预事务,具体行为依赖于容器本身的事务处理逻辑。
            JDBC: 这个配置就是直接使用了 JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务作用域。
         -->
        <transactionManager type="MANAGED"/>
        <dataSource type="POOLED">
            <property name="driver" value="${jdbc.driver}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.user}"/>
            <property name="password" value="${jdbc.password}"/>
        </dataSource>
    </environment>
</environments>
    <mappers>
        <mapper resource="mapper/TeacherMapper.xml" />
    </mappers>
</configuration>
jdbc.properties文件
jdbc.url=jdbc:mysql://localhost:3306/yanfa5?characterEncoding=utf8
jdbc.driver=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root

随后我们在测试类中获取一个集合,测试方法是否成功:

@Test
    public void testBatchInsertByNormal() {
        long start = System.currentTimeMillis();
        int rows = teacherDao.batchInsertByNormal(testData);
        log.info("插入数据行数: " + rows+", 耗时: " + (System.currentTimeMillis() - start));
    }

在此后介绍一下使用ExecutorType.BATCH方式执行批量操作:
这里只展示区别,代码如下:

  接口中的方法:
int insertTeacher(Teacher teacher);
  xml文件中的sql语句:
<insert id="insertTeacher" parameterType="Teacher">
       insert into teacher(tname) values (#{tname});
   </insert>
  测试类中的方法:
  @Test
    public void testBatchInsertByExecutorType() {
        SqlSessionFactory factory = MyBatisTools.getInstance().getSessionFactory();
        SqlSession sqlSession = factory.openSession(ExecutorType.BATCH, false);
        TeacherDao teacherDao = sqlSession.getMapper(TeacherDao.class);
        long start = System.currentTimeMillis();
        int rows = 0;
        int batchSize = 100;
        int count = 0;
        for(Teacher teacher : testData) {
            rows += teacherDao.insertTeacher(teacher);
            count ++;
            if(count % batchSize == 0) {
                sqlSession.flushStatements();
            }
        }
        sqlSession.flushStatements();
        sqlSession.commit();
        sqlSession.close();
        log.info("插入数据行数: " + rows+", 耗时: " + (System.currentTimeMillis() - start));
    }  

浅谈Spring与Mybatis整合

    Spring与Mybatis整合获取sqlSession在我的理解就是将sqlSession交给Spring管理,正常的流程和之前介绍的别无它二,唯一区别就是在xml总获取的方式,此次我们直接看xml中的配置,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://mybatis.org/schema/mybatis-spring
        http://mybatis.org/schema/mybatis-spring.xsd">
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <context:component-scan base-package="com.xxx.spring.service"/>
    <mybatis:scan base-package="com.xxx.spring"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:/mapper/*"/>
    </bean>
</beans>

    此时我们看到在代码的最后我们不仅添加了连接数据库的依赖,并且加入了映射的配置,此时我们已经将sqlSession放入了Spring容器中代理,在实现类中我们可以通过getBean来获取。

public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        MessageMapperImpl messageMapper = ctx.getBean(MessageMapperImpl.class);
        List<Message> messageList = messageMapper.queryAll();
        log.info("" + messageList);
    }

    注意一点,我们这次需要新建一个service层,里面声明一下接口,并重载其中的一个查询sql语句的方法,注意注解代码,代码如下:

@Service
public class MessageMapperImpl {
    @Autowired
    private MessageMapper messageMapper;

    public List<Message> queryAll(){

        return messageMapper.selectAll();
    }

}

    至此我们已经完成了Spring与Mybatis完成了整合。

后言

    我们可以通过自动生成代码,来获取bean中的类与接口中的sql查询方法,以及mybatis映射数据库和sql语句的编写的xml文件,很是方便,目前掌握两种方法,一种是maven依赖插件方法,另一种是命令行方法,具体代码怎么书写,咱们下次再谈!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值