[知了堂学习笔记]_mybatis_03如何快速搭建mybatis框架之二

请关注“知了堂学习社区”,地址:[http://www.zhiliaotang.com/portal.php]

5.配置实体类和数据库表的映射文件
MyBatis的映射文件主要关联实体类与数据库表,主要目的是将表返回的数据映射到实体类(封装)

<?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,namespace的值习惯上设置成报名+sql映射文件名 -->
<mapper namespace="com.zhiliaotang.mybatis.mapper.StudentMapper">

    <!-- 解决表的字段名称和实体类属性不一样 -->
    <!-- MyBatis中多表映射 -->
    <resultMap type="Student01" id="baseResultMap">
        <id column="SNO" property="s_no"/>
        <result column="SBIRTHDAY" property="s_birthday"/>
        <result column="SNAME" property="s_name"/>
        <result column="SSEX" property="s_sex"/>
        <result column="CLASS" property="s_class"/>
    </resultMap>
    <resultMap type="Student" id="Student">
        <id column="SNO" property="sno"/>
        <result column="SNAME" property="sname"/>
        <result column="SSEX" property="ssex"/>
        <result column="SBIRTHDAY" property="sBirthday"/>
        <result column="CLASS" property="clas"/>
        <association property="teacher" javaType="Teacher">
            <id column="TNO" property="tno"/>
            <result column="TNAME" property="tname"/>
<result column="TSEX" property="tsex"/>
            <result column="TBIRTHDAY" property="tBirthday"/>
            <result column="PROF" property="prof"/>
            <result column="DEPART" property="depart"/
        </association>

    </resultMap
    <parameterMap type="Student01" id="baseParameterMap">
        <parameter property="s_no" javaType="java.lang.String"/>
        <parameter property="s_name" javaType="java.lang.String"/>
        <parameter property="s_sex" javaType="java.lang.String"/>
        <parameter property="s_birthday" javaType="java.util.Date"/>
        <parameter property="s_class" javaType="java.lang.String"/>
    </parameterMap>

    <!-- 查询 -->
    <!-- 使用占位符:#{}表示一个占位符 -->
    <select id="getInfo" resultType="Student">
        select * from student where SNO = 108
    </select>
    <select id="getInfoById" resultType="Student">
        select * from student where SNO = #{sno} and SBIRTHDAY = #{sBirthday}
    </select>

    <select id="getInfo01" resultMap="baseResultMap">
        select * from student where SNO = 108
    </select>
    <select id="getInfoById01" resultMap="baseResultMap" parameterMap="baseParameterMap">
        select * from student where SNO = #{s_no} and SBIRTHDAY = #{s_birthday}
    </select>

    <!-- 测试if标签 -->
    <select id="dySelectIf" resultType="Student" parameterType="Student" >
        select * from student where 1=1
        <if test="sno != null">
            and sno = #{sno}
        </if>
        <if test="sBirthday != null">
            and sBirthday = #{sBirthday}
        </if>
    </select>
<!-- 测试 choose标签-->
    <select id="dySelectChoose" resultType="Student" parameterType="Student">
        select * from student where 1=1
        <choose>
            <when test="sno != null">
                and sno = #{sno}
            </when>
            <when test="sBirthday != null">
                and sBirthday = #{sBirthday}
            </when>
        </choose>
    </select>
    <!-- 测试 where标签-->
    <select id="dySelectWhere" resultType="Student" parameterType="Student">
        select * from student
        <where>
            <if test="sno != null">
                and sno = #{sno}
            </if>
            <if test="sBirthday != null">
                and sBirthday = #{sBirthday}
            </if>
        </where>
    </select>

    <!-- 测试update -->
    <update id="dyUpate" parameterType="Student">
        update student
        <set>
        <if test="sno != null">
            sBirthday = #{sBirthday}
        </if>
        </set>
        <where>
            <if test="sno != null">
                and sno = #{sno}
            </if>
        </where>
    </update>
<!-- 测试forEach标签 -->
    <select id="dyForEach" parameterType="java.util.List" resultType="Student">
        select * from student where sno in
        <foreach collection="list" index="index" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
    </select>

    <!-- 测试forEachMap标签 -->
    <select id="dyForEachMap" parameterType="java.util.Map" resultType="Student">
        select * from student where sno in
        <foreach collection="ids" index="index" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
    </select>

    <!-- 测试trim标签 -->
    <select id="dyTrim" resultType="Student" parameterType="Student">
        select * from student
        <trim prefix="where" prefixOverrides="and | or">
            <if test="sno != null">
                and sno = #{sno}
            </if>
            <if test="sBirthday != null ">
                and sBirthday = #{sBirthday}
            </if>
        </trim>
    </select>


    <!-- 测试多对一关系映射 -->
    <select id="getStudent" resultMap="Student" parameterType="java.lang.String">
        select * from student a,teacher b where a.tno = b.tno and a.sno = #{sno}
    </select>



</mapper>

6.测试MyBatis

package com.zhiliaotang.mybatis.test;
import java.io.IOException;
import java.io.Reader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import com.zhiliaotang.mybatis.dao.StudentDao;
import com.zhiliaotang.mybatis.model.Student;
import com.zhiliaotang.mybatis.model.Student01;
import com.zhiliaotang.mybatis.model.Teacher;

public class MyBatisTest {
    //加载配置文件
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            reader = Resources.getResourceAsReader("config.xml");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    }
    //查询id为108的信息
    @Test
    public void m01() {
        //CRUD
        //获取SqlSession对象
//执行映射文件中SQL语句
        //返回结果

        SqlSession sqlSession = sqlSessionFactory.openSession();
        String sql = "com.zhiliaotang.mybatis.mapper.StudentMapper.getInfo";
        Student student = sqlSession.selectOne(sql);
        System.out.println(student.getSno() +" "+student.getSname()+" "+student.getSsex()+" "+student.getsBirthday()+" "+student.getClas());
        sqlSession.close();
    }
    //条件查询
    @Test
    public void m02() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String sql = "com.zhiliaotang.mybatis.mapper.StudentMapper.getInfoById";
        Student student = sqlSession.selectOne(sql, 108);
        System.out.println(student.getSno() +" "+student.getSname()+" "+student.getSsex()+" "+student.getsBirthday()+" "+student.getClas());
        sqlSession.close();
    }
    //数据类型不匹配的情况(时间类型)
    @Test
    public void m03() throws ParseException{
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String s = "1977-09-01 00:00:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sql = "com.zhiliaotang.mybatis.mapper.StudentMapper.getInfoById";
        Student student = sqlSession.selectOne(sql, new Student("108", sdf.parse(s)));
        System.out.println(student.getSno() +" "+student.getSname()+" "+student.getSsex()+" "+student.getsBirthday()+" "+student.getClas());
        sqlSession.close();
    }
    //字段名与表名不相同时的情况处理
    @Test
    public void m04() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String sql = "com.zhiliaotang.mybatis.mapper.StudentMapper.getInfo01";
        Student01 student01 = sqlSession.selectOne(sql);
        System.out.println(student01.getS_no()+" "+student01.getS_name()+" "+student01.getS_sex()+" "+student01.getS_birthday()+" "+student01.getS_class());
        sqlSession.close();
    }
