【MyBayis】MyBayis詳解(0)基於簡單查詢的部署使用

一、數據準備
本示例全部基於MySQL數據庫完成,如想直接看代碼請前往https://download.csdn.net/download/tanglei6636/11009889下載即可。
需要創建以下幾張表:
表

  1. Person表
DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (
  `P_id` int(11) NOT NULL,
  `p_name` varchar(255) DEFAULT NULL,
  `card_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`P_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

INSERT INTO `person` VALUES ('1', '小明', '3701');
INSERT INTO `person` VALUES ('2', '小紅', '3702');
  1. Card表
DROP TABLE IF EXISTS `card`;
CREATE TABLE `card` (
  `c_id` int(11) NOT NULL,
  `c_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`c_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

INSERT INTO `card` VALUES ('3701', '小明的card');
INSERT INTO `card` VALUES ('3702', '小紅的card');
  1. Student表
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `s_id` int(8) NOT NULL DEFAULT '0',
  `name` varchar(50) DEFAULT NULL,
  `sex` varchar(50) DEFAULT NULL,
  `age` int(8) DEFAULT NULL,
  `g_id` int(8) DEFAULT NULL,
  PRIMARY KEY (`s_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `student` VALUES ('1', '小明', '男', '10', '1');
INSERT INTO `student` VALUES ('2', '小紅', '女', '10', '1');
INSERT INTO `student` VALUES ('3', '小王', '男', '10', '1');
INSERT INTO `student` VALUES ('4', '小花', '女', '10', '2');
  1. Grade表
DROP TABLE IF EXISTS `grade`;
CREATE TABLE `grade` (
  `g_id` int(8) NOT NULL DEFAULT '0',
  `g_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`g_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `grade` VALUES ('1', '一年級一班');
INSERT INTO `grade` VALUES ('2', '一年級二班');
  1. Groups表

DROP TABLE IF EXISTS `groups`;
CREATE TABLE `groups` (
  `g_id` int(8) NOT NULL DEFAULT '0',
  `g_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`g_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `groups` VALUES ('1', '手工');
INSERT INTO `groups` VALUES ('2', '電腦');
INSERT INTO `groups` VALUES ('3', '美術');
INSERT INTO `groups` VALUES ('4', '音樂');
  1. Student_Groups表
DROP TABLE IF EXISTS `student_group`;
CREATE TABLE `student_group` (
  `sg_id` int(8) NOT NULL DEFAULT '0',
  `s_id` int(8) DEFAULT NULL,
  `g_id` int(8) DEFAULT NULL,
  PRIMARY KEY (`sg_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `student_group` VALUES ('1', '1', '1');
INSERT INTO `student_group` VALUES ('2', '1', '2');
INSERT INTO `student_group` VALUES ('3', '2', '1');
INSERT INTO `student_group` VALUES ('4', '2', '2');
INSERT INTO `student_group` VALUES ('5', '1', '3');
INSERT INTO `student_group` VALUES ('6', '3', '1');

二、編寫代碼
Bean、Mapper接口、Mapper XML 可以使用逆向工程mybatis-generator自動生成,下載地址:https://github.com/mybatis/generator , Maven工程也可以通過POM文件導入jar包使用。

		<!-- mybatis-generator插件包 -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>

		<!-- dao層代碼生成插件 -->
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>

在main的resource目錄下創建generatorConfig.xml文件
generatorConfig
generator Config文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >

<generatorConfiguration>

    <!--驅動的位置-->
    <classPathEntry
            location="C:\Users\tangl\.m2\repository\mysql\mysql-connector-java\5.1.6\mysql-connector-java-5.1.6.jar"/>

    <context id="mysqlContext" defaultModelType="flat" targetRuntime="MyBatis3Simple">

        <!--避免與保留字衝突-->
        <property name="autoDelimitKeywords" value="true"/>
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <!--去掉註釋-->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
        </commentGenerator>

        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/demo?serverTimezone=UTC"
                        userId="root"
                        password="root">
        </jdbcConnection>

        <javaModelGenerator targetPackage="bean" targetProject="E:\workSpace\demo\src\main\java"/>

        <sqlMapGenerator targetPackage="mapper" targetProject="E:\workSpace\demo\src\main\resources"/>

        <javaClientGenerator type="XMLMAPPER" targetPackage="mapper"
                             targetProject="E:\workSpace\demo\src\main\java"/>

        <table tableName="test" domainObjectName="Test" enableDeleteByExample="true">
        </table>

    </context>
</generatorConfiguration>

節點說明如下表:
節點說明
使用方法:
使用方法
使用該逆向工程生成所有表對應的Bean、Mapper接口、Mapper XML。

Mapper節點說明如下圖:
節點說明
1、Person
Bean

public class Person {
    private int pId;
    private String pName;

	//card爲與Person一對一關係的對象
    private Card card;
    //省略get set方法
}

Mapper接口

public interface PersonMapper {
    List<Person> selectPerson();
}

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="mapper.PersonMapper">

    <resultMap id="BaseResultMap" type="bean.Person">
        <result column="p_id" jdbcType="INTEGER" property="pId"/>
        <result column="p_name" jdbcType="VARCHAR" property="pName"/>
        <association property="card" javaType="bean.Card">
            <result column="c_id" jdbcType="INTEGER" property="cID"/>
            <result column="c_name" jdbcType="VARCHAR" property="cName"/>
        </association>
    </resultMap>
    
    <select id="selectPerson" resultMap="BaseResultMap">
      SELECT
        *
      FROM person p , card c
      WHERE p.card_id = c.c_id
    </select>
</mapper>

card
result中使用assocation可以注入一一對應的數據關係,在查詢時自動將該屬性解析爲對應的Bean。
2、Card
Bean

public class Card {
    private int cID;
    private String cName;
}

3、Student
Bean

public class Student {
    private Integer sId;

    private String name;

    private String sex;

    private Integer age;

    private Integer gId;

	//學生對象與班級對象一對多的對應關係
    private Grade grade;

	//學生對象與興趣小組對象多對多的對應關係
	private Set<Group> groups;
}

Mapper接口

public interface StudentMapper {
    int countByExample(StudentExample example);

    int deleteByExample(StudentExample example);

    int deleteByPrimaryKey(Integer sId);

    int insert(Student record);

    int insertSelective(Student record);

    List<Student> selectByExample(StudentExample example);

    Student selectByPrimaryKey(Integer sId);

    Student getStuById(Integer id);

    int updateByExampleSelective(@Param("record") Student record, @Param("example") StudentExample example);

    int updateByExample(@Param("record") Student record, @Param("example") StudentExample example);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

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="mapper.StudentMapper" >
  <resultMap id="BaseResultMap" type="bean.Student" >
    <id column="s_id" property="sId" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="sex" property="sex" jdbcType="VARCHAR" />
    <result column="age" property="age" jdbcType="INTEGER" />
    <result column="g_id" property="gId" jdbcType="INTEGER" />
    <association property="grade" javaType="bean.Grade">
      <id column="g_id" property="gId"/>
      <result column="g_name" property="gName"/>
    </association>
    <collection property="groups" ofType="bean.Group">
      <id column="g_id" property="gId" jdbcType="INTEGER" />
      <result column="g_name" property="gName" jdbcType="VARCHAR" />
    </collection>
  </resultMap>
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    s_id, name, sex, age, g_id
  </sql>

  <select id="getStuById" parameterType="Integer" resultMap="BaseResultMap" statementType="CALLABLE">
      {call getStuById(#{id,mode=IN})}
  </select>

  <select id="selectByExample" resultMap="BaseResultMap" parameterType="bean.StudentExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from student
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from student
    where s_id = #{sId,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from student
    where s_id = #{sId,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="bean.StudentExample" >
    delete from student
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="bean.Student" >
    insert into student (s_id, name, sex, 
      age, g_id)
    values (#{sId,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, 
      #{age,jdbcType=INTEGER}, #{gId,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="bean.Student" >
    insert into student
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="sId != null" >
        s_id,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="sex != null" >
        sex,
      </if>
      <if test="age != null" >
        age,
      </if>
      <if test="gId != null" >
        g_id,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="sId != null" >
        #{sId,jdbcType=INTEGER},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null" >
        #{sex,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
      <if test="gId != null" >
        #{gId,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="bean.StudentExample" resultType="java.lang.Integer" >
    select count(*) from student
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update student
    <set >
      <if test="record.sId != null" >
        s_id = #{record.sId,jdbcType=INTEGER},
      </if>
      <if test="record.name != null" >
        name = #{record.name,jdbcType=VARCHAR},
      </if>
      <if test="record.sex != null" >
        sex = #{record.sex,jdbcType=VARCHAR},
      </if>
      <if test="record.age != null" >
        age = #{record.age,jdbcType=INTEGER},
      </if>
      <if test="record.gId != null" >
        g_id = #{record.gId,jdbcType=INTEGER},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update student
    set s_id = #{record.sId,jdbcType=INTEGER},
      name = #{record.name,jdbcType=VARCHAR},
      sex = #{record.sex,jdbcType=VARCHAR},
      age = #{record.age,jdbcType=INTEGER},
      g_id = #{record.gId,jdbcType=INTEGER}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="bean.Student" >
    update student
    <set >
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null" >
        sex = #{sex,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        age = #{age,jdbcType=INTEGER},
      </if>
      <if test="gId != null" >
        g_id = #{gId,jdbcType=INTEGER},
      </if>
    </set>
    where s_id = #{sId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="bean.Student" >
    update student
    set name = #{name,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER},
      g_id = #{gId,jdbcType=INTEGER}
    where s_id = #{sId,jdbcType=INTEGER}
  </update>
</mapper>

studentresult中使用collection 可以注入集合對應的數據關係,在查詢時自動將該屬性解析爲對應的Bean的集合。
4、Grade
Bean

public class Grade {

    private Integer gId;

    private String gName;

    private Set<Student> students;
}

5、Groups
Bean

public class Group {
    private Integer gId;

    private String gName;

    private Set<Student> students;
}

Mapper接口

public interface GroupMapper {
    int deleteByPrimaryKey(Integer gId);

    int insert(Group record);

    Group selectByPrimaryKey(Integer gId);

    List<Group> selectAll();

    int updateByPrimaryKey(Group record);
}

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="mapper.GroupMapper" >
  <resultMap id="BaseResultMap" type="bean.Group" >
    <id column="g_id" property="gId" jdbcType="INTEGER" />
    <result column="g_name" property="gName" jdbcType="VARCHAR" />
    <collection property="students" ofType="bean.Student">
      <id column="s_id" property="sId" jdbcType="INTEGER" />
      <result column="name" property="name" jdbcType="VARCHAR" />
      <result column="sex" property="sex" jdbcType="VARCHAR" />
      <result column="age" property="age" jdbcType="INTEGER" />
      <result column="g_id" property="gId" jdbcType="INTEGER" />
    </collection>
  </resultMap>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from group
    where g_id = #{gId,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="bean.Group" >
    insert into group (g_id, g_name)
    values (#{gId,jdbcType=INTEGER}, #{gName,jdbcType=VARCHAR})
  </insert>
  <update id="updateByPrimaryKey" parameterType="bean.Group" >
    update group
    set g_name = #{gName,jdbcType=VARCHAR}
    where g_id = #{gId,jdbcType=INTEGER}
  </update>
  <select id="selectByPrimaryKey"
          resultMap="BaseResultMap"
          parameterType="java.lang.Integer" >
    select *
    from groups g,student s,student_group sg
    where g.g_id = sg.g_id
    AND s.s_id = sg.s_id
    AND sg.g_id = #{gId,jdbcType=INTEGER}
  </select>
  <select id="selectAll" resultMap="BaseResultMap" >
    select g_id, g_name
    from group
  </select>
</mapper>

三、執行測試

public class TestMyBatis {

    private Logger logger = Logger.getLogger(TestMyBatis.class);

    private SqlSession session;

    @Before
    public void init(){
        try{
            //1.加載mybatis環境
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            //2.通過mybatis實例化數據訪問接口
            session = sqlSessionFactory.openSession();
        }
        catch(IOException e){
            logger.warn("加載mybatis環境異常",e);
        }
    }


    @After
    public void destory(){
        if(session!=null)
    {
        session.close();
    }
}

    @Test
    public void testOneToOne(){

        List<Person> list = session.getMapper(PersonMapper.class).selectPerson();

        for (Person person : list) {
            logger.info(person.toString());
        }

    }

    @Test
    public void testOneToMany(){

       Grade grade = session.getMapper(GradeMapper.class).selectByPrimaryKey(1);

       Set<Student> s = grade.getStudents();

        for (Student student : s) {
            logger.info(student.toString());
        }

    }

    @Test
    public void testManyToMany(){

        Group group = session.getMapper(GroupMapper.class).selectByPrimaryKey(1);

        Set<Student> s = group.getStudents();

        for (Student student : s) {
            logger.info(student.toString());
        }

    }

    @Test
    public void testExample() {

        StudentExample studentExample = new StudentExample();
        StudentExample.Criteria criteria = studentExample.createCriteria();
        criteria.andAgeEqualTo(10);
        criteria.andSexIsNotNull();
        criteria.andSIdEqualTo(1);
        //去除重複記錄
        studentExample.setDistinct(true);
        //根據年齡排序
        studentExample.setOrderByClause("s_id DESC");
        List<Student> list = session.getMapper(StudentMapper.class).selectByExample(studentExample);

        for (Student student : list) {
            logger.info(student.toString());
        }
    }

    @Test
    public void testProcedure() {

        Student student = session.getMapper(StudentMapper.class).getStuById(1);

        logger.info(student.toString());
    }
}

1、一對一查詢
一對一
2、一對多查詢
一對多
3、多對多查詢
多對多
4、Exmple使用
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
5、調用存儲過程
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章