码迷,mamicode.com
首页 > 其他好文 > 详细

mybatis复习

时间:2020-11-06 01:27:37      阅读:14      评论:0      收藏:0      [点我收藏+]

标签:rtu   com   unp   mybatis框架   except   EDA   结构   pool   分析   

目录

============================================

01.Mybatis课程介绍及环境搭建

-------------------------------------------=

01.mybatis课程介绍

-------------------------------------------=

02.三层架构和ssm框架的对应关系

-------------------------------------------=

03.jdbc操作数据库的问题分析

-------------------------------------------=

04.mybatis概述

mybatis 通过 xml 或注解的方式将要执行的各种 statement 配置起来,并通过 java 对象和 statement 中sql 的动态参数进行映射生成最终执行的 sql 语句,最后由 mybatis 框架执行 sql 并将结果映射为 java 对象并返回。

-------------------------------------------=

05.mybatis环境搭建-前期准备

-------------------------------------------=

06.mybatis的环境搭建

-------------------------------------------=

07.环境搭建的注意事项

	第一步:创建maven工程并导入坐标
	第二步:创建实体类和dao的接口
	第三步:创建Mybatis的主配置文件
			SqlMapConifg.xml
	第四步:创建映射配置文件
			IUserDao.xml
第一个mybatis程序
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.mybatis</groupId>
	<artifactId>hellomybatis57</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<packaging>jar</packaging>

	<dependencies>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.4.5</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.6</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.12</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
		</dependency>
	</dependencies>

</project>
package com.domain;

import java.util.Date;

public class User{

    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username=‘" + username + ‘\‘‘ +
                ", birthday=" + birthday +
                ", sex=‘" + sex + ‘\‘‘ +
                ", address=‘" + address + ‘\‘‘ +
                ‘}‘;
    }
}

package com.dao;

import java.util.List;

import com.domain.User;

public interface IUserDao {

    /**
     * 查询所有操作
     * @return
     */
    List<User> findAll();
}

<?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">
<!-- mybatis的主配置文件 -->
<configuration>
    <!-- 配置环境 -->
    <environments default="mysql">
        <!-- 配置mysql的环境-->
        <environment id="mysql">
            <!-- 配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源(连接池) -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息 -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/easy"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
    <mappers>
        <mapper resource="com/dao/IUserMapper.xml"/>
    </mappers>
</configuration>
<?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.dao.IUserDao">
    <!--配置查询所有-->
    <select id="findAll" resultType="com.domain.User">
        select * from user
    </select>
</mapper>
package com.dao;

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 com.domain.User;

import java.io.InputStream;
import java.util.List;

public class MyTest {

    /**
     * 入门案例
     * @param args
     */
    public static void main(String[] args)throws Exception {
        //1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂生产SqlSession对象
        SqlSession session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        IUserDao userDao = session.getMapper(IUserDao.class);
        //5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println(user);
        }
        //6.释放资源
        session.close();
        in.close();
    }
}


运行结果:

2020-11-04 10:38:50,243 0      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter.
2020-11-04 10:38:50,399 156    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 10:38:50,400 157    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 10:38:50,400 157    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 10:38:50,400 157    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 10:38:50,554 311    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2020-11-04 10:38:50,823 580    [           main] DEBUG source.pooled.PooledDataSource  - Created connection 1459794865.
2020-11-04 10:38:50,824 581    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@5702b3b1]
2020-11-04 10:38:50,827 584    [           main] DEBUG       com.dao.IUserDao.findAll  - ==>  Preparing: select * from user 
2020-11-04 10:38:50,873 630    [           main] DEBUG       com.dao.IUserDao.findAll  - ==> Parameters: 
2020-11-04 10:38:50,922 679    [           main] DEBUG       com.dao.IUserDao.findAll  - <==      Total: 6
User{id=41, username=‘老王‘, birthday=Tue Feb 27 17:47:08 CST 2018, sex=‘男‘, address=‘北京‘}
User{id=42, username=‘小二王‘, birthday=Fri Mar 02 15:09:37 CST 2018, sex=‘女‘, address=‘北京金燕龙‘}
User{id=43, username=‘小二王‘, birthday=Sun Mar 04 11:34:34 CST 2018, sex=‘女‘, address=‘北京金燕龙‘}
User{id=45, username=‘星空集团‘, birthday=Sun Mar 04 12:04:06 CST 2018, sex=‘男‘, address=‘北京金燕龙‘}
User{id=46, username=‘老王‘, birthday=Wed Mar 07 17:37:26 CST 2018, sex=‘男‘, address=‘北京‘}
User{id=48, username=‘小马宝莉‘, birthday=Thu Mar 08 11:44:00 CST 2018, sex=‘女‘, address=‘北京修正‘}
2020-11-04 10:38:50,927 684    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@5702b3b1]
2020-11-04 10:38:50,928 685    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@5702b3b1]
2020-11-04 10:38:50,928 685    [           main] DEBUG source.pooled.PooledDataSource  - Returned connection 1459794865 to pool.

目录结构.png

技术图片

源码:hellomybatis57

============================================

02.Mybatis入门案例


1 mybatis的入门


3 mybatis入门案例中的设计模式分析


3 mybatis注解开发和编写dao实现类的方式

mybatis注解开发
package com.dao;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.domain.User;

public interface IUserDao {

    /**
     * 查询所有操作
     * @return
     */
	@Select("select * from user")
    List<User> findAll();
}

<?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">
<!-- mybatis的主配置文件 -->
<configuration>
    <!-- 配置环境 -->
    <environments default="mysql">
        <!-- 配置mysql的环境-->
        <environment id="mysql">
            <!-- 配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源(连接池) -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息 -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/easy"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件
        如果是用注解来配置的话,此处应该使用class属性指定被注解的dao全限定类名
    -->
    <mappers>
        <mapper class="com.dao.IUserDao"/>
    </mappers>
</configuration>
源码:hellomybatis58
编写dao实现类的方式
package com.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.dao.IUserDao;
import com.domain.User;

public class UserDao implements IUserDao{

	 private SqlSessionFactory factory;

	    public UserDao(SqlSessionFactory  factory){
	        this.factory = factory;
	    }


	    public List<User> findAll(){
	        //1.使用工厂创建SqlSession对象
	        SqlSession session = factory.openSession();
	        //2.使用session执行查询所有方法
	        List<User> users = session.selectList("com.dao.IUserDao.findAll");
	        session.close();
	        //3.返回查询结果
	        return users;
	    }
}

<?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.dao.IUserDao">
    <!--配置查询所有-->
    <select id="findAll" resultType="com.domain.User">
        select * from user
    </select>
</mapper>
<?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">
<!-- mybatis的主配置文件 -->
<configuration>
    <!-- 配置环境 -->
    <environments default="mysql">
        <!-- 配置mysql的环境-->
        <environment id="mysql">
            <!-- 配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源(连接池) -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息 -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/easy"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
    <mappers>
        <mapper resource="com/dao/IUserMapper.xml"/>
    </mappers>
</configuration>
package com.dao;

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 com.dao.impl.UserDao;
import com.domain.User;

import java.io.InputStream;
import java.util.List;

public class MyTest {

    /**
     * 入门案例
     * @param args
     */
    public static void main(String[] args)throws Exception {
    	//1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂创建dao对象
        IUserDao userDao = new UserDao(factory);
        //4.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println(user);
        }
        //5.释放资源
        in.close();
    }
}

源码:hellomybatis59

============================================

03.自定义Mybatis框架

============================================

04.自定义Mybatis框架基于注解开发

============================================

05.使用Mybatis完成CRUD


1 回顾Mybatis的环境搭建-实现查询所有功能


2 Mybatis的CRUD-保存操作

package com.domain;

import java.util.Date;

public class User{

    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username=‘" + username + ‘\‘‘ +
                ", birthday=" + birthday +
                ", sex=‘" + sex + ‘\‘‘ +
                ", address=‘" + address + ‘\‘‘ +
                ‘}‘;
    }
}

<?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.dao.IUserDao">
    <!--配置查询所有-->
    <select id="findAll" resultType="com.domain.User">
        select * from user
    </select>
    
     <!-- 保存用户 -->
    <insert id="saveUser" parameterType="com.domain.User">
       
        insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday});
    </insert>
</mapper>
package com.dao;

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.After;
import org.junit.Before;
import org.junit.Test;

