The study notes mybatis database connection

Small practice project structure:

The first step: first references jar package, two packages used here, mybaits and mysql

Step Two: Configure mybatis-config.xml and jdbc.properties

jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/jtsys
jdbc.username=root
jdbc.password=root

mybaits-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>
    <!-- 设置引入配置文件 -->
    <properties resource="jdbc.properties"/>

    <!-- 设置驼峰命名规则 -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!-- 对事务的管理和连接池的配置 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driverClass}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>

    <!-- mapping 文件路径配置 -->
    <mappers>
        <mapper resource="mapper/UserMapper.xml" />
    </mappers>
</configuration>

Step Three: Write pojo, XXXMapper.xml, XXXDao Interface

sing:

package pojo;

public class User {

    private Integer id;
    private String username;
    private String mobile;
    private String email;

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", mobile='" + mobile + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

XXXDao Interface

package mapper;

import org.apache.ibatis.annotations.Param;
import pojo.User;

public interface UserDao {
    /**
     * 根据id进行查询
     */
    User findById(@Param("id") Integer id);
}

XXXMapper.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.UserDao">
    <select id="findUsers" resultType="pojo.User">
        select id,username,email,mobile from sys_users
    </select>

    <select id="findById" resultType="pojo.User">
        select id,username,email,mobile from sys_users where id=#{id}
    </select>

</mapper>

Step Four: mybaits start connecting to the database

package connTest;

import mapper.UserDao;
import pojo.User;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ConnDB {
    public static void main(String[] args) throws IOException {
        /**
         * mybatis连接数据库步骤:
         */
        //1.读取配置文件
        InputStream stream = Resources.getResourceAsStream("mybatis-config.xml");
        //2.获取sessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        //3.创建session对象
        SqlSession session = sqlSessionFactory.openSession();
        /**
         * mybatis连接数据库,有三种方式:
         * 第一种同jdbc类似,通过获取连接,得到传输器,然后发送sql指令进行连接数据库。
         * 第二种方式,通过XXXmapper.xml方式连接数据库。
         * 第三种方式,通过创建XXXDao接口,调用XXXMapper.xml文件连接数据库。
         */
        //4:第一种,发送XXXMapper.xml中定义的方法
        String mapperId = "mapper.UserDao.findUsers";
        List<User> users = session.selectList(mapperId);
        for (User user : users) {
            System.out.println(user);
        }
        //4:第二种:通过接口调用XXXMapper.xml中定义的方法
        UserDao userDao = session.getMapper(UserDao.class);
        User user = userDao.findById(19);
        System.out.println(user);
        session.close();
    }
}

Here mybatis connection to the database has been completed, the next re-learning multi-table joint investigation:

Many association query: classes and student table

Class objects: clazz

package com.cy.pj.pojo;

import java.util.List;

public class Clazz {
    private Integer id;
    private String name;
    private Integer principalId;
    private Teacher principal;
    private List<Student> studentList;

    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 getPrincipalId() {
        return principalId;
    }

    public void setPrincipalId(Integer principalId) {
        this.principalId = principalId;
    }

    public List<Student> getStudentList() {
        return studentList;
    }

    public void setStudentList(List<Student> studentList) {
        this.studentList = studentList;
    }

    public Teacher getPrincipal() {
        return principal;
    }

    public void setPrincipal(Teacher principal) {
        this.principal = principal;
    }

