【Mybatis】学习
Mybatis 学习
环境搭建
pom.xml
     <!--log4j-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.6.6</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.6.6</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.16</version>
    </dependency>
    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>
mybatis.properties
# jdbc
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
#dbcp
initialSize=0
maxActive=10
maxIdle=10
minIdle=1
maxWait=60000 
mybatis-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>
    <!-- 不建议使用这种方式定义别名,但要知道
    <typeAlias type="com.zhengqing.mybatis.bean.User" ></typeAlias>  -->
    <!-- 自定义别名:  typeAliases:类型的别名 -->
<!--    <typeAliases>-->
<!--        <!– typeAlias:这个type和alias的关系 -》 一一关系-->
<!--         注意:如果不写alias,默认是类型的简单类名:首字母大小写无关,但是建议使用的时候使用大写! –>-->
<!--        <!– 表示这个包路径下的所有的类都有别名,默认简单类名 –>-->
<!--        <package name="com.kdgc.wangxianlin.entity"></package>-->
<!--    </typeAliases>-->
    <!-- 引用mybatis.properties配置文件 -->
    <properties resource="mybatis.properties" />
    <!--日志输出的方式-->
    <settings>
        <setting name="logImpl" value="LOG4J" />
        <setting name="cacheEnabled" value="true"/>
    </settings>
    <!-- environments:多个环境   development:开发 -->
    <environments default="development">
        <!--可以设置多个数据库的链接   id是唯一的标识,通过id来进行区分-->
        <environment id="development">
            <!--transactionManager事务控制-->
            <transactionManager type="JDBC" />
            <!-- 配置数据库连接信息 -->
            <dataSource type="POOLED">
                <!-- value属性值引用db.properties配置文件中配置的值 -->
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    <!-- 映射文件 在这代表的是映射文件的地址-->
    <mappers>
        <mapper resource="mapper/UserDao.xml" />
    </mappers>
</configuration>
log4j.properties
log4j.rootLogger=DEBUG,stdout
### console ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
### mybatis ###
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=ERROR
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
测试准备
 SqlSession openSession = null;
    /**
     * 创建会话工厂
     * @return
     * @throws IOException
     */
    @Before
    public void getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        openSession = sqlSessionFactory.openSession();
    }
    @After
    public void closeOpsession() throws IOException {
        if(openSession!=null){
            openSession.close();
        }
    }
新增
 <!--新增所有列-->
    <insert id="insert" keyProperty="id" useGeneratedKeys="true">
        insert into test.user(user_name, age, nick_name, create_time)
        values (#{userName}, #{age}, #{nickName}, #{createTime})
    </insert>
UserDao.java
    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 影响行数
     */
    int insert(User user);
UserDaoTest.java
  /**
     * 新增
     * @throws IOException
     */
    @Test
    public void insert() throws IOException {
        UserDao userDao = openSession.getMapper(UserDao.class);
        User user = new User();
        user.setUserName("Tony");
        user.setNickName("托尼");
        user.setAge(24);
        int res = userDao.insert(user);
        System.out.println(res);
        openSession.commit();
    }
日志
Connected to the target VM, address: '127.0.0.1:55181', transport: 'socket'
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Opening JDBC Connection
DEBUG - Created connection 685558284.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@28dcca0c]
DEBUG - ==>  Preparing: insert into test.user(user_name, age, nick_name, create_time) values (?, ?, ?, ?)
DEBUG - ==> Parameters: halo(String), 22(Integer), Halos(String), null
DEBUG - <==    Updates: 1
1
DEBUG - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@28dcca0c]
Disconnected from the target VM, address: '127.0.0.1:55181', transport: 'socket'
修改
UserDao.xml
 <!--通过主键修改数据-->
    <update id="update">
        update test.user
        <set>
            <if test="userName != null and userName != ''">
                user_name = #{userName},
            </if>
            <if test="age != null">
                age = #{age},
            </if>
            <if test="nickName != null and nickName != ''">
                nick_name = #{nickName},
            </if>
            <if test="createTime != null">
                create_time = #{createTime},
            </if>
        </set>
        where id = #{id}
    </update>
UserDao.java
/**
     * 修改数据
     *
     * @param user 实例对象
     * @return 影响行数
     */
    int update(User user);
UserDaoTest.java
     /**
     * 修改
     * @throws IOException
     */
    @Test
    public void updateById() throws IOException {
        UserDao userDao = openSession.getMapper(UserDao.class);
        User user = new User();
        user.setId(3);
        user.setUserName("Tony");
        user.setNickName("托尼");
        user.setAge(24);
        int res = userDao.update(user);
        System.out.println(res);
        openSession.commit();
    }
日志
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Opening JDBC Connection
DEBUG - Created connection 1686369710.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@6483f5ae]
DEBUG - ==>  Preparing: update test.user SET user_name = ?, age = ?, nick_name = ? where id = ?
DEBUG - ==> Parameters: helo(String), 24(Integer), Helos(String), 3(Integer)
DEBUG - <==    Updates: 1
1
删除
UserDao.xml
  <!--通过主键删除-->
    <delete id="deleteById">
        delete from test.user where id = #{id}
    </delete>