import com.domain.User;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class MyTest {

	 private InputStream in;
	    private SqlSession sqlSession;
	    private IUserDao userDao;

	    @Before//用于在测试方法执行之前执行
	    public void init()throws Exception{
	        //1.读取配置文件,生成字节输入流
	        in = Resources.getResourceAsStream("SqlMapConfig.xml");
	        //2.获取SqlSessionFactory
	        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
	        //3.获取SqlSession对象
	        sqlSession = factory.openSession();
	        //4.获取dao的代理对象
	        userDao = sqlSession.getMapper(IUserDao.class);
	    }

	    @After//用于在测试方法执行之后执行
	    public void destroy()throws Exception{
	        //提交事务
	        sqlSession.commit();
	        //6.释放资源
	        sqlSession.close();
	        in.close();
	    }

	    /**
	     * 测试查询所有
	     */
	    @Test
	    public void testFindAll(){
	        //5.执行查询所有方法
	        List<User> users = userDao.findAll();
	        for(User user : users){
	            System.out.println(user);
	        }

	    }
	    
	    
	    /**
	     * 测试保存操作
	     */
	    @Test
	    public void testSave(){
	        User user = new User();
	        user.setUsername("曹操");
	        user.setAddress("北京市顺义区");
	        user.setSex("男");
	        user.setBirthday(new Date());
	        System.out.println("保存操作之前:"+user);
	        //5.执行保存方法
	        userDao.saveUser(user);

	        System.out.println("保存操作之后:"+user);
	    }
   
}


package com.dao;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.domain.QueryVo;
import com.domain.User;

public interface IUserDao {

	/**
     * 查询所有用户
     * @return
     */
    List<User> findAll();

    /**
     * 保存用户
     * @param user
     */
    void saveUser(User user);

    /**
     * 更新用户
     * @param user
     */
    void updateUser(User user);

    /**
     * 根据Id删除用户
     * @param userId
     */
    void deleteUser(Integer userId);

    /**
     * 根据id查询用户信息
     * @param userId
     * @return
     */
    User findById(Integer userId);

    /**
     * 根据名称模糊查询用户信息
     * @param username
     * @return
     */
    List<User> findByName(String username);

    /**
     * 查询总用户数
     * @return
     */
    int findTotal();

    /**
     * 根据queryVo中的条件查询用户
     * @param vo
     * @return
     */
    List<User> findUserByVo(QueryVo vo);
}

2020-11-04 17:51:09,756 1      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter.
2020-11-04 17:51:09,916 161    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 17:51:09,916 161    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 17:51:09,916 161    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 17:51:09,916 161    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
保存操作之前:User{id=null, username=‘曹操‘, birthday=Wed Nov 04 17:51:10 CST 2020, sex=‘男‘, address=‘北京市顺义区‘}
2020-11-04 17:51:10,021 266    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2020-11-04 17:51:10,269 514    [           main] DEBUG source.pooled.PooledDataSource  - Created connection 674483268.
2020-11-04 17:51:10,270 515    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@2833cc44]
2020-11-04 17:51:10,272 517    [           main] DEBUG      com.dao.IUserDao.saveUser  - ==>  Preparing: insert into user(username,address,sex,birthday)values(?,?,?,?); 
2020-11-04 17:51:10,336 581    [           main] DEBUG      com.dao.IUserDao.saveUser  - ==> Parameters: 曹操(String), 北京市顺义区(String), 男(String), 2020-11-04 17:51:10.005(Timestamp)
2020-11-04 17:51:10,337 582    [           main] DEBUG      com.dao.IUserDao.saveUser  - <==    Updates: 1
保存操作之后:User{id=null, username=‘曹操‘, birthday=Wed Nov 04 17:51:10 CST 2020, sex=‘男‘, address=‘北京市顺义区‘}
2020-11-04 17:51:10,338 583    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@2833cc44]
2020-11-04 17:51:10,341 586    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@2833cc44]
2020-11-04 17:51:10,341 586    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@2833cc44]
2020-11-04 17:51:10,342 587    [           main] DEBUG source.pooled.PooledDataSource  - Returned connection 674483268 to pool.


3 Mybatis的CRUD-修改和删除操作

CRUD-修改
<?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.dao.IUserDao">
    <!--配置查询所有-->
    <select id="findAll" resultType="com.domain.User">
        select * from user
    </select>
    
     <!-- 保存用户 -->
    <insert id="saveUser" parameterType="com.domain.User">
       
        insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday});
    </insert>
    
        <!-- 更新用户 -->
    <update id="updateUser" parameterType="com.domain.User">
        update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}
    </update>
</mapper>
package com.dao;

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.After;
import org.junit.Before;
import org.junit.Test;

import com.domain.User;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class MyTest {

	 private InputStream in;
	    private SqlSession sqlSession;
	    private IUserDao userDao;

	    @Before//用于在测试方法执行之前执行
	    public void init()throws Exception{
	        //1.读取配置文件,生成字节输入流
	        in = Resources.getResourceAsStream("SqlMapConfig.xml");
	        //2.获取SqlSessionFactory
	        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
	        //3.获取SqlSession对象
	        sqlSession = factory.openSession();
	        //4.获取dao的代理对象
	        userDao = sqlSession.getMapper(IUserDao.class);
	    }

	    @After//用于在测试方法执行之后执行
	    public void destroy()throws Exception{
	        //提交事务
	        sqlSession.commit();
	        //6.释放资源
	        sqlSession.close();
	        in.close();
	    }

	    /**
	     * 测试查询所有
	     */
	    @Test
	    public void testFindAll(){
	        //5.执行查询所有方法
	        List<User> users = userDao.findAll();
	        for(User user : users){
	            System.out.println(user);
	        }

	    }
	    
	    
	    /**
	     * 测试保存操作
	     */
	    @Test
	    public void testSave(){
	        User user = new User();
	        user.setUsername("曹操");
	        user.setAddress("北京市顺义区");
	        user.setSex("男");
	        user.setBirthday(new Date());
	        System.out.println("保存操作之前:"+user);
	        //5.执行保存方法
	        userDao.saveUser(user);

	        System.out.println("保存操作之后:"+user);
	    }
	    
	    /**
	     * 测试更新操作
	     */
	    @Test
	    public void testUpdate(){
	        User user = new User();
	        user.setId(49);
	        user.setUsername("testUpdate");
	        user.setAddress("北京市顺义区");
	        user.setSex("女");
	        user.setBirthday(new Date());

	        //5.执行保存方法
	        userDao.updateUser(user);
	    }
   
}
删除用户
	<!-- 删除用户 -->
	<delete id="deleteUser" parameterType="java.lang.Integer">
		delete from user where id = #{uid}
	</delete>
	    /**
	     * 测试删除操作
	     */
	    @Test
	    public void testDelete(){
	        //5.执行删除方法
	        userDao.deleteUser(49);
	    }

4 Mybatis的CRUD-查询一个和模糊查询

查询一个
	<!-- 根据id查询用户 -->
	<select id="findById" parameterType="java.lang.Integer"
		resultType="com.domain.User">
		select * from user where id = #{uid}
	</select>
	    /**
	     * 测试删除操作
	     */
	    @Test
	    public void testFindOne(){
	        //5.执行查询一个方法
	        User user = userDao.findById(46);
	        System.out.println(user);
	    }
模糊查询
	    <!-- 根据名称模糊查询 -->
    <select id="findByName" parameterType="java.lang.String" resultType="com.domain.User">
          select * from user where username like #{name}
        <!-- select * from user where username like ‘%${value}%‘-->
   </select>
/**
	 * 测试模糊查询操作
	 */
	@Test
	public void testFindByName() {

		// 5.执行查询一个方法
		List<User> users = userDao.findByName("%王%");
		// List<User> users = userDao.findByName("王");
		for (User user : users) {
			System.out.println(user);
		}
	}