    @Override
    public String toString() {
        return "Clazz{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", principalId=" + principalId +
                ", principal=" + principal +
                ", studentList=" + studentList +
                '}';
    }
}

Students Object: student

package com.cy.pj.pojo;

public class Student {
    private Integer id;
    private String name;
    private String gender;
    private Integer age;
    private String address;
    private Integer classId;

    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 String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Integer getAge() {
        return age;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getClassId() {
        return classId;
    }

    public void setClassId(Integer classId) {
        this.classId = classId;
    }

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

Creating Dao and XXXMapper.xml:

OtherDao

package com.cy.pj.mapping;

import com.cy.pj.pojo.Clazz;
import com.cy.pj.pojo.Teacher;

import java.util.List;

public interface OtherDao {

    List<Clazz> findClassWithStudent();

    List<Teacher> findTeacher();
}

OtherMapper.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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
例如namespace="com.springdemo.mapping.userMapper"就是com.springdemo.mapping(包名)+userMapper(userMapper.xml文件去除后缀)
 -->
<mapper namespace="com.cy.pj.mapping.OtherDao">

    <!-- clazz表和student表设置为一对多关系
    association/collection中column可以理解为resultmap关联的表中存放着association/collection中关联表的何种关系,
    如果一对多,需要在多的一方存放resultMap关联表中的id,所以用id关联去查,可以查出多个。
    如果一对一,可能在resultMap表中存放了association表的id,用存放association表中id的列去查。-->
    <resultMap id="queryClazzStudent" type="com.cy.pj.pojo.Clazz">
        <id property="id" column="id"/>
        <association property="principal" column="principalId" javaType="com.cy.pj.pojo.Teacher" select="findTeacherByPId"></association>
        <collection property="studentList" column="id" ofType="com.cy.pj.pojo.Student" javaType="ArrayList" select="findStudent">
        </collection>
    </resultMap>

    <select id="findClassWithStudent" resultMap="queryClazzStudent">
        select * from clazz
    </select>
    <select id="findTeacherByPId" resultType="com.cy.pj.pojo.Teacher">
        select * from teacher where id=#{id}
    </select>
    <select id="findStudent" resultType="com.cy.pj.pojo.Student">
        select * from student where classId=#{id}
    </select>

    <!-- teacher表和course表设置为一对一关系 -->
    <resultMap id="queryTeacherWithCourse" type="com.cy.pj.pojo.Teacher">
        <id property="id" column="id"/>
        <association property="course" column="id" javaType="com.cy.pj.pojo.Course" select="findCourse"></association>
    </resultMap>

    <select id="findTeacher" resultMap="queryTeacherWithCourse">
        select * from teacher
    </select>
    <select id="findCourse" resultType="com.cy.pj.pojo.Course">
        select * from course where teacherId=#{id}
    </select>
</mapper>

Written test class for testing:

package com.cy.pj.conntest;

import com.cy.pj.mapping.DeptDao;
import com.cy.pj.mapping.OtherDao;
import com.cy.pj.pojo.Clazz;
import com.cy.pj.pojo.Dept;
import com.cy.pj.pojo.Role;
import com.cy.pj.pojo.Teacher;
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 java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class ConnDatabase {
    public static void main(String[] args) throws IOException, SQLException {

        InputStream inputStream = Resources.getResourceAsStream("Mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        /**
         * mybatis连接数据库方式一:通过mapper.xml中的key连接数据库
         */
        /*String statement = "com.cy.pj.mapping.RoleMapper.getRole";
        Role role = sqlSession.selectOne(statement, 1);
        System.out.println(role);*/

        /**
         * mybatis连接数据库方式二:利用反射XXXmapper类连接数据库
         */
        /*DeptDao deptDao = sqlSession.getMapper(DeptDao.class);
        List<Dept> depts = deptDao.findAllDept();
        for (Dept dept : depts) {
            System.out.println(dept);
        }*/
        /**
         * clazz表和student表为一对多关系,利用collection进行联合查询
         */
        OtherDao otherDao = sqlSession.getMapper(OtherDao.class);
        List<Clazz> clazzList = otherDao.findClassWithStudent();
        for (Clazz clazz : clazzList) {
            System.out.println(clazz);
        }
        /**
         * course表和teacher表设置一对一关系,利用association进行联合查询
         */
        /*OtherDao otherDao = sqlSession.getMapper(OtherDao.class);
        List<Teacher> teacherList = otherDao.findTeacher();
        for (Teacher teacher : teacherList) {
            System.out.println(teacher);
        }*/

        /**
         * mybatis连接数据方式三:利用statement连接数据库
         */
        /*Connection connection = sqlSession.getConnection();
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("select * from sys_roles");
        while (resultSet.next()){
            String name = resultSet.getString("name");
            String note = resultSet.getString("note");
            System.out.println("name="+name+";note="+note);
        }*/
    }
}

Test results are as follows:

 It can be seen using the two tables associated with many queries, the main use of collection to query, and one to one relationship between the use of association association inquiry, mainly as follows:

<resultMap id="queryClazzStudent" type="com.cy.pj.pojo.Clazz">
<!--将resultMap中的对象成为对象一,里面有两个属性,id为resultMap的唯一标识,type为关联的对象一
下面可以设置<id property="此为对象一的属性" column="此为对象对应表中的列名"/>一对多关联查询时,<id/>不可少,<result property="与id相同" column="与id相同">-->
    <id property="id" column="id"/>
    <association property="principal" column="principalId"         
         javaType="com.cy.pj.pojo.Teacher" select="findTeacherByPId">
    <!-- association关联对象为对象二,对象二与对象一一般为一对一关系,对象一中有一个属性是对象二,        <association property="对象一中关于对象二的属性" column="此属性为对象一与对象二的关联关系,比如对象一对应的表中存放对象二对象表的id之类的" javaType="对象二" select="查询对象二的方法">-->
    </association>
    <collection property="studentList" column="id" ofType="com.cy.pj.pojo.Student" 
         javaType="ArrayList" select="findStudent">
     <!---collection相关属性同association相似 不过这里关联对象三利用ofType,javaType为集合list类型->
    </collection>
</resultMap>

    <select id="findClassWithStudent" resultMap="queryClazzStudent">
        select * from clazz
    </select>
    <select id="findTeacherByPId" resultType="com.cy.pj.pojo.Teacher">
        select * from teacher where id=#{id}
    </select>
    <select id="findStudent" resultType="com.cy.pj.pojo.Student">
        select * from student where classId=#{id}
    </select>

Summary: mainly related to the process mybatis query the database, the database connection steps mybatis, configuration profiles, the query process of hierarchical queries, dao operation mapper.xml, mapper.xml query the data and return the results, as well as multi-table joins Inquire.

Add some dynamic sql knowledge to facilitate the review:

Dynamic SQL:

1. <where> </ where> add dynamic conditions where

<If test = ""> </ if> dynamic determination, determines whether the argument passed correctly

select * from emp
<where>
<if test="name != null and name !=''">
    name like concat('%',#{name},'%')
</if>
<if test="job != null and job != ''">
    and job = #{job}
</if>
</where>

2.<foreach collection="ids" item="id" separator="," open="(" close=")"></froeach>

<insert id="addBatchSave" >
  	insert into tbl_employee(last_name,email,gender) values
  	<foreach collection="emps" item="emppp" separator=",">
		(#{emppp.lastName},#{emppp.email},#{emppp.gender})
	</foreach>
 </insert> 

3. <set> </ set> Dynamic Updates

<update id="updateEmp">
	 	update emp 
	 		<set>
	 		<if test="name != null and name != ''">
	 			name=#{name},
	 		</if>
	 		<if test="job != null and job != ''">
	 			job=#{job}
	 		</if>
	 	</set>
	 	where id=#{id}
	 </update>

4. <sql id = "idName"> </ sql> frequently used fragment encapsulation sql, reference is <includ refid = "idName">

<sql id="insertColumn">
		<if test="_databaseId=='mysql'">
			id,last_name,email,gender
		</if>
		<if test="_databaseId=='oracle'">
			id,last_name,email,department_id
		</if>
	</sql>
	<insert id="addEmployeeBysql" databaseId="mysql">
		insert into tbl_employee(
			<!-- 引用外部定义的sql -->
			<include refid="insertColumn" ></include>
		) 
		values (#{id},#{lastName},#{email},#{gender})
	</insert>

5.<trim prefix="where" prefixOverrides="" suffix="" suffixOverrides="and">

prefix = "": Prefix: trim tab body importance to fight the result of the entire string string. prifix entire string to fight a prefix string

prifixOverrides = "": override prefix: removing the entire string of characters in front of the extra

suffix = "": Suffix: to fight the entire string plus a suffix string

suffixOverrides = "": suffix cover: removing the entire string of characters followed by excess

Alternatively integral values ​​beginning with the prefix, by replacing part of the overall final suffix.

select * from emp
    <trim prefix="where" prefixOverrides="" suffix="" suffixOverrides="and">
    <if test="job != null and job != ''">
    	job=#{job} and
    </if>
    <if test="topid != null and topid != ''">
    	topid=#{topid} and
    </if>
    </trim>

6.<chose><when test=""></when><when test=""></when></chose>

When first when established, it will not execute down. As long as a front does not hold, it is down to judge, find the end of the establishment.

select * from emp 
<where>
    <choose>
        <when test="name != null and name != ''">
        	name like concat('%',#{name},'%')
        </when>
        <when test="job != null and job !=''">
        	and job=#{job}
        </when>
    </choose>
</where>

 

Published 15 original articles · won praise 0 · Views 277

Guess you like

Origin blog.csdn.net/weixin_45146962/article/details/104864641