UserDao.java
    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 影响行数
     */
    int deleteById(Integer id);
UserDaoTest.java
   /**
     * 删除
     * @throws IOException
     */
    @Test
    public void deleteById() throws IOException {
        UserDao userDao = openSession.getMapper(UserDao.class);
        int res = userDao.deleteById(3);
        System.out.println(res);
        openSession.commit();
    }
日志
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Opening JDBC Connection
DEBUG - Created connection 1739876329.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@67b467e9]
DEBUG - ==>  Preparing: delete from test.user where id = ?
DEBUG - ==> Parameters: 3(Integer)
DEBUG - <==    Updates: 1
1
查询
UserDao.xml
  <!--通过实体作为筛选条件查询-->
    <select id="queryAll" resultMap="UserMap">
        select
        id, user_name, age, nick_name, create_time
        from test.user
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="userName != null and userName != ''">
                and user_name = #{userName}
            </if>
            <if test="age != null">
                and age = #{age}
            </if>
            <if test="nickName != null and nickName != ''">
                and nick_name = #{nickName}
            </if>
            <if test="createTime != null">
                and create_time = #{createTime}
            </if>
        </where>
    </select>
UserDao.java
   /**
     * 通过实体作为筛选条件查询
     *
     * @param user 实例对象
     * @return 对象列表
     */
    List<User> queryAll(User user);
UserDaoTest.java
 /**
     * 按条件查询所有
     * @throws IOException
     */
    @Test
    public void queryAll() throws IOException {
        UserDao userDao = openSession.getMapper(UserDao.class);
        User user = new User();
        user.setAge(24);
        List<User> list= userDao.queryAll(user);
        System.out.println(list.toString());
    }
日志
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Cache Hit Ratio [com.kdgc.wangxianlin.dao.UserDao]: 0.0
DEBUG - Opening JDBC Connection
DEBUG - Created connection 1475491159.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@57f23557]
DEBUG - ==>  Preparing: select id, user_name, age, nick_name, create_time from test.user WHERE age = ?
DEBUG - ==> Parameters: 24(Integer)
DEBUG - <==      Total: 1
[User{id=4, userName='Tony', age=24, nickName='托尼', createTime=null}]
批量新增/删除
批量新增
UserDao.xml
    <insert id="insertBatch" keyProperty="id" useGeneratedKeys="true">
        insert into test.user(user_name, age, nick_name, create_time)
        values
        <foreach collection="entities" item="entity" separator=",">
            (#{entity.userName}, #{entity.age}, #{entity.nickName}, #{entity.createTime})
        </foreach>
    </insert>
UserDao.java
    /**
     * 批量新增数据(MyBatis原生foreach方法)
     *
     * @param entities List<User> 实例对象列表
     * @return 影响行数
     */
    int insertBatch(@Param("entities") List<User> entities);
UserDaoTest.java
 /**
     * 批量插入
     * @throws IOException
     */
    @Test
    public void insertBatch() throws IOException {
        UserDao userDao = openSession.getMapper(UserDao.class);
        List<User> list= new ArrayList<>();
        User user = new User();
        user.setUserName("Tony");
        user.setNickName("托尼");
        user.setAge(24);
        list.add(user);
        User user2 = new User();
        user2.setUserName("Hony");
        user2.setNickName("哈尼");
        user2.setAge(22);
        list.add(user2);
        int res= userDao.insertBatch(list);
        System.out.println(res);
        openSession.commit();
    }
日志
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Opening JDBC Connection
DEBUG - Created connection 323326911.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@134593bf]
DEBUG - ==>  Preparing: insert into test.user(user_name, age, nick_name, create_time) values (?, ?, ?, ?) , (?, ?, ?, ?)
DEBUG - ==> Parameters: Tony(String), 24(Integer), 托尼(String), null, Hony(String), 22(Integer), 哈尼(String), null
DEBUG - <==    Updates: 2
2
DEBUG - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@134593bf]
批量删除
UserDao.xml
   <!-- void deleteBatch(List<Long> ids);-->
    <delete id="deleteBatch" parameterType="list">
        <!-- DELETE from user where id in(2,3,4,5) -->
        <!-- collection="list":遍历的集合  index:索引  item:每次遍历得到的对象 open:以什么开始 close:以什么关闭 separator:分隔符 -->
        DELETE from user where id in
        <foreach collection="list"  item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </delete>
UserDao.java
   /**
     * 批量删除数据
     *
     * @param id 主键
     * @return 影响行数
     */
    int deleteBatch(List<Integer> id);
UserDaoTest.java
   /**
     * 批量删除
     * @throws IOException
     */
    @Test
    public void deleteBatch() throws IOException {
        UserDao userDao = openSession.getMapper(UserDao.class);
        List<Integer> list= new ArrayList<>();
        list.add(3);
        list.add(4);
        int res= userDao.deleteBatch(list);
        System.out.println(res);
        openSession.commit();
    }