2020-11-04 18:36:50,844 0      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter.
2020-11-04 18:36:51,008 164    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:36:51,008 164    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:36:51,008 164    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:36:51,008 164    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:36:51,140 296    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2020-11-04 18:36:51,399 555    [           main] DEBUG source.pooled.PooledDataSource  - Created connection 238157928.
2020-11-04 18:36:51,399 555    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@e320068]
2020-11-04 18:36:51,401 557    [           main] DEBUG    com.dao.IUserDao.findByName  - ==>  Preparing: select * from user where username like ? 
2020-11-04 18:36:51,459 615    [           main] DEBUG    com.dao.IUserDao.findByName  - ==> Parameters: %王%(String)
2020-11-04 18:36:51,516 672    [           main] DEBUG    com.dao.IUserDao.findByName  - <==      Total: 4
User{id=41, username=‘老王‘, birthday=Tue Feb 27 17:47:08 CST 2018, sex=‘男‘, address=‘北京‘}
User{id=42, username=‘小二王‘, birthday=Fri Mar 02 15:09:37 CST 2018, sex=‘女‘, address=‘北京金燕龙‘}
User{id=43, username=‘小二王‘, birthday=Sun Mar 04 11:34:34 CST 2018, sex=‘女‘, address=‘北京金燕龙‘}
User{id=46, username=‘老王‘, birthday=Wed Mar 07 17:37:26 CST 2018, sex=‘男‘, address=‘北京‘}
2020-11-04 18:36:51,521 677    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@e320068]
2020-11-04 18:36:51,522 678    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@e320068]
2020-11-04 18:36:51,522 678    [           main] DEBUG source.pooled.PooledDataSource  - Returned connection 238157928 to pool.

List<User> users = userDao.findByName("王");

select * from user where username like ‘%${value}%‘

2020-11-04 18:40:24,567 0      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter.
2020-11-04 18:40:24,735 168    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:40:24,735 168    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:40:24,735 168    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:40:24,735 168    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:40:24,870 303    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2020-11-04 18:40:25,109 542    [           main] DEBUG source.pooled.PooledDataSource  - Created connection 1489069835.
2020-11-04 18:40:25,111 544    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@58c1670b]
2020-11-04 18:40:25,113 546    [           main] DEBUG    com.dao.IUserDao.findByName  - ==>  Preparing: select * from user where username like ‘%王%‘ 
2020-11-04 18:40:25,159 592    [           main] DEBUG    com.dao.IUserDao.findByName  - ==> Parameters: 
2020-11-04 18:40:25,189 622    [           main] DEBUG    com.dao.IUserDao.findByName  - <==      Total: 4
User{id=41, username=‘老王‘, birthday=Tue Feb 27 17:47:08 CST 2018, sex=‘男‘, address=‘北京‘}
User{id=42, username=‘小二王‘, birthday=Fri Mar 02 15:09:37 CST 2018, sex=‘女‘, address=‘北京金燕龙‘}
User{id=43, username=‘小二王‘, birthday=Sun Mar 04 11:34:34 CST 2018, sex=‘女‘, address=‘北京金燕龙‘}
User{id=46, username=‘老王‘, birthday=Wed Mar 07 17:37:26 CST 2018, sex=‘男‘, address=‘北京‘}
2020-11-04 18:40:25,195 628    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@58c1670b]
2020-11-04 18:40:25,197 630    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@58c1670b]
2020-11-04 18:40:25,198 631    [           main] DEBUG source.pooled.PooledDataSource  - Returned connection 1489069835 to pool.


5 Mybatis的CRUD-查询返回一行一列和占位符分析

查询总记录条数
    <!-- 获取用户的总记录条数 -->
    <select id="findTotal" resultType="java.lang.Integer">
        select count(id) from user;
    </select>
	/**
     * 测试查询总记录条数
     */
    @Test
    public void testFindTotal(){
        //5.执行查询一个方法
        int count = userDao.findTotal();
        System.out.println(count);
    }

6 Mybatis的CRUD-保存操作的细节-获取保存数据的id

	<!-- 保存用户 -->
	<insert id="saveUser" parameterType="com.domain.User">
		<!-- 配置插入操作后,获取插入数据的id -->
		<selectKey keyProperty="id" keyColumn="id" resultType="java.lang.Integer"
			order="AFTER">
			select last_insert_id();
		</selectKey>
		insert into
		user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday});
	</insert>
	/**
	 * 测试保存操作
	 */
	@Test
	public void testSave() {
		User user = new User();
		user.setUsername("曹操");
		user.setAddress("北京市顺义区");
		user.setSex("男");
		user.setBirthday(new Date());
		System.out.println("保存操作之前:" + user);
		// 5.执行保存方法
		userDao.saveUser(user);

		System.out.println("保存操作之后:" + user);
	}
2020-11-04 18:48:01,917 0      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter.
2020-11-04 18:48:02,077 160    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:48:02,077 160    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:48:02,078 161    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:48:02,078 161    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
保存操作之前:User{id=null, username=‘曹操‘, birthday=Wed Nov 04 18:48:02 CST 2020, sex=‘男‘, address=‘北京市顺义区‘}
2020-11-04 18:48:02,190 273    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2020-11-04 18:48:02,438 521    [           main] DEBUG source.pooled.PooledDataSource  - Created connection 1399499405.
2020-11-04 18:48:02,438 521    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@536aaa8d]
2020-11-04 18:48:02,441 524    [           main] DEBUG      com.dao.IUserDao.saveUser  - ==>  Preparing: insert into user(username,address,sex,birthday)values(?,?,?,?); 
2020-11-04 18:48:02,523 606    [           main] DEBUG      com.dao.IUserDao.saveUser  - ==> Parameters: 曹操(String), 北京市顺义区(String), 男(String), 2020-11-04 18:48:02.175(Timestamp)
2020-11-04 18:48:02,524 607    [           main] DEBUG      com.dao.IUserDao.saveUser  - <==    Updates: 1
2020-11-04 18:48:02,527 610    [           main] DEBUG ao.IUserDao.saveUser!selectKey  - ==>  Preparing: select last_insert_id(); 
2020-11-04 18:48:02,527 610    [           main] DEBUG ao.IUserDao.saveUser!selectKey  - ==> Parameters: 
2020-11-04 18:48:02,550 633    [           main] DEBUG ao.IUserDao.saveUser!selectKey  - <==      Total: 1
保存操作之后:User{id=52, username=‘曹操‘, birthday=Wed Nov 04 18:48:02 CST 2020, sex=‘男‘, address=‘北京市顺义区‘}
2020-11-04 18:48:02,551 634    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@536aaa8d]
2020-11-04 18:48:02,553 636    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@536aaa8d]
2020-11-04 18:48:02,553 636    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@536aaa8d]
2020-11-04 18:48:02,553 636    [           main] DEBUG source.pooled.PooledDataSource  - Returned connection 1399499405 to pool.


7 Mybatis中参数的深入-使用实体类的包装对象作为查询条件

package com.domain;

public class QueryVo {
	private User user;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

}

	<!-- 根据queryVo的条件查询用户 -->
	<select id="findUserByVo" parameterType="com.domain.QueryVo"
		resultType="com.domain.User">
		select * from user where username like #{user.username}
	</select>
    /**
     * 测试使用QueryVo作为查询条件
     */
    @Test
    public void testFindByVo(){
        QueryVo vo = new QueryVo();
        User user = new User();
        user.setUsername("%王%");
        vo.setUser(user);
        //5.执行查询一个方法
        List<User> users = userDao.findUserByVo(vo);
        for(User u : users){
            System.out.println(u);
        }
    }
2020-11-04 18:54:40,065 0      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter.
2020-11-04 18:54:40,228 163    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:54:40,228 163    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:54:40,228 163    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:54:40,228 163    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 18:54:40,352 287    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2020-11-04 18:54:40,608 543    [           main] DEBUG source.pooled.PooledDataSource  - Created connection 662822946.
2020-11-04 18:54:40,609 544    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@2781e022]
2020-11-04 18:54:40,611 546    [           main] DEBUG  com.dao.IUserDao.findUserByVo  - ==>  Preparing: select * from user where username like ? 
2020-11-04 18:54:40,654 589    [           main] DEBUG  com.dao.IUserDao.findUserByVo  - ==> Parameters: %王%(String)
2020-11-04 18:54:40,718 653    [           main] DEBUG  com.dao.IUserDao.findUserByVo  - <==      Total: 4
User{id=41, username=‘老王‘, birthday=Tue Feb 27 17:47:08 CST 2018, sex=‘男‘, address=‘北京‘}
User{id=42, username=‘小二王‘, birthday=Fri Mar 02 15:09:37 CST 2018, sex=‘女‘, address=‘北京金燕龙‘}
User{id=43, username=‘小二王‘, birthday=Sun Mar 04 11:34:34 CST 2018, sex=‘女‘, address=‘北京金燕龙‘}
User{id=46, username=‘老王‘, birthday=Wed Mar 07 17:37:26 CST 2018, sex=‘男‘, address=‘北京‘}
2020-11-04 18:54:40,723 658    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@2781e022]
2020-11-04 18:54:40,723 658    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@2781e022]
2020-11-04 18:54:40,723 658    [           main] DEBUG source.pooled.PooledDataSource  - Returned connection 662822946 to pool.