@Test
    public void m05() throws ParseException {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String s = "1977-09-01 00:00:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sql = "com.zhiliaotang.mybatis.mapper.StudentMapper.getInfoById01";
        Student01 student01 = sqlSession.selectOne(sql, new Student01("108",sdf.parse(s)));
        System.out.println(student01.getS_no()+" "+student01.getS_name()+" "+student01.getS_sex()+" "+student01.getS_birthday()+" "+student01.getS_class());
        sqlSession.close();
    }
    /*@Test
    public void m06() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Date date = new Date();
        String sql = "com.zhiliaotang.mybatis.mapper.StudentMapper.insertStudent";
        Student01 student01 = sqlSession.selectOne(sql,new Student01("110","豆豆","女",date ,"7201"));
        System.out.println(student01.getS_no()+" "+student01.getS_name()+" "+student01.getS_sex()+" "+student01.getS_birthday()+" "+student01.getS_class());
        sqlSession.commit();
        sqlSession.close();

    }*/

    //测试if
    @Test
    public void m07() throws ParseException {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String s = "1977-09-01 00:00:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sql = "com.zhiliaotang.mybatis.mapper.StudentMapper.dySelectIf";
        Student student = sqlSession.selectOne(sql,new Student("108",sdf.parse(s)));
        System.out.println(student.getSno()+" "+student.getsBirthday());
        sqlSession.close();
    }
    //测试choose
    @Test
    public void m08() throws ParseException {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String s = "1977-09-01 00:00:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sql = "com.zhiliaotang.mybatis.mapper.StudentMapper.dySelectChoose";
        Student student = sqlSession.selectOne(sql,new Student("108",sdf.parse(s)));
        System.out.println(student.getSno()+" "+student.getsBirthday());
        sqlSession.close();

    }
    //测试where
    @Test
    public void m09() throws ParseException {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String s = "1977-09-01 00:00:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sql = "com.zhiliaotang.mybatis.mapper.StudentMapper.dySelectWhere";
        Student student = sqlSession.selectOne(sql,new Student("108",sdf.parse(s)));
        System.out.println(student.getSno()+" "+student.getsBirthday());
        sqlSession.close();
    }
    //测试update
    @Test
    public void m10() throws ParseException {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String s = "1977-09-01 10:20:30";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sql = "com.zhiliaotang.mybatis.mapper.StudentMapper.dyUpate";
        sqlSession.update(sql, new Student("108",sdf.parse(s)));
        sqlSession.commit();
        sqlSession.close();
    }
    //测试forEach
    @Test
    public void m11() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String sql = "com.zhiliaotang.mybatis.mapper.StudentMapper.dyForEach";
        List<String> list = new ArrayList<>();
        list.add("107");
        list.add("108");
        List<Student> listStudent = sqlSession.selectList(sql, list);
        for(Student stu : listStudent) {
            System.out.println(stu.getSno()+" "+stu.getsBirthday());
        }
        sqlSession.close();
    }

    //测试trim
    @Test
    public void m13() throws ParseException {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String sql = "com.zhiliaotang.mybatis.mapper.StudentMapper.dyTrim";
        String s = "1977-09-01 10:20:30";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Student student = sqlSession.selectOne(sql,new Student("108",sdf.parse(s)));
        System.out.println(student.getSno()+" "+student.getsBirthday());
        sqlSession.close();
    }

    //测试多对一关系映射
    @Test
    public void m14() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String sql = "com.zhiliaotang.mybatis.mapper.StudentMapper.getStudent";
        Student student = sqlSession.selectOne(sql,"108");
        //mybatis返回是一个学生的实体对象
        //如果要显示学生对应老师名称,按照对象的方式去寻找老师的对象,再去获取老师的属性
        //多对一关系,子表对应父表的关系
        Teacher teacher = student.getTeacher();
        System.out.println(student.getSname()+" "+teacher.getTname());
        sqlSession.close();
    }

    //测试一对多关系映射
    @Test
    public void m15() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String sql = "com.zhiliaotang.mybatis.mapper.TeacherMapper.getTeacher";
        //mybatis返回的是一个老师的实体对象
        //如果显示一个老师下面的多个学生,先找老师对象,然后找学生对象
        Teacher teacher = sqlSession.selectOne(sql,"804");
        List<Student> student = teacher.getStudent();
        for(Student s : student) {
            System.out.println(teacher.getTname()+" "+s.getSname());

        }
        sqlSession.close();
    }
//测试使用Map快速多表查询
    @Test
    public void m16() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String sql = "com.zhiliaotang.mybatis.mapper.TeacherMapper.getTeacherMap";
        List<Map> list = sqlSession.selectList(sql, "804");
        for(Map map : list) {
            System.out.println(map.get("TNAME")+" "+map.get("SNAME"));

        }
        sqlSession.close();
    }

    //接口注释测试
    @Test
    public void m17() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //初始化接口对象
        //调用接口中方法就是去执行某一个数据库的操作
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
        Student student = studentDao.getStudent("108");
        System.out.println(student.getSno()+" "+student.getSname());
        sqlSession.close();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值