Java教程

MyBatis进阶

本文主要是介绍MyBatis进阶,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

MyBatis进阶

1. 接口代理实现Dao层

  1. 结构图

    WJq6FP.png

  2. 接口代理(dynamic)

    package com.ding.dynamic;
    
    import com.ding.bean.Student;
    import com.ding.mapper.StudentMapper;
    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 java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
    * @Description TODO
    * @Author 丁帅帅
    * @Date 21/07/19 16:43
    * @Version 1.0
    */
    public class Test01 {
    
     /*  public static void main(String[] args) {
           try {
               selectByIds();
           } catch (Exception e) {
               e.printStackTrace();
           }
       }*/
    
       @Test
       public void selectCondition() throws Exception{
           //1.加载核心配置文件
           InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
           //2.获取SqlSession工厂对象
           SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
           //3.通过工厂对象获取SqlSession对象
           SqlSession sqlSession = sqlSessionFactory.openSession(true);
    
           //4.获取StudentMapper接口的实现类对象
           StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    
           Student stu = new Student();
           stu.setId(2);
           stu.setName("李四");
           //stu.getAge(24);
    
           //5.调用实现类的方法,接收结果
           List<Student> list = mapper.selectCondition(stu);
    
           //6.处理结果
           for (Student student : list) {
               System.out.println(student);
           }
    
           //7.释放资源
           sqlSession.close();
           is.close();
       }
    
       @Test
       public  void selectByIds() throws Exception{
    
           //1.加载核心配置文件
           InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
           //2.获取SqlSession工厂对象
           SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
           //3.通过工厂对象获取SqlSession对象
           SqlSession sqlSession = sqlSessionFactory.openSession(true);
    
           //4.获取StudentMapper接口的实现类对象
           StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    
           List<Integer> ids = new ArrayList<>();
           ids.add(1);
           ids.add(2);
           ids.add(3);
    
           //5.调用实现类的方法,接收结果
           List<Student> list = mapper.selectByIds(ids);
    
           //6.处理结果
           for (Student student : list) {
               System.out.println(student);
           }
    
           //7.释放资源
           sqlSession.close();
           is.close();
       }
    }
    
    
  3. StudentMapper

    <?xml version="1.0" encoding="UTF-8" ?>
    <!--MyBatis的DTD约束-->
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <!--
        mapper:核心根标签
        namespace属性:名称空间
    -->
    <mapper namespace="com.ding.mapper.StudentMapper">
    
        <sql id="select">select * from student</sql>
        <!--
            select:查询功能的标签
            id属性:唯一标识
            resultType属性:指定结果映射对象类型
            parameterType属性:指定参数映射对象类型
        -->
        <select id="selectAll" resultType="student">
           <include refid="select"/>
        </select>
    
        <select id="selectById" resultType="student" parameterType="int">
           <include refid="select"/> where id=#{id}
        </select>
    
        <insert id="insert" parameterType="student">
            insert into student values(#{id},#{name},#{age})
        </insert>
    
        <update id="update" parameterType="student">
            update student set name=#{name},age=#{age} where id=#{id}
        </update>
    
        <delete id="delete" parameterType="int">
            delete from student where id=#{id}
        </delete>
    
        <select id="selectCondition" resultType="student" parameterType="student">
            <include refid="select"/>
            <where>
                <if test="id!=null">
                    id=#{id}
                </if>
    
                <if test="name!=null">
                    and name=#{name}
                </if>
                <if test="age!=null">
                    and age = #{age}
                </if>
            </where>
        </select>
    
        <select id="selectByIds" resultType="student" parameterType="list">
    
            <include refid="select"/>
                <where>
                    <foreach collection="list" open="id in (" close=")" item="id" separator=",">
                        #{id}
                    </foreach>
                </where>
    
        </select>
    </mapper>
    
  4. 分页插件(paging)

 <!--集成分页助手插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
package com.ding.paging;

import com.ding.bean.Student;
import com.ding.mapper.StudentMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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 java.io.InputStream;
import java.util.List;

/**
 * @Description 分页插件测试
 * @Author 丁帅帅
 * @Date 21/07/19 19:08
 * @Version 1.0
 */
public class Test01 {


    @Test
    public void selectPaging() throws Exception{

           //1.加载核心配置文件
           InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

           //2.获取SqlSession工厂对象
           SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

           //3.通过工厂对象获取SqlSession对象
           SqlSession sqlSession = sqlSessionFactory.openSession(true);

           //4.获取StudentMapper接口的实现类对象
           StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

           //通过分页助手实现分页功能
           //第一页:显示三条数据
            // PageHelper.startPage(1,3);
            // 第二页:显示3条数据
            PageHelper.startPage(2,3);

           //5.调用实现类的方法,接收结果
           List<Student> list = mapper.selectAll();

           //6.处理结果
           for (Student student : list) {
               System.out.println(student);
           }

           //获取分页相关参数
        PageInfo<Student> info = new PageInfo<>(list);
        System.out.println("总条数: "+info.getTotal());
        System.out.println("总页数:" + info.getPages());
        System.out.println("当前页:" + info.getPageNum());
        System.out.println("每页显示条数:" + info.getPageSize());
        System.out.println("上一页:" + info.getPrePage());
        System.out.println("下一页:" + info.getNextPage());
        System.out.println("是否是第一页:" + info.isIsFirstPage());
        System.out.println("是否是最后一页:" + info.isIsLastPage());

        //7.释放资源
           sqlSession.close();
           is.close();
       }
}

多表操作

结构图

WYVEwt.png

1.bean类

package com.ding.bean;

public class Card {
    private Integer id;     //主键id
    private String number;  //身份证号

    private Person p;       //所属人的对象

    public Card() {
    }

    public Card(Integer id, String number, Person p) {
        this.id = id;
        this.number = number;
        this.p = p;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public Person getP() {
        return p;
    }

    public void setP(Person p) {
        this.p = p;
    }

    @Override
    public String toString() {
        return "Card{" +
                "id=" + id +
                ", number='" + number + '\'' +
                ", p=" + p +
                '}';
    }
}

package com.ding.bean;

import java.util.List;

public class Classes {
    private Integer id;     //主键id
    private String name;    //班级名称

    private List<Student> students; //班级中所有学生对象

    public Classes() {
    }

    public Classes(Integer id, String name, List<Student> students) {
        this.id = id;
        this.name = name;
        this.students = students;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    @Override
    public String toString() {
        return "Classes{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", students=" + students +
                '}';
    }
}

package com.ding.bean;

public class Course {
    private Integer id;     //主键id
    private String name;    //课程名称

    public Course() {
    }

    public Course(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Course{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

package com.ding.bean;

public class Person {
    private Integer id;     //主键id
    private String name;    //人的姓名
    private Integer age;    //人的年龄

    public Person() {
    }

    public Person(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

package com.ding.bean;

import java.util.List;

public class Student {
    private Integer id;     //主键id
    private String name;    //学生姓名
    private Integer age;    //学生年龄

    private List<Course> courses;   // 学生所选择的课程集合

    public Student() {
    }

    public Student(Integer id, String name, Integer age, List<Course> courses) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.courses = courses;
    }

    public List<Course> getCourses() {
        return courses;
    }

    public void setCourses(List<Course> courses) {
        this.courses = courses;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

2.MyBatisConfig

<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD约束-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<!--configuration 核心根标签-->
<configuration>

    <!--引入数据库连接的配置文件-->
    <properties resource="jdbc.properties"/>

    <!--配置LOG4J-->
    <settings>
        <setting name="logImpl" value="log4j"/>
    </settings>


    <!--起别名-->
    <typeAliases>

        <package name="com.ding.bean"/>
    </typeAliases>


    <!--environments配置数据库环境,环境可以有多个。default属性指定使用的是哪个-->
    <environments default="mysql">
        <!--environment配置数据库环境  id属性唯一标识-->
        <environment id="mysql">
            <!-- transactionManager事务管理。  type属性,采用JDBC默认的事务-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- dataSource数据源信息   type属性 连接池-->
            <dataSource type="POOLED">
                <!-- property获取数据库连接的配置信息 -->
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>

    <!-- mappers引入映射配置文件 -->
    <mappers>
        <!-- mapper 引入指定的映射配置文件   resource属性指定映射配置文件的名称 -->
        <mapper resource="com/ding/one_to_one/OneToOneMapper.xml"/>
        <mapper resource="com/ding/one_to_many/OneToManyMapper.xml"/>
        <mapper resource="com/ding/many_to_many/ManyToManyMapper.xml"/>
    </mappers>
</configuration>

3. 一对一

  1. OneToOneMapper.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.ding.table01.OneToOneMapper">
    <!--配置字段和实体对象属性的映射关系-->
    <resultMap id="oneToOne" type="card">
        <id column="cid" property="id" />
        <result column="number" property="number" />
        <!--
            association:配置被包含对象的映射关系
            property:被包含对象的变量名
            javaType:被包含对象的数据类型
        -->
        <association property="p" javaType="person">
            <id column="pid" property="id" />
            <result column="name" property="name" />
            <result column="age" property="age" />
        </association>
    </resultMap>

    <select id="selectAll" resultMap="oneToOne">
        SELECT c.id cid,number,pid,NAME,age FROM card c,person p WHERE c.pid=p.id
    </select>
</mapper>
  1. table01

    package com.ding.table01;
    
    import com.ding.bean.Card;
    
    import java.util.List;
    
    public interface OneToOneMapper {
        //查询全部
        public abstract List<Card> selectAll();
    }
    
    
    package com.ding.table01;
    
    import com.ding.bean.Card;
    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 java.io.InputStream;
    import java.util.List;
    
    public class Test01 {
        @Test
        public void selectAll() throws Exception{
            //1.加载核心配置文件
            InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
            //2.获取SqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
            //3.通过工厂对象获取SqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
    
            //4.获取OneToOneMapper接口的实现类对象
            OneToOneMapper mapper = sqlSession.getMapper(OneToOneMapper.class);
    
            //5.调用实现类的方法,接收结果
            List<Card> list = mapper.selectAll();
    
            //6.处理结果
            for (Card c : list) {
                System.out.println(c);
            }
    
            //7.释放资源
            sqlSession.close();
            is.close();
        }
    }
    
    

4.一对多

  1. OneToManyMapper
<?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.ding.table02.OneToManyMapper">
    <resultMap id="oneToMany" type="classes">
        <id column="cid" property="id"/>
        <result column="cname" property="name"/>

        <!--
            collection:配置被包含的集合对象映射关系
            property:被包含对象的变量名
            ofType:被包含对象的实际数据类型
        -->
        <collection property="students" ofType="student">
            <id column="sid" property="id"/>
            <result column="sname" property="name"/>
            <result column="sage" property="age"/>
        </collection>
    </resultMap>
    <select id="selectAll" resultMap="oneToMany">
        SELECT c.id cid,c.name cname,s.id sid,s.name sname,s.age sage FROM classes c,student s WHERE c.id=s.cid
    </select>
</mapper>
  1. table02
package com.ding.table02;

import com.ding.bean.Classes;

import java.util.List;

public interface OneToManyMapper {
    //查询全部
    public abstract List<Classes> selectAll();
}

package com.ding.table02;

import com.ding.bean.Classes;
import com.ding.bean.Student;
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 java.io.InputStream;
import java.util.List;

public class Test01 {
    @Test
    public void selectAll() throws Exception{
        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //4.获取OneToManyMapper接口的实现类对象
        OneToManyMapper mapper = sqlSession.getMapper(OneToManyMapper.class);

        //5.调用实现类的方法,接收结果
        List<Classes> classes = mapper.selectAll();

        //6.处理结果
        for (Classes cls : classes) {
            System.out.println(cls.getId() + "," + cls.getName());
            List<Student> students = cls.getStudents();
            for (Student student : students) {
                System.out.println("\t" + student);
            }
        }

        //7.释放资源
        sqlSession.close();
        is.close();
    }
}

5.多对多

  1. ManyToManyMapper
<?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.ding.table03.ManyToManyMapper">
    <resultMap id="manyToMany" type="student">
        <id column="sid" property="id"/>
        <result column="sname" property="name"/>
        <result column="sage" property="age"/>

        <collection property="courses" ofType="course">
            <id column="cid" property="id"/>
            <result column="cname" property="name"/>
        </collection>
    </resultMap>
    <select id="selectAll" resultMap="manyToMany">
        SELECT sc.sid,s.name sname,s.age sage,sc.cid,c.name cname FROM student s,course c,stu_cr sc WHERE sc.sid=s.id AND sc.cid=c.id
    </select>
</mapper>
  1. table03
package com.ding.table03;

import com.ding.bean.Student;

import java.util.List;

public interface ManyToManyMapper {
    //查询全部
    public abstract List<Student> selectAll();
}

package com.ding.table03;

import com.ding.bean.Course;
import com.ding.bean.Student;
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 java.io.InputStream;
import java.util.List;

public class Test01 {
    @Test
    public void selectAll() throws Exception{
        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //4.获取ManyToManyMapper接口的实现类对象
        ManyToManyMapper mapper = sqlSession.getMapper(ManyToManyMapper.class);

        //5.调用实现类的方法,接收结果
        List<Student> students = mapper.selectAll();

        //6.处理结果
        for (Student student : students) {
            System.out.println(student.getId() + "," + student.getName() + "," + student.getAge());
            List<Course> courses = student.getCourses();
            for (Course cours : courses) {
                System.out.println("\t" + cours);
            }
        }

        //7.释放资源
        sqlSession.close();
        is.close();
    }
}

这篇关于MyBatis进阶的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!