源码:hellomybatis60

8 Mybatis中的返回值深入-调整实体类属性解决增和改方法的报错


9 Mybatis中的返回值深入-解决实体类属性和数据库列名不对应的两种方式

源码:hellomybatis61

============================================

06.使用Mybatis完成DAO层的开发

源码:day02_eesy_02mybatsiDAO

1 Mybatis中编写dao实现类的使用方式-查询列表


2 Mybatis中编写dao实现类的使用-保存操作


3 Mybatis中编写dao实现类的使用-修改删除等其他操作


4 Mybatis中使用Dao实现类的执行过程分析-查询方法


4 Mybatis中使用Dao实现类的执行过程分析-查询方法1


5 Mybatis中使用Dao实现类的执行过程分析-增删改方法


6 Mybatis中使用代理Dao的执行过程分析(1)


7 properties标签的使用及细节


8 typeAliases标签和package标签

mappers(映射器)
使用相对于类路径的资源
如: <mapper resource="com/dao/IUserDao.xml" />
使用 mapper 接口类路径
如: <mapper class="com.dao.UserDao"/>
注意:此种方法要求 mapper 接口名称和 mapper 映射文件名称相同,且放在同一个目录中。
注册指定包下的所有 mapper 接口
如: <package name="cn.itcast.mybatis.mapper"/>
注意:此种方法要求 mapper 接口名称和 mapper 映射文件名称相同,且放在同一个目录中

============================================

07.Mybatis的连接池及事务


1 今日课程内容介绍


2 连接池介绍


3 mybatis连接池的分类


4 mybatis中使用unpooled配置连接池的原理分析


5 mybatis中使用poolead配置连接的原理分析


6 mybatis中的事务原理和自动提交设置

============================================

08.动态SQL

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(32) NOT NULL COMMENT ‘用户名称‘,
  `birthday` datetime default NULL COMMENT ‘生日‘,
  `sex` char(1) default NULL COMMENT ‘性别‘,
  `address` varchar(256) default NULL COMMENT ‘地址‘,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (41,‘老王‘,‘2018-02-27 17:47:08‘,‘男‘,‘北京‘),(42,‘小二王‘,‘2018-03-02 15:09:37‘,‘女‘,‘北京金燕龙‘),(43,‘小二王‘,‘2018-03-04 11:34:34‘,‘女‘,‘北京金燕龙‘),(45,‘喵喵喵‘,‘2018-03-04 12:04:06‘,‘男‘,‘北京金燕龙‘),(46,‘老王‘,‘2018-03-07 17:37:26‘,‘男‘,‘北京‘),(48,‘小马宝莉‘,‘2018-03-08 11:44:00‘,‘女‘,‘北京修正‘);

DROP TABLE IF EXISTS `account`;