日志
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Opening JDBC Connection
DEBUG - Created connection 323326911.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@134593bf]
DEBUG - ==>  Preparing: DELETE from user where id in ( ? , ? )
DEBUG - ==> Parameters: 3(Integer), 4(Integer)
DEBUG - <==    Updates: 2
2
DEBUG - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@134593bf]
【Mybatis】学习的更多相关文章
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作(转载)
		本文转载自:http://www.cnblogs.com/jpf-java/p/6013540.html 上一篇博文MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybati ... 
- MyBatis学习总结(八)——Mybatis3.x与Spring4.x整合(转载)
		孤傲苍狼 只为成功找方法,不为失败找借口! MyBatis学习总结(八)--Mybatis3.x与Spring4.x整合 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: m ... 
- MyBatis学习总结(七)——Mybatis缓存(转载)
		孤傲苍狼 只为成功找方法,不为失败找借口! MyBatis学习总结(七)--Mybatis缓存 一.MyBatis缓存介绍 正如大多数持久层框架一样,MyBatis 同样提供了一级缓存和二级缓存的 ... 
- (原创)mybatis学习二,spring和mybatis的融合
		mybatis学习一夯实基础 上文介绍了mybatis的相关知识,这一节主要来介绍mybaits和spring的融合 一,环境搭建 1,jar包下载,下载路径为jar包 2,将包导入到java工程中 ... 
- (原创)mybatis学习一,夯实基础
		一,what?(是什么) MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可 ... 
- MyBatis学习--简单的增删改查
		jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: Public static void main(String[] args) ... 
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作
		上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对u ... 
- 【Todo】Mybatis学习-偏理论
		之前写过好几篇Mybatis相关的文章: http://www.cnblogs.com/charlesblc/p/5906431.html <SSM(SpringMVC+Spring+Myba ... 
- MyBatis学习系列三——结合Spring
		目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring MyBatis在项目中应用一般都要结合Spring,这一章主要把MyBat ... 
- MyBatis学习系列二——增删改查
		目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring 数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改, ... 
随机推荐
- Redis 数据类型 Set
			Redis 数据类型 Set(集合) Redis 常用命令,思维导图 >>> Redis 的 Set 是 String 类型的无序集合.集合成员是唯一的,这就意味着集合中不能出现重复 ... 
- 2.JAVA入门基础知识
			数据类型: java的数据类型分为两大类:基本类型和引用类型 基本类型: 整数类型: byte 一个字节 -128-127 short 2个字节 32768-32767 int 4个字节 很大 lon ... 
- Hystrix 如何在不引入 Archaius 的前提下实现动态配置更新
			Hystrix 简介 Hystrix 是 Netflix 开源的一个限流熔断降级组件,防止依赖服务发生错误后,将调用方的服务拖垮.这里对 Hystrix 本身不做过多介绍. Hystrix 目前处于维 ... 
- 一文详解RocketMQ-Spring的源码解析与实战
			摘要:这篇文章主要介绍 Spring Boot 项目使用 rocketmq-spring SDK 实现消息收发的操作流程,同时笔者会从开发者的角度解读 SDK 的设计逻辑. 本文分享自华为云社区< ... 
- js与java对json的操作
			JSON呢,是现在大部分,并且主流的传递数据的方式. 今天讲一下javascript的java对json的操作 提到js,当下就有一个比较主流的插件,vue.js,这个插件程序员没用过也都听说过吧, ... 
- 获取电脑的网络连接状态(五)WebClient
			网络连接判断,使用WebClient测试获取: 1 public static bool IsWebClientConnected() 2 { 3 try 4 { 5 using (var clien ... 
- 2022-05-04:比如,str = “ayxbx“, 有以下4种切法 : a | yxbx、ay | xbx、ayx | bx、ayxb | x, 其中第1、3、4种切法符合:x和y的个数,至少在
			2022-05-04:比如,str = "ayxbx", 有以下4种切法 : a | yxbx.ay | xbx.ayx | bx.ayxb | x, 其中第1.3.4种切法符合: ... 
- 2022-01-16:小明手中有n块积木,并且小明知道每块积木的重量。现在小明希望将这些积木堆起来, 要求是任意一块积木如果想堆在另一块积木上面,那么要求: 1.上面的积木重量不能小于下面的积木重量;
			2022-01-16:小明手中有n块积木,并且小明知道每块积木的重量.现在小明希望将这些积木堆起来, 要求是任意一块积木如果想堆在另一块积木上面,那么要求: 1.上面的积木重量不能小于下面的积木重量: ... 
- 2021-07-07:股票问题4。给定一个整数数组 prices ,它的第 i 个元素 prices[i] 是一支给定的股票在第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你最多可以完成
			2021-07-07:股票问题4.给定一个整数数组 prices ,它的第 i 个元素 prices[i] 是一支给定的股票在第 i 天的价格.设计一个算法来计算你所能获取的最大利润.你最多可以完成 ... 
- ModuleNotFoundError: No module named 'flask_sqlalchemy'
			ModuleNotFoundError: No module named 'flask_sqlalchemy' 解决: pip install flask_sqlalchemy 
