MyBatis简单实例

本文项目代码:https://download.csdn.net/download/qq_43499543/19349764

MyBatis的执行步骤

  1. 读取MyBatis全局配置文件mybatis-config.xml(名称不固定)。
  2. 加载映射文件mapper.xml(名称不固定)。
  3. 根据配置文件创建会话工厂SqlSessionFactory。
  4. 通过会话工程SqlSessionFactory创建SqlSession对象,该对象提供了执行SQL的所有方法。
  5. 通过Executor操作数据库,Executor是MyBatis的一个核心接口,与SqlSession绑定,每个SqlSession都有一个新的Executor对象,由Configuration创建。SqlSession内部通过Executor操作数据库,增删改查通过Executor接口的update方法执行,查询语句通过query方法执行。
  6. 输入参数和输出结果的映射。在执行SQL语句前,Executor通过MappedStatement对象,将传入的Java对象映射到SQL语句中,在执行SQL语句后,MappedStatement对象将执行结果映射到Java对象。

具体操作

实例一

1.编写pojo层

public class Student {
    private int id;
    private String name;
    private String sex;
    //get,set,constructor省略
 }

2.编写MyBatis全局配置文件

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>
    <!--配置环境-->
    <environments default="test">
        <!--配置一个id为test的环境-->
        <environment id="test">
            <!--使用JDBC事务-->
            <transactionManager type="JDBC"></transactionManager>
            <!--数据库连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/chinasoft"></property>
                <property name="username" value="root"></property>
                <property name="password" value="123456"></property>
            </dataSource>
        </environment>
    </environments>
    <!--引用映射文件-->
    <mappers>
        <mapper resource="mapper.xml"></mapper>
    </mappers>
</configuration>

3.编写映射文件

mapper.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="main.resources.mapper">
    <!--方法名 参数类型 返回类型-->
    <select id="selectById" parameterType="int" resultType="pojo.Student">
    <!--执行语句-->
    select * from t_student where id = #{id};
  </select>
</mapper>

4.单元测试

public class test {
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    @Before
    public void init(){
        //读取mybatis配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream;
        try{
            //得到配置文件流
            inputStream = Resources.getResourceAsStream(resource);
            //根据配置文件信息创建会话工厂
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //通过工厂得到SqlSession
            sqlSession = sqlSessionFactory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void testFindStudent(){
        //通过sqlSession执行映射文件中定义的SQL,并返回映射结果
        Student student = sqlSession.selectOne("selectById",1);
        System.out.println(student.getId());
    }
    @After
    public void destroy(){
        //提交事务
        sqlSession.commit();
        //关闭事务
        sqlSession.close();
    }

}

实例二:接口编程

1.编写pojo层

代码同实例一

2.编写接口
StudentMapper.java

public interface StudentMapper {
    void updateById(Student student);   //通过id更新表
    void insert1(Student student);  //插入一个学生
    void insert2(Student[] students);   //以数组的形式插入多个学生
    void insert3(Map<String,String> stringMap);     //以Map的形式插入多个学生
    Student select1(int studentId);    //通过id查询学生
    List<Student> select2();    //查询多个学生
    void delete(List<Integer>  idList);  //删除多个学生
}

3.编写MyBatis全局配置文件
mybatis-config.xml

将映射文件修改为
<mapper resource="mapper\StudentMapper.xml"></mapper>
其余同上

4.编写映射文件mapper实现接口
StudentMapper.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">
<!-- namespace要和java包里的接口名对应 -->
<mapper namespace="mapper.StudentMapper">
    <!-- id要和接口中的方法名对应,parameterType和方法的参数类型对应,resultType和方法的返回类型对应-->
    <update id="updateById" parameterType="pojo.Student">
        <!-- #{}里的属性名要和pojo里Student实体类的属性名对应 -->
        UPDATE `t_student` SET t_student.`name`=#{name} , t_student.`sex`=#{sex} WHERE t_student.`id`=#{id};
    </update>

    <update id="insert1" parameterType="pojo.Student">
        <!-- 自增主键直接获取时会返回0,通过mybatis框架提供的selectKey标签获得自增产生的ID值-->
        <selectKey order="AFTER" keyColumn="id_value" resultType="int"  keyProperty="id" >
            SELECT LAST_INSERT_ID() AS id_value
        </selectKey>
        INSERT INTO `t_student`(t_student.`name`,t_student.`sex`)VALUES(#{name},#{sex});
    </update>

    <update id="insert2">
        INSERT INTO `t_student`(t_student.`name`,t_student.`sex`)VALUES
        <!-- collection集合:支持list、数组、map,item:元素类型,separator分隔符 -->
        <foreach collection="array" item="student" separator="," >
            (#{student.name},#{student.sex})
        </foreach>
    </update>

    <update id="insert3">
        INSERT INTO `t_student`(t_student.`name`,t_student.`sex`)VALUES(#{key01},#{key02})
    </update>

    <!-- select1略-->

    <resultMap id="select2ResultMap" type="pojo.Student">
        <!-- column要和数据库列名对应,property要和pojo.Student实体类属性名对应 -->
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <result column="sex" property="sex"></result>
    </resultMap>
    <select id="select2" resultMap="select2ResultMap">
        SELECT t_student.`id`,t_student.`name`,t_student.`sex` FROM `t_student`
    </select>

    <delete id="delete" parameterType="list">
        DELETE FROM `t_student` WHERE t_student.`id` IN (
        <foreach collection="list" item="studentId" separator=",">
            #{studentId}
        </foreach>
        );
    </delete>

</mapper>

5.单元测试
方便起见,编写了一个工具类实现通用语句
MyBatisUtil.java

public class MyBatisUtil {
    public static SqlSessionFactory sqlSessionFactory;
    // 加载类需要执行得代码
    static {
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    public static SqlSession getSqlSession(boolean flag){
        SqlSession sqlSession = sqlSessionFactory.openSession(flag);
        return sqlSession;
    }

    public static  void  close(SqlSession sqlSession){
        if(sqlSession!=null){
            sqlSession.close();
        }
    }
}

测试类

public class StudentMapperTest {
    
    @Test
    public void insert1() {
        SqlSession sqlSession  = MyBatisUtil.getSqlSession(true);
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student student = new Student("kk","w");
        mapper.insert1(student);
        System.out.println(student.getId());
    }

    @Test
    public void insert2() {
        SqlSession sqlSession  = MyBatisUtil.getSqlSession(true);
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student[] students = {new Student("ha","m"),
                            new Student("kk","w")};
        mapper.insert2(students);
    }


    @Test
    public void select2() {
        SqlSession sqlSession  = MyBatisUtil.getSqlSession(true);
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = mapper.select2();
        for(Student student:studentList){
            System.out.println(student.getName());
        }
    }

    @Test
    public void delete() {
        SqlSession sqlSession  = MyBatisUtil.getSqlSession(true);
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Integer>  idList=new ArrayList<>();
        idList.add(4);
        idList.add(5);
        idList.add(6);
        idList.add(7);
        mapper.delete(idList);
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值