CREATE TABLE `account` (
  `ID` int(11) NOT NULL COMMENT ‘编号‘,
  `UID` int(11) default NULL COMMENT ‘用户编号‘,
  `MONEY` double default NULL COMMENT ‘金额‘,
  PRIMARY KEY  (`ID`),
  KEY `FK_Reference_8` (`UID`),
  CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `account`(`ID`,`UID`,`MONEY`) values (1,46,1000),(2,45,1000),(3,46,2000);

DROP TABLE IF EXISTS `role`;

CREATE TABLE `role` (
  `ID` int(11) NOT NULL COMMENT ‘编号‘,
  `ROLE_NAME` varchar(30) default NULL COMMENT ‘角色名称‘,
  `ROLE_DESC` varchar(60) default NULL COMMENT ‘角色描述‘,
  PRIMARY KEY  (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `role`(`ID`,`ROLE_NAME`,`ROLE_DESC`) values (1,‘院长‘,‘管理整个学院‘),(2,‘总裁‘,‘管理整个公司‘),(3,‘校长‘,‘管理整个学校‘);

DROP TABLE IF EXISTS `user_role`;

CREATE TABLE `user_role` (
  `UID` int(11) NOT NULL COMMENT ‘用户编号‘,
  `RID` int(11) NOT NULL COMMENT ‘角色编号‘,
  PRIMARY KEY  (`UID`,`RID`),
  KEY `FK_Reference_10` (`RID`),
  CONSTRAINT `FK_Reference_10` FOREIGN KEY (`RID`) REFERENCES `role` (`ID`),
  CONSTRAINT `FK_Reference_9` FOREIGN KEY (`UID`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `user_role`(`UID`,`RID`) values (41,1),(45,1),(41,2);


01.mybatis中的动态sql语句-if标签


02.mybatis中动态sql语句-where标签的使用

package com.domain;

import java.util.Date;

public class User {

	private Integer userId;
	private String userName;
	private String userAddress;
	private String userSex;
	private Date userBirthday;

	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserAddress() {
		return userAddress;
	}

	public void setUserAddress(String userAddress) {
		this.userAddress = userAddress;
	}

	public String getUserSex() {
		return userSex;
	}

	public void setUserSex(String userSex) {
		this.userSex = userSex;
	}

	public Date getUserBirthday() {
		return userBirthday;
	}

	public void setUserBirthday(Date userBirthday) {
		this.userBirthday = userBirthday;
	}

	@Override
	public String toString() {
		return "User{" + "userId=" + userId + ", userName=‘" + userName + ‘\‘‘ + ", userAddress=‘" + userAddress + ‘\‘‘
				+ ", userSex=‘" + userSex + ‘\‘‘ + ", userBirthday=" + userBirthday + ‘}‘;
	}
}

package com.domain;

public class QueryVo {
	private User user;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

}

<?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.dao.IUserDao">

	<!-- 配置 查询结果的列名和实体类的属性名的对应关系 -->
	<resultMap id="userMap" type="com.domain.User">
		<!-- 主键字段的对应 -->
		<id property="userId" column="id"></id>
		<!--非主键字段的对应 -->
		<result property="userName" column="username"></result>
		<result property="userAddress" column="address"></result>
		<result property="userSex" column="sex"></result>
		<result property="userBirthday" column="birthday"></result>
	</resultMap>

	<!--配置查询所有 -->
	<select id="findAll" resultMap="userMap">
		select * from user
	</select>

	<!-- 保存用户 -->
	<insert id="saveUser" parameterType="com.domain.User">
		<!-- 配置插入操作后,获取插入数据的id -->
		<selectKey keyProperty="userId" keyColumn="id"
			resultType="java.lang.Integer" order="AFTER">
			select last_insert_id();
		</selectKey>
		insert into
		user(username,address,sex,birthday)values(#{userName},#{userAddress},#{userSex},#{userBirthday});
	</insert>

	<!-- 根据id查询用户 -->
    <select id="findById" parameterType="java.lang.Integer" resultMap="userMap">
        select * from user where id = #{uid}
    </select>

    <!-- 根据名称模糊查询 -->
    <select id="findByName" parameterType="java.lang.String" resultMap="userMap">
          select * from user where username like #{name}
   </select>

    <!-- 根据queryVo的条件查询用户 -->
    <select id="findUserByVo" parameterType="com.domain.QueryVo" resultMap="userMap">
        select * from user where username like #{user.userName}
    </select>
    
        <select id="findUserByCondition" resultMap="userMap" parameterType="com.domain.User">
        select * from user
        <where>
            <if test="userName != null">
                and username = #{userName}
            </if>
            <if test="userSex != null">
                and sex = #{userSex}
            </if>
        </where>
    </select>

</mapper>
package com.dao;

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.After;
import org.junit.Before;
import org.junit.Test;

import com.domain.QueryVo;
import com.domain.User;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class MyTest {

    private InputStream in;
    private SqlSession sqlSession;
    private IUserDao userDao;

    @Before//用于在测试方法执行之前执行
    public void init()throws Exception{
        //1.读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        sqlSession = factory.openSession();
        //4.获取dao的代理对象
        userDao = sqlSession.getMapper(IUserDao.class);
    }

    @After//用于在测试方法执行之后执行
    public void destroy()throws Exception{
        //提交事务
        sqlSession.commit();
        //6.释放资源
        sqlSession.close();
        in.close();
    }

    /**
     * 测试查询所有
     */
    @Test
    public void testFindAll(){
        //5.执行查询所有方法
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println(user);
        }

    }
    
    /**
     * 测试删除操作
     */
    @Test
    public void testFindOne(){
        //5.执行查询一个方法
        User  user = userDao.findById(54);
        System.out.println(user);
    }

    /**
     * 测试模糊查询操作
     */
    @Test
    public void testFindByName(){
        //5.执行查询一个方法
        List<User> users = userDao.findByName("%王%");
//        List<User> users = userDao.findByName("王");
        for(User user : users){
            System.out.println(user);
        }
    }

    /**
     * 测试使用QueryVo作为查询条件
     */
    @Test
    public void testFindByVo() {
        QueryVo vo = new QueryVo();
        User user = new User();
        user.setUserName("%王%");
        vo.setUser(user);
        //5.执行查询一个方法
        List<User> users = userDao.findUserByVo(vo);
        for (User u : users) {
            System.out.println(u);
        }
    }
    
    /**
     * 测试查询所有
     */
    @Test
    public void testFindByCondition(){
        User u = new User();
        u.setUserName("老王");
//        u.setUserSex("女");

        //5.执行查询所有方法
        List<User> users = userDao.findUserByCondition(u);
        for(User user : users){
            System.out.println(user);
        }

    }
    
}

2020-11-04 19:50:08,545 0      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter.
2020-11-04 19:50:08,716 171    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 19:50:08,716 171    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 19:50:08,717 172    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 19:50:08,717 172    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 19:50:08,894 349    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2020-11-04 19:50:09,189 644    [           main] DEBUG source.pooled.PooledDataSource  - Created connection 988458918.
2020-11-04 19:50:09,189 644    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3aeaafa6]
2020-11-04 19:50:09,192 647    [           main] DEBUG o.IUserDao.findUserByCondition  - ==>  Preparing: select * from user WHERE username = ? 
2020-11-04 19:50:09,246 701    [           main] DEBUG o.IUserDao.findUserByCondition  - ==> Parameters: 老王(String)
2020-11-04 19:50:09,285 740    [           main] DEBUG o.IUserDao.findUserByCondition  - <==      Total: 2
User{userId=41, userName=‘老王‘, userAddress=‘北京‘, userSex=‘男‘, userBirthday=Tue Feb 27 17:47:08 CST 2018}
User{userId=46, userName=‘老王‘, userAddress=‘北京‘, userSex=‘女‘, userBirthday=Wed Mar 07 17:37:26 CST 2018}
2020-11-04 19:50:09,289 744    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3aeaafa6]
2020-11-04 19:50:09,290 745    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3aeaafa6]
2020-11-04 19:50:09,290 745    [           main] DEBUG source.pooled.PooledDataSource  - Returned connection 988458918 to pool.


03.mybatis中动态sql语句-foreach和sql标签

select * from user where id in(41,45,54)
41	老王	2018-02-27 17:47:08	男	北京
45	星空集团	2018-03-04 12:04:06	男	北京金燕龙
54	喵喵喵	2020-11-04 19:03:59	男	北京市顺义区
package com.domain;

import java.util.List;

public class QueryVo {

    private User user;

    private List<Integer> ids;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<Integer> getIds() {
        return ids;
    }

    public void setIds(List<Integer> ids) {
        this.ids = ids;
    }
}

     <!-- 根据queryvo中的Id集合实现查询用户列表 -->
    <select id="findUserInIds" resultMap="userMap" parameterType="com.domain.QueryVo">
        select * from user
        <where>
            <if test="ids != null and ids.size()>0">
                <foreach collection="ids" open="and id in (" close=")" item="uid" separator=",">
                    #{uid}
                </foreach>
            </if>
        </where>
    </select>
 /**
     * 测试foreach标签的使用
     */
    @Test
    public void testFindInIds(){
        QueryVo vo = new QueryVo();
        List<Integer> list = new ArrayList<Integer>();
        list.add(41);
        list.add(45);
        list.add(54);
        vo.setIds(list);

        //5.执行查询所有方法
        List<User> users = userDao.findUserInIds(vo);
        for(User user : users){
            System.out.println(user);
        }

    }
2020-11-04 20:03:46,291 0      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter.
2020-11-04 20:03:46,462 171    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 20:03:46,463 172    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 20:03:46,463 172    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 20:03:46,463 172    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 20:03:46,661 370    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2020-11-04 20:03:46,932 641    [           main] DEBUG source.pooled.PooledDataSource  - Created connection 926370398.
2020-11-04 20:03:46,932 641    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@37374a5e]
2020-11-04 20:03:46,949 658    [           main] DEBUG com.dao.IUserDao.findUserInIds  - ==>  Preparing: select * from user WHERE id in ( ? , ? , ? ) 
2020-11-04 20:03:47,005 714    [           main] DEBUG com.dao.IUserDao.findUserInIds  - ==> Parameters: 41(Integer), 45(Integer), 54(Integer)
2020-11-04 20:03:47,055 764    [           main] DEBUG com.dao.IUserDao.findUserInIds  - <==      Total: 3
User{userId=41, userName=‘老王‘, userAddress=‘北京‘, userSex=‘男‘, userBirthday=Tue Feb 27 17:47:08 CST 2018}
User{userId=45, userName=‘星空集团‘, userAddress=‘北京金燕龙‘, userSex=‘男‘, userBirthday=Sun Mar 04 12:04:06 CST 2018}
User{userId=54, userName=‘喵喵喵‘, userAddress=‘北京市顺义区‘, userSex=‘男‘, userBirthday=Wed Nov 04 19:03:59 CST 2020}
2020-11-04 20:03:47,059 768    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@37374a5e]
2020-11-04 20:03:47,059 768    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@37374a5e]
2020-11-04 20:03:47,060 769    [           main] DEBUG source.pooled.PooledDataSource  - Returned connection 926370398 to pool.

源码:hellomybatis62

============================================

09.Mybatis的多表操作


1 mybatis表之间关系分析


2 完成account表的建立及实现单表查询


3 完成account的一对一操作-通过写account的子类方式查询

测试查询所有账户,同时包含用户名称和地址
41	老王	2018-02-27 17:47:08	男	北京
42	小二王	2018-03-02 15:09:37	女	北京金燕龙
43	小二王	2018-03-04 11:34:34	女	北京金燕龙
45	星空集团	2018-03-04 12:04:06	男	北京金燕龙
46	老王	2018-03-07 17:37:26	女	北京
54	喵喵喵	2020-11-04 19:03:59	男	北京市顺义区
select u.*, a.id as aid, a.uid,a.money from account a, user u where u.id =a.uid;
id	username	birthday	sex	address	aid	uid	money
41	老王	2018-02-27 17:47:08	男	北京	1	41	1000
45	星空集团	2018-03-04 12:04:06	男	北京金燕龙	2	45	1000
41	老王	2018-02-27 17:47:08	男	北京	3	41	2000
package com.domain;

public class Account {

	private Integer id;
	private Integer uid;
	private Double money;

	public Integer getId() {
		return id;
	}

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

	public Integer getUid() {
		return uid;
	}

	public void setUid(Integer uid) {
		this.uid = uid;
	}

	public Double getMoney() {
		return money;
	}

	public void setMoney(Double money) {
		this.money = money;
	}

	@Override
	public String toString() {
		return "Account [id=" + id + ", uid=" + uid + ", money=" + money + "]";
	}

}

package com.domain;

import java.util.Date;

public class User{

    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username=‘" + username + ‘\‘‘ +
                ", birthday=" + birthday +
                ", sex=‘" + sex + ‘\‘‘ +
                ", address=‘" + address + ‘\‘‘ +
                ‘}‘;
    }
}

package com.domain;

public class AccountUser extends Account {

    private String username;
    private String address;

    public String getUsername() {
        return username;
    }

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

    public String getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return super.toString()+"        AccountUser{" +
                "username=‘" + username + ‘\‘‘ +
                ", address=‘" + address + ‘\‘‘ +
                ‘}‘;
    }
}


