zoukankan      html  css  js  c++  java
  • mybatis学习(一)不使用 XML 构建 SqlSessionFactory

    如果使用 Maven 来构建项目,则需将下面的 dependency 代码置于 pom.xml 文件中:

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>x.x.x</version>
    </dependency>

    配置mybatis-config.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>
    
          <!-- 别名 
            1.类型别名 typeAlias type属性值为全类名 alias为别名
            2.根据包   name属性值为包名 别名为包内类名的小写
          -->
        <typeAliases>
            <!-- <typeAlias type="com.tzh.bean.Clazz" alias="clazz"/>
            <typeAlias type="com.tzh.bean.Student" alias="student"/> -->
            <package name="com.tzh.bean"/>
        </typeAliases>
    
        <environments default="default">
            <environment id="default">
                <transactionManager type="JDBC"></transactionManager>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver" />
                    <property name="url" value="jdbc:mysql:///1606a" />
                    <property name="username" value="root" />
                    <property name="password" value="root" />
                </dataSource>
            </environment>
        </environments>
    
        <mappers>
            <mapper resource="com/tzh/mapper/*.xml" />
        </mappers>
    
    </configuration>

    创建beanSession工厂

    每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先定制的 Configuration 的实例构建出 SqlSessionFactory 的实例。
    package com.tzh.test;
    
    import java.io.InputStream;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    public class SqlSessionUtils {
    
        public static SqlSession getSqlSession() {
            SqlSession sqlSession = null;
            try {
                InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
    
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    
                sqlSession = sqlSessionFactory.openSession();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return sqlSession;
        }

    创建mapper接口

    package com.tzh.mapper;
    
    import java.util.List;
    
    import com.tzh.bean.Student;
    
    public interface StuMapperDao {
        
        List<Student> getStuList(Student student);
        List<Student> getStuListChoose(Student student);
        
        int updateStu(Student student);
        
        int addStu(List<Student> stuList );
        
    
        int delStu(int [] arr);
    }

    sql语句

    <?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">
    <!-- namespace 对应的是接口的全名 -->
    <mapper namespace="namespace">
         <!-- student为别名 在核心配置文件设置 -->
        <select id="getStuList" resultType="student" parameterType="student">
    
            select * from 0802_stu
            <!-- where 1 = 1 -->
            <!-- 如果内部的判断条件成立,会自动加上where关键字,并且会把多余的and或者or去掉 -->
            <where>
                <if test="sname !=null and sname!='' ">
                    and sname like concat('%',#{sname},'%')
                </if>
    
                <if test="sex!=null and sex!=''">
                    and sex =#{sex}
                </if>
                <if test="age >0 ">
                    and age &lt; #{age}
                </if>
            </where>
        </select>
        <select id="getStuListChoose" resultType="student"
            parameterType="student">
    
            select * from 0802_stu
            <!-- where 1 = 1 -->
            <!-- 如果内部的判断条件成立,会自动加上where关键字,并且会把多余的and或者or去掉 -->
            <!-- <where> -->
            <trim prefix="where" prefixOverrides="and |or ">
                <!-- 条件成立在前面加上WHER关键词 并 prefixOverrides前缀覆盖 条件成立去挑前缀add|or-->
    
                <!-- choose when otherwise 用法和switch case break 类似 只运行一个条件都符合时运行第一个 -->
                <choose>
                    <when test="sname !=null and sname!='' ">
                        and sname like concat('%',#{sname},'%')
                    </when>
                    <when test="sex!=null and sex!=''">
                        and sex =#{sex}
                    </when>
                    <otherwise><!-- 其他相当于else -->
                        and age &lt; #{age}
                    </otherwise>
                </choose>
            </trim>
            <!-- </where> -->
        </select>
    
        <update id="updateStu" parameterType="student">
            update 0802_stu
            <!-- SET 在内部的条件成立,就会加上set关键字,并且会把多余的逗号去掉 -->
            <!-- <set> -->
            <trim prefix="set" suffixOverrides=",">
            <!-- suffixOverrides 去掉多余的 , -->
                <if test="sname != null and sname !=''">
                    sname = #{sname},
                </if>
                <if test="sex !=null and sex != ''">
                    sex = #{sex},
                </if>
                <if test="age>0">
                    age = #{age}
                </if>
                </trim>
            <!-- </set> -->
            where sid= #{sid}
        </update>
        
        <insert id="addStu" parameterType="list">
            INSERT into 0802_stu (sname,sex,age,cid) VALUES 
            <!-- 你可以传递一个 List 实例或者数组作为参数对象传给 MyBatis。
            当你这么做的时 候,MyBatis 会自动将它包装在一个 Map 中,用名称在作为键。
            List 实例将会以“list” 作为键,而数组实例将会以“array”作为键。 -->
            <foreach collection="list" item="stu" separator=",">
                (#{stu.sname},#{stu.sex},#{stu.age},#{stu.cid})
            </foreach>
            
                    <!-- ('隆多','',20,2),
                    ('隆多','',20,2),
                    ('隆多','',20,2),
                    ('隆多','',20,2),
                    ('隆多','',20,2),
                    ('隆多','',20,2) -->
        
        </insert>
        
        <delete id="delStu" parameterType="java.lang.reflect.Array">
            DELETE FROM 0802_stu WHERE sid in 
                <foreach collection="array" item="sid" open="("  separator=","  close=")" >
                    #{sid}
                </foreach>
        </delete>
    
    </mapper>

    测试

    package com.tzh.test;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    
    import com.tzh.bean.Student;
    import com.tzh.mapper.StuMapperDao;
    
    public class TestDemo {
        
        @Test
        public void testListLike() {
            
            SqlSession sqlSession = SqlSessionUtils.getSqlSession();
            StuMapperDao mapper = sqlSession.getMapper(StuMapperDao.class);
            Student student = new Student();
            student.setSname("k");
            student.setSex("");
            student.setAge(34);
            
            //List<Student> stuList = mapper.getStuList(student);
            List<Student> stuList = mapper.getStuListChoose(student);
            for (Student student2 : stuList) {
                System.out.println(student2);
            }
            
            
        }
        
        @Test
        public void testUpdate() {
            
            SqlSession sqlSession = SqlSessionUtils.getSqlSession();
            StuMapperDao mapper = sqlSession.getMapper(StuMapperDao.class);
            Student student = new Student();
            student.setSname("k");
            student.setSex("");
            //student.setAge(34);
            student.setSid(1);
            
            int updateStu = mapper.updateStu(student);
            sqlSession.commit();
        }
        
        @Test
        public void testAdd() {
            
            SqlSession sqlSession = SqlSessionUtils.getSqlSession();
            StuMapperDao mapper = sqlSession.getMapper(StuMapperDao.class);
            Student student = new Student();
            student.setSname("k");
            student.setSex("");
            student.setAge(34);
            student.setCid(1);
            Student student1 = new Student();
            student1.setSname("k");
            student1.setSex("");
            student1.setAge(34);
            student1.setCid(1);
            Student student2 = new Student();
            student2.setSname("k");
            student2.setSex("");
            student2.setAge(34);
            student2.setCid(1);
            
            List<Student> stuList = new ArrayList<Student>();
            
            stuList.add(student);
            stuList.add(student1);
            stuList.add(student2);
            
            int addStu = mapper.addStu(stuList);
            
            sqlSession.commit();
            
        }
        
        @Test
        public void testDel() {
            SqlSession sqlSession = SqlSessionUtils.getSqlSession();
            StuMapperDao mapper = sqlSession.getMapper(StuMapperDao.class);
            
            int [] arr = {1,2,3,4,5};
            
            int delStu = mapper.delStu(arr);
            sqlSession.commit();
        }
    
    }
  • 相关阅读:
    [AU3]技巧
    [AU3]Windows 10 Update message DETELEDER Win10更新通知删除助手
    vue多选框选择后显示选中的内容
    计算object的长度
    关于苹果手机点击事件无效的解决办法
    vue中将汉字按照首字母排序,也适用于其他地方,但不适用多音字
    关于json数据格式错误
    Java下使用Swing来进行图形界面开发
    数字与静态
    Java中的内存机制及管理
  • 原文地址:https://www.cnblogs.com/JonaLin/p/11573001.html
Copyright © 2011-2022 走看看