<?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.dao.IAccountDao">

    <!--配置查询所有-->
    <select id="findAll" resultType="com.domain.Account">
        select * from account
    </select>
    
        <!--查询所有账户同时包含用户名和地址信息-->
    <select id="findAllAccount" resultType="com.domain.AccountUser">
        select a.*,u.username,u.address from account a , user u where u.id = a.uid;
    </select>
    
</mapper>
package com.dao;

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.After;
import org.junit.Before;
import org.junit.Test;

import com.domain.Account;
import com.domain.AccountUser;

import java.io.InputStream;
import java.util.List;

public class MyAccount {

	private InputStream in;
	private SqlSession sqlSession;
	private IAccountDao accountDao;

	@Before // 用于在测试方法执行之前执行
	public void init() throws Exception {
		// 1.读取配置文件,生成字节输入流
		in = Resources.getResourceAsStream("SqlMapConfig.xml");
		// 2.获取SqlSessionFactory
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		// 3.获取SqlSession对象
		sqlSession = factory.openSession(true);
		// 4.获取dao的代理对象
		accountDao = sqlSession.getMapper(IAccountDao.class);
	}

	@After // 用于在测试方法执行之后执行
	public void destroy() throws Exception {
		// 提交事务
		// sqlSession.commit();
		// 6.释放资源
		sqlSession.close();
		in.close();
	}

	/**
	 * 测试查询所有
	 */
	@Test
	public void testFindAll() {
		List<Account> accounts = accountDao.findAll();
		for (Account account : accounts) {
			System.out.println("--------每个account的信息------------");
			System.out.println(account);
		}
	}
	
	 /**
     * 测试查询所有账户,同时包含用户名称和地址
     */
    @Test
    public void testFindAllAccountUser(){
        List<AccountUser> aus = accountDao.findAllAccount();
        for(AccountUser au : aus){
            System.out.println(au);
        }
    }
}

2020-11-04 20:46:50,544 0      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter.
2020-11-04 20:46:50,728 184    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 20:46:50,728 184    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 20:46:50,729 185    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 20:46:50,729 185    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 20:46:50,888 344    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2020-11-04 20:46:51,190 646    [           main] DEBUG source.pooled.PooledDataSource  - Created connection 238157928.
2020-11-04 20:46:51,193 649    [           main] DEBUG dao.IAccountDao.findAllAccount  - ==>  Preparing: select a.*,u.username,u.address from account a , user u where u.id = a.uid; 
2020-11-04 20:46:51,242 698    [           main] DEBUG dao.IAccountDao.findAllAccount  - ==> Parameters: 
2020-11-04 20:46:51,288 744    [           main] DEBUG dao.IAccountDao.findAllAccount  - <==      Total: 3
Account [id=1, uid=41, money=1000.0]        AccountUser{username=‘老王‘, address=‘北京‘}
Account [id=2, uid=45, money=1000.0]        AccountUser{username=‘星空集团‘, address=‘北京金燕龙‘}
Account [id=3, uid=41, money=2000.0]        AccountUser{username=‘老王‘, address=‘北京‘}
2020-11-04 20:46:51,289 745    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@e320068]
2020-11-04 20:46:51,289 745    [           main] DEBUG source.pooled.PooledDataSource  - Returned connection 238157928 to pool.

源码:hellomybatis63

4 完成account一对一操作-建立实体类关系的方式

package com.domain;

public class Account {

	private Integer id;
	private Integer uid;
	private Double money;
	
	//从表实体应该包含一个主表实体的对象引用
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

	public Integer getId() {
		return id;
	}

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

	public Integer getUid() {
		return uid;
	}

	public void setUid(Integer uid) {
		this.uid = uid;
	}

	public Double getMoney() {
		return money;
	}

	public void setMoney(Double money) {
		this.money = money;
	}

	@Override
	public String toString() {
		return "Account [id=" + id + ", uid=" + uid + ", money=" + money + ", user=" + user + "]";
	}
}

package com.domain;

import java.util.Date;

public class User{

    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username=‘" + username + ‘\‘‘ +
                ", birthday=" + birthday +
                ", sex=‘" + sex + ‘\‘‘ +
                ", address=‘" + address + ‘\‘‘ +
                ‘}‘;
    }
}

package com.dao;

import java.util.List;

import com.domain.Account;

public interface IAccountDao {

	/**
     * 查询所有账户,同时还要获取到当前账户的所属用户信息
     * @return
     */
    List<Account> findAll();
    /**
     * 查询所有账户,并且带有用户名称和地址信息
     * @return
     */
    List<Account> findAllAccount();
}

<?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.dao.IAccountDao">

	<!-- 定义封装account和user的resultMap -->
	<resultMap id="accountUserMap" type="com.domain.Account">
		<id property="id" column="aid"></id>
		<result property="uid" column="uid"></result>
		<result property="money" column="money"></result>
		<!-- 一对一的关系映射:配置封装user的内容 -->
		<association property="user" column="uid" javaType="com.domain.User">
			<id property="id" column="id"></id>
			<result column="username" property="username"></result>
			<result column="address" property="address"></result>
			<result column="sex" property="sex"></result>
			<result column="birthday" property="birthday"></result>
		</association>
	</resultMap>

	<!--配置查询所有 -->
	<select id="findAll" resultType="com.domain.Account">
		select * from account
	</select>

	<!--查询所有账户同时包含用户名和地址信息 -->
	<select id="findAllAccount" resultMap="accountUserMap">
		select u.*,a.id as aid,a.uid,a.money from account a , user u where u.id =
		a.uid;
	</select>

</mapper>
package com.dao;

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.After;
import org.junit.Before;
import org.junit.Test;

import com.domain.Account;

import java.io.InputStream;
import java.util.List;

public class MyAccount {

	private InputStream in;
	private SqlSession sqlSession;
	private IAccountDao accountDao;

	@Before // 用于在测试方法执行之前执行
	public void init() throws Exception {
		// 1.读取配置文件,生成字节输入流
		in = Resources.getResourceAsStream("SqlMapConfig.xml");
		// 2.获取SqlSessionFactory
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		// 3.获取SqlSession对象
		sqlSession = factory.openSession(true);
		// 4.获取dao的代理对象
		accountDao = sqlSession.getMapper(IAccountDao.class);
	}

	@After // 用于在测试方法执行之后执行
	public void destroy() throws Exception {
		// 提交事务
		// sqlSession.commit();
		// 6.释放资源
		sqlSession.close();
		in.close();
	}

	/**
	 * 测试查询所有
	 */
	@Test
	public void testFindAll() {
		List<Account> accounts = accountDao.findAll();
		for (Account account : accounts) {
			System.out.println(account);
		}
	}

	/**
	 * 测试查询所有账户,同时包含用户名称和地址
	 */
	@Test
	public void testFindAllAccountUser() {
		List<Account> accounts = accountDao.findAllAccount();
		for (Account account : accounts) {
			System.out.println(account);

			System.out.println(account.getUser());
		}

	}
}

2020-11-04 21:19:18,954 0      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter.
2020-11-04 21:19:19,114 160    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 21:19:19,114 160    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 21:19:19,114 160    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 21:19:19,114 160    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 21:19:19,256 302    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2020-11-04 21:19:19,510 556    [           main] DEBUG source.pooled.PooledDataSource  - Created connection 811587677.
2020-11-04 21:19:19,512 558    [           main] DEBUG dao.IAccountDao.findAllAccount  - ==>  Preparing: select u.*,a.id as aid,a.uid,a.money from account a , user u where u.id = a.uid; 
2020-11-04 21:19:19,555 601    [           main] DEBUG dao.IAccountDao.findAllAccount  - ==> Parameters: 
2020-11-04 21:19:19,597 643    [           main] DEBUG dao.IAccountDao.findAllAccount  - <==      Total: 3
Account [id=1, uid=41, money=1000.0, user=User{id=41, username=‘老王‘, birthday=Tue Feb 27 17:47:08 CST 2018, sex=‘男‘, address=‘北京‘}]
User{id=41, username=‘老王‘, birthday=Tue Feb 27 17:47:08 CST 2018, sex=‘男‘, address=‘北京‘}
Account [id=2, uid=45, money=1000.0, user=User{id=45, username=‘星空集团‘, birthday=Sun Mar 04 12:04:06 CST 2018, sex=‘男‘, address=‘北京金燕龙‘}]
User{id=45, username=‘星空集团‘, birthday=Sun Mar 04 12:04:06 CST 2018, sex=‘男‘, address=‘北京金燕龙‘}
Account [id=3, uid=41, money=2000.0, user=User{id=41, username=‘老王‘, birthday=Tue Feb 27 17:47:08 CST 2018, sex=‘男‘, address=‘北京‘}]
User{id=41, username=‘老王‘, birthday=Tue Feb 27 17:47:08 CST 2018, sex=‘男‘, address=‘北京‘}
2020-11-04 21:19:19,602 648    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@305fd85d]
2020-11-04 21:19:19,602 648    [           main] DEBUG source.pooled.PooledDataSource  - Returned connection 811587677 to pool.

源码:hellomybatis64

5 完成user的一对多查询操作

 select u.*, a.id as aid, a.uid,a.money from user u left outer join account a on u.id = a.uid
id	username	birthday	sex	address	aid	uid	money
41	老王	2018-02-27 17:47:08	男	北京	1	41	1000
41	老王	2018-02-27 17:47:08	男	北京	3	41	2000
42	小二王	2018-03-02 15:09:37	女	北京金燕龙			
43	小二王	2018-03-04 11:34:34	女	北京金燕龙			
45	星空集团	2018-03-04 12:04:06	男	北京金燕龙	2	45	1000
46	老王	2018-03-07 17:37:26	女	北京			
54	喵喵喵	2020-11-04 19:03:59	男	北京市顺义区			
package com.domain;

import java.util.Date;
import java.util.List;

public class UserAccount{

    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    
  //一对多关系映射:主表实体应该包含从表实体的集合引用
    private List<Account> accounts;

    public List<Account> getAccounts() {
		return accounts;
	}

	public void setAccounts(List<Account> accounts) {
		this.accounts = accounts;
	}

	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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

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

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", sex=" + sex + ", address="
				+ address + ", accounts=" + accounts + "]";
	}

}

package com.domain;

import java.util.Date;
import java.util.List;

public class User{

    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
	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 Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", sex=" + sex + ", address="
				+ address + "]";
	}
 
}

package com.domain;

public class Account {

	private Integer id;
	private Integer uid;
	private Double money;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Integer getUid() {
		return uid;
	}
	public void setUid(Integer uid) {
		this.uid = uid;
	}
	public Double getMoney() {
		return money;
	}
	public void setMoney(Double money) {
		this.money = money;
	}
	@Override
	public String toString() {
		return "Account [id=" + id + ", uid=" + uid + ", money=" + money + "]";
	}

}

<?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.dao.IUserDao">

<!-- 定义User的resultMap-->
    <resultMap id="userAccountMap" type="com.domain.UserAccount">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="address" column="address"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>
        <!-- 配置user对象中accounts集合的映射 -->
        <collection property="accounts" ofType="com.domain.Account">
            <id column="aid" property="id"></id>
            <result column="uid" property="uid"></result>
            <result column="money" property="money"></result>
        </collection>
    </resultMap>
    <!--配置查询所有-->
    <select id="findAll" resultMap="userAccountMap">
        select u.*, a.id as aid, a.uid,a.money from user u left outer join account a on u.id = a.uid
    </select>
    
    <!-- 根据id查询用户 -->
    <select id="findById" parameterType="java.lang.String" resultType="com.domain.User">
        select * from user where id = #{uid}
    </select>
</mapper>
package com.dao;

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.After;
import org.junit.Before;
import org.junit.Test;

import com.domain.User;
import com.domain.UserAccount;

import java.io.InputStream;
import java.util.List;

public class MyTest {

	private InputStream in;
    private SqlSession sqlSession;
    private IUserDao userDao;

    @Before//用于在测试方法执行之前执行
    public void init()throws Exception{
        //1.读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        sqlSession = factory.openSession(true);
        //4.获取dao的代理对象
        userDao = sqlSession.getMapper(IUserDao.class);
    }

    @After//用于在测试方法执行之后执行
    public void destroy()throws Exception{
        //提交事务
        // sqlSession.commit();
        //6.释放资源
        sqlSession.close();
        in.close();
    }

    /**
     * 测试查询所有
     */
    @Test
    public void testFindAll(){
        List<UserAccount> users = userDao.findAll();
        for(UserAccount user : users){
            System.out.println("-----每个用户的信息------");
            System.out.println(user);
        }
    }
}


2020-11-04 22:10:27,079 0      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter.
2020-11-04 22:10:27,289 210    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 22:10:27,289 210    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 22:10:27,289 210    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 22:10:27,290 211    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 22:10:27,429 350    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2020-11-04 22:10:27,691 612    [           main] DEBUG source.pooled.PooledDataSource  - Created connection 289639718.
2020-11-04 22:10:27,694 615    [           main] DEBUG       com.dao.IUserDao.findAll  - ==>  Preparing: select u.*, a.id as aid, a.uid,a.money from user u left outer join account a on u.id = a.uid 
2020-11-04 22:10:27,742 663    [           main] DEBUG       com.dao.IUserDao.findAll  - ==> Parameters: 
2020-11-04 22:10:27,799 720    [           main] DEBUG       com.dao.IUserDao.findAll  - <==      Total: 7
-----每个用户的信息------
User [id=41, username=老王, birthday=Tue Feb 27 17:47:08 CST 2018, sex=男, address=北京, accounts=[Account [id=1, uid=41, money=1000.0], Account [id=3, uid=41, money=2000.0]]]
-----每个用户的信息------
User [id=42, username=小二王, birthday=Fri Mar 02 15:09:37 CST 2018, sex=女, address=北京金燕龙, accounts=[]]
-----每个用户的信息------
User [id=43, username=小二王, birthday=Sun Mar 04 11:34:34 CST 2018, sex=女, address=北京金燕龙, accounts=[]]
-----每个用户的信息------
User [id=45, username=星空集团, birthday=Sun Mar 04 12:04:06 CST 2018, sex=男, address=北京金燕龙, accounts=[Account [id=2, uid=45, money=1000.0]]]
-----每个用户的信息------
User [id=46, username=老王, birthday=Wed Mar 07 17:37:26 CST 2018, sex=女, address=北京, accounts=[]]
-----每个用户的信息------
User [id=54, username=喵喵喵, birthday=Wed Nov 04 19:03:59 CST 2020, sex=男, address=北京市顺义区, accounts=[]]
2020-11-04 22:10:27,804 725    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@11438d26]
2020-11-04 22:10:27,804 725    [           main] DEBUG source.pooled.PooledDataSource  - Returned connection 289639718 to pool.

源码:hellomybatis65

6 分析mybatis多对多的步骤并搭建环境

41	1
45	1
41	2
ID	ROLE_NAME	ROLE_DESC
1	院长	管理整个学院
2	总裁	管理整个公司
3	校长	管理整个学校

7 mybatis多对多准备角色表的实体类和映射配置


8 mybatis多对多操作-查询角色获取角色下所属用户信息

SELECT * FROM role r LEFT OUTER JOIN user_role ur ON r.id = ur.rid
ID	ROLE_NAME	ROLE_DESC	UID	RID
1	院长	管理整个学院	41	1
1	院长	管理整个学院	45	1
2	总裁	管理整个公司	41	2
3	校长	管理整个学校		
package com.domain;

import java.util.List;

public class RoleUser {
	
	private Integer roleId;
	private String roleName;
	private String roleDesc;
	
	//多对多的关系映射:一个角色可以赋予多个用户
    private List<User> users;

	public Integer getRoleId() {
		return roleId;
	}

	public void setRoleId(Integer roleId) {
		this.roleId = roleId;
	}

	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	public String getRoleDesc() {
		return roleDesc;
	}

	public void setRoleDesc(String roleDesc) {
		this.roleDesc = roleDesc;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	@Override
	public String toString() {
		return "RoleUser [roleId=" + roleId + ", roleName=" + roleName + ", roleDesc=" + roleDesc + ", users=" + users
				+ "]";
	}
}

<?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.dao.IRoleDao">

	<resultMap id="roleMap" type="com.domain.RoleUser">
		<id property="roleId" column="rid"></id>
		<result property="roleName" column="role_name"></result>
		<result property="roleDesc" column="role_desc"></result>
		<collection property="users" ofType="com.domain.User">
			<id column="id" property="id"></id>
			<result column="username" property="username"></result>
			<result column="address" property="address"></result>
			<result column="sex" property="sex"></result>
			<result column="birthday" property="birthday"></result>
		</collection>
	</resultMap>

	<!--查询所有 -->
	<select id="findAll" resultMap="roleMap">
		select u.*,r.id as rid,r.role_name,r.role_desc from role r
	left outer join user_role ur on r.id = ur.rid
		left outer join user u on u.id = ur.uid
	</select>

</mapper>
package com.dao;

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.After;
import org.junit.Before;
import org.junit.Test;

import com.domain.Role;
import com.domain.RoleUser;

import java.io.InputStream;
import java.util.List;

public class MyRole {

	private InputStream in;
	private SqlSession sqlSession;
	private IRoleDao roleDao;

	@Before // 用于在测试方法执行之前执行
	public void init() throws Exception {
		// 1.读取配置文件,生成字节输入流
		in = Resources.getResourceAsStream("SqlMapConfig.xml");
		// 2.获取SqlSessionFactory
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		// 3.获取SqlSession对象
		sqlSession = factory.openSession(true);
		// 4.获取dao的代理对象
		roleDao = sqlSession.getMapper(IRoleDao.class);
	}

	@After // 用于在测试方法执行之后执行
	public void destroy() throws Exception {
		// 提交事务
		// sqlSession.commit();
		// 6.释放资源
		sqlSession.close();
		in.close();
	}

	/**
	 * 测试查询所有
	 */
	@Test
	public void testFindAll() {
		List<RoleUser> roles = roleDao.findAll();
		for (RoleUser role : roles) {
			System.out.println("---每个角色的信息----");
			System.out.println(role);

		}
	}
}

2020-11-04 23:37:06,551 0      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter.
2020-11-04 23:37:06,730 179    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 23:37:06,731 180    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 23:37:06,732 181    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 23:37:06,732 181    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 23:37:06,743 192    [           main] DEBUG       org.apache.ibatis.io.VFS  - Class not found: org.jboss.vfs.VFS
2020-11-04 23:37:06,743 192    [           main] DEBUG org.apache.ibatis.io.JBoss6VFS  - JBoss 6 VFS API is not available in this environment.
2020-11-04 23:37:06,746 195    [           main] DEBUG       org.apache.ibatis.io.VFS  - Class not found: org.jboss.vfs.VirtualFile
2020-11-04 23:37:06,747 196    [           main] DEBUG       org.apache.ibatis.io.VFS  - VFS implementation org.apache.ibatis.io.JBoss6VFS is not valid in this environment.
2020-11-04 23:37:06,748 197    [           main] DEBUG       org.apache.ibatis.io.VFS  - Using VFS adapter org.apache.ibatis.io.DefaultVFS
2020-11-04 23:37:06,749 198    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Find JAR URL: file:/F:/xxxx/MyWorks/eclipse_work/hellomybatis66/target/test-classes/com/dao
2020-11-04 23:37:06,750 199    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Not a JAR: file:/F:/xxxx/MyWorks/eclipse_work/hellomybatis66/target/test-classes/com/dao
2020-11-04 23:37:06,833 282    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Reader entry: MyRole.class
2020-11-04 23:37:06,834 283    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Listing file:/F:/xxxx/MyWorks/eclipse_work/hellomybatis66/target/test-classes/com/dao
2020-11-04 23:37:06,834 283    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Find JAR URL: file:/F:/xxxx/MyWorks/eclipse_work/hellomybatis66/target/test-classes/com/dao/MyRole.class
2020-11-04 23:37:06,834 283    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Not a JAR: file:/F:/xxxx/MyWorks/eclipse_work/hellomybatis66/target/test-classes/com/dao/MyRole.class
2020-11-04 23:37:06,835 284    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Reader entry: ????
SELECT
	u.*, r.id AS rid,
	r.role_name,
	r.role_desc
FROM
	role r
LEFT OUTER JOIN user_role ur ON r.id = ur.rid
LEFT OUTER JOIN USER u ON u.id = ur.uid
id	username	birthday	sex	address	rid	role_name	role_desc
41	老王	2018-02-27 17:47:08	男	北京	1	院长	管理整个学院
41	老王	2018-02-27 17:47:08	男	北京	2	总裁	管理整个公司
					3	校长	管理整个学校
源码:hellomybatis66

9 mybatis多对多操作-查询用户获取用户所包含的角色信息

select u.*,r.id as rid,r.role_name,r.role_desc from user u
         left outer join user_role ur  on u.id = ur.uid
         left outer join role r on r.id = ur.rid
id	username	birthday	sex	address	rid	role_name	role_desc
41	老王	2018-02-27 17:47:08	男	北京	1	院长	管理整个学院
41	老王	2018-02-27 17:47:08	男	北京	2	总裁	管理整个公司
42	小二王	2018-03-02 15:09:37	女	北京金燕龙			
43	小二王	2018-03-04 11:34:34	女	北京金燕龙			
45	星空集团	2018-03-04 12:04:06	男	北京金燕龙	1	院长	管理整个学院
46	老王	2018-03-07 17:37:26	女	北京			
54	喵喵喵	2020-11-04 19:03:59	男	北京市顺义区			
2020-11-04 23:44:58,435 0      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter.
2020-11-04 23:44:58,602 167    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 23:44:58,602 167    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 23:44:58,602 167    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 23:44:58,602 167    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-11-04 23:44:58,609 174    [           main] DEBUG       org.apache.ibatis.io.VFS  - Class not found: org.jboss.vfs.VFS
2020-11-04 23:44:58,610 175    [           main] DEBUG org.apache.ibatis.io.JBoss6VFS  - JBoss 6 VFS API is not available in this environment.
2020-11-04 23:44:58,610 175    [           main] DEBUG       org.apache.ibatis.io.VFS  - Class not found: org.jboss.vfs.VirtualFile
2020-11-04 23:44:58,611 176    [           main] DEBUG       org.apache.ibatis.io.VFS  - VFS implementation org.apache.ibatis.io.JBoss6VFS is not valid in this environment.
2020-11-04 23:44:58,612 177    [           main] DEBUG       org.apache.ibatis.io.VFS  - Using VFS adapter org.apache.ibatis.io.DefaultVFS
2020-11-04 23:44:58,613 178    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Find JAR URL: file:/F:/xxxx/MyWorks/eclipse_work/hellomybatis66/target/test-classes/com/dao
2020-11-04 23:44:58,613 178    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Not a JAR: file:/F:/xxxx/MyWorks/eclipse_work/hellomybatis66/target/test-classes/com/dao
2020-11-04 23:44:58,685 250    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Reader entry: MyRole.class
2020-11-04 23:44:58,685 250    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Reader entry: MyUser.class
2020-11-04 23:44:58,686 251    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Listing file:/F:/xxxx/MyWorks/eclipse_work/hellomybatis66/target/test-classes/com/dao
2020-11-04 23:44:58,686 251    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Find JAR URL: file:/F:/xxxx/MyWorks/eclipse_work/hellomybatis66/target/test-classes/com/dao/MyRole.class
2020-11-04 23:44:58,687 252    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Not a JAR: file:/F:/xxxx/MyWorks/eclipse_work/hellomybatis66/target/test-classes/com/dao/MyRole.class
2020-11-04 23:44:58,688 253    [           main] DEBUG rg.apache.ibatis.io.DefaultVFS  - Reader entry: ????
查询用户获取用户所包含的角色信息 .png

![](.assets/查询用户获取用户所包含的角色信息 .png)

源码:hellomybatis66

============================================

10.JNDI扩展知识

============================================

11.Mybatis的缓存


1 今日课程安排


2 延迟加载和立即加载的概念


3 mybatis一对一实现延迟加载


4 mybatis一对多实现延迟加载


5 缓存的概念


6 Mybatis中的一级缓存


7 触发清空一级缓存的情况


8 mybatis的二级缓存

============================================

12.Mybatis注解开发


1 mybatis注解开发的环境搭建


2 mybatis注解开发测试和使用注意事项


3 mybatis注解开发保存和更新功能


4 mybatis注解开发CRUD的其他操作


5 mybatis注解建立实体类属性和数据库表中列的对应关系


6 mybatis注解开发一对一的查询配置


7 Mybatis注解开发一对多的查询配置


8 mybatis注解开发使用二级缓存

mybatis复习

标签:rtu   com   unp   mybatis框架   except   EDA   结构   pool   分析   

原文地址:https://www.cnblogs.com/RoyalGuardsTomCat/p/13929511.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!