工程目录结构查看:

执行流程:

1.数据库文件mybatisdb.sql

避免报错1406 - Data too long for column

根据不同的客户端工具使用不同的字符集编码

(1)cmd执行(本身GBK):mysql -uroot -prootswliuSET NAMES GBK;(2)mysql客户端工具Navicat等(本身UTF8):SET NAMES UTF8;-- 可以省略CREATE DATABASE IF NOT EXISTS `mybatisdb` DEFAULT CHARACTER SET utf8;USE `mybatisdb`;DROP TABLE IF EXISTS `user`;CREATE TABLE `user` (`ID` int(11) NOT NULL AUTO_INCREMENT,`NAME` varchar(30) DEFAULT NULL,`BIRTHDAY` datetime DEFAULT NULL,`ADDRESS` varchar(200) DEFAULT NULL,PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;insert  into `user`(`ID`,`NAME`,`BIRTHDAY`,`ADDRESS`) values (1,'夏言','1573-01-01 00:00:00','桂州村'),(2,'严嵩','1587-01-01 00:00:00','分宜县城介桥村');select * from `user`;

2. 测试类TestMybatis.java

package mybatis;import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;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.Before;
import org.junit.Test;import com.swliu.mybatis.pojo.User;public class TestMybatis {private SqlSessionFactory factory;//SqlSessionFactory线程安全类,可以作为成员变量(高并发场景)@Beforepublic void init() throws IOException{//1.创建SqlSessionFactory,加载核心配置文件String resource = "sqlMapConfig.xml";InputStream is = Resources.getResourceAsStream(resource);factory = new SqlSessionFactoryBuilder().build(is);}@Testpublic void findAll() throws IOException{//2.利用工厂创建SqlSession对象,读取某个映射文件来执行SqlSession session = factory.openSession();SqlSession非线程安全类,不能作为成员变量(高并发场景)//查询所有。namespace.id,桶namespace定位唯一映射。映射文件有多个访问,通过id找到唯一标签String statement = "com.swliu.mybatis.pojo.UserMapper.findAll";  //指向映射文件,映射文件中需要pojo//ORM 对象和数据库表映射工具,持久化工具MybatisList<User> userList = session.selectList(statement);//打印数据for(User u: userList){System.out.println(u);}}@Testpublic void findOne() throws IOException{SqlSession session = factory.openSession();String statement = "com.swliu.mybatis.pojo.UserMapper.findOne";   User u = session.selectOne(statement,2 );System.out.println(u);}@Testpublic void findCount() throws IOException{SqlSession session = factory.openSession();String statement = "com.swliu.mybatis.pojo.UserMapper.findCount";  int count = session.selectOne(statement);System.out.println(count);}@Testpublic void insert() throws IOException{SqlSession session = factory.openSession();String statement = "com.swliu.mybatis.pojo.UserMapper.insert";    User u = new User();u.setName("刘德华");u.setBirthday(new Date());u.setAddress("中国香港");session.insert(statement,u);//如何证明mybatis默认事务是手动提交?//如果mybatis默认事务是自动提交,则下面i=1/0执行之前,就已经将数据插入到数据库;//如果数据库中没有该条数据提交的内容,则说明事务已经回滚,则证明mybatis为事务手动提交//int i=1/0;//mybatis默认事务手动提交session.commit();}@Testpublic void update() throws IOException{SqlSession session = factory.openSession();String statement = "com.swliu.mybatis.pojo.UserMapper.update";  String name="Jack";session.update(statement,name);//如何证明mybatis默认事务是手动提交?//如果mybatis默认事务是自动提交,则下面i=1/0执行之前,就已经将数据插入到数据库;//如果数据库中没有该条数据提交的内容,则说明事务已经回滚,则证明mybatis为事务手动提交//int i=1/0;//mybatis默认事务手动提交session.commit();}@Testpublic void delete() throws IOException{SqlSession session = factory.openSession();String statement = "com.swliu.mybatis.pojo.UserMapper.delete";  int pid=12;session.delete(statement,pid);//如何证明mybatis默认事务是手动提交?//如果mybatis默认事务是自动提交,则下面i=1/0执行之前,就已经将数据插入到数据库;//如果数据库中没有该条数据提交的内容,则说明事务已经回滚,则证明mybatis为事务手动提交//int i=1/0;//mybatis默认事务手动提交session.commit();}@Testpublic void findYear() throws IOException{SqlSession session = factory.openSession();String statement = "com.swliu.mybatis.pojo.UserMapper.findYear"; List<User> userList = session.selectList(statement);for(User u: userList){System.out.println(u);}}@Testpublic void order() throws IOException{SqlSession session = factory.openSession();String statement = "com.swliu.mybatis.pojo.UserMapper.order";  //不能使用string传值,不符合业务需要//List<User> userList = session.selectList(statement,"name");//可以使用对象传值的方式Map<String, Object> map = new HashMap<String, Object>();map.put("findObj", "name");List<User> userList = session.selectList(statement,map);for(User u: userList){System.out.println(u);}}}

selectList返回的数据:可以是多条/一条/没有

selectOne返回的数据:只能有一个值

SqlSessionFactory线程安全类,可以作为成员变量(高并发场景)

SqlSession非线程安全类,不能作为成员变量(高并发场景)

mybatis默认事务开启,需要手动提交

begin;
start transaction;

commit;

3.配置事务、数据源、映射文件、全局配置文件 sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!-- 简化类,起别名 --><typeAliases><typeAlias type="com.swliu.mybatis.pojo.User" alias="User"/></typeAliases><!-- 配置事务、数据源、映射文件、全局配置 --><environments default="deploy"><environment id="deploy"><!-- 事务:类似java锁,防止并发;JDBC/MANAGE --><transactionManager type="JDBC"/><!-- 数据源:POOLED池化/UNPOOLED非池化/JNDI命名和目录的管理方式:类似于DNS域名解析,需要一个单独的服务器来解析--><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatisdb?charactorEncoding=utf8"/><property name="username" value="root"/><property name="password" value="rootswliu"/></dataSource></environment><!-- <environment id="test"></environment> --></environments><!-- 映射 --><mappers><mapper resource="com/swliu/mybatis/pojo/UserMapper.xml"/></mappers></configuration>   

4.配置映射文件的命名空间(java包): 包的路径.映射文件的名称 UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- 配置映射文件的命名空间(java包): 包的路径.映射文件的名称 -->
<mapper namespace="com.swliu.mybatis.pojo.UserMapper"><!-- 列出所有的字段,可以共享--><sql id="cols">id,name,birthday,address</sql><!-- 需求:查询user表的所有数据 --><select id="findAll" resultType="User">select <include refid="cols"/> from user</select><!-- 需求:获取某个用户信息 --><select id="findOne" parameterType="int" resultType="User">select <include refid="cols"/> from user where id=#{pid}</select><!-- 需求:查询记录总数 SQL优化:count(id)比count(*) 执行效率高 --><select id="findCount" resultType="int">select count(id) from user</select><!-- 需求:插入一条数据--><!-- mybatis非常智能,直接可以获取对象中的参数--><select id="insert" parameterType="User">insert into user(name,birthday,address) values(#{name},#{birthday},#{address})</select><!-- 需求:修改一条数据--><select id="update" parameterType="string">update user set name=#{name} where name='刘德华'</select><!-- 需求:删除一条数据--><select id="delete" parameterType="int">delete from user where id=#{pid}</select><!-- 如果有特殊符号,在xml中不用去解析,可以用下面的方式括起来即可(CDATA规范:原样输出)select * from user where year(birthday) <![CDATA[>]]>1580 and year(birthday) <![CDATA[<]]>1590 --><!-- 需求:按年龄段查询--><select id="findYear" resultType="User">select <include refid="cols"/> from user where year(birthday) >1580 and year(birthday) <1590 </select><!-- order测试:Mybatis不能直接支持特殊的string,需要使用对象get方法获取(解决方法:改成user对象或者map结构)#{}表示占位符形式,防止SQL注入;  select * from user order by 'name'; (不符合业务需要,'name'没有按占位符使用)${}表示直接字符串拼接,存在隐患,不能防止SQL注入,慎用.order by/group byselect * from user order by name;  (业务需要,使用对象传值)--><select id="order" parameterType="map" resultType="User">select <include refid="cols"/> from user order by ${findObj}</select></mapper>

参数parameterType/parameterMap(后者废除,可以用parameterType="map"替代)

select * from user where year(birthday) >1580 and year(birthday) <1590 ;
select * from user where extract(year from birthday)>1580 and extract(year from birthday) <1590 ;
select * from user where birthday between '1580-1-1' and '1590-12-31';

如果有特殊符号>或者<:

方式一:在xml中不用去解析,可以用下面的方式括起来即可(CDATA规范:原样输出)
select <include refid="cols"/> from user where year(birthday) <![CDATA[>]]>1580 and year(birthday) <![CDATA[<]]>1590

或:

select <include refid="cols"/> from user where 
<![CDATA[
year(birthday)>1580 and year(birthday)<1590 
]]>

方式二:

select <include refid="cols"/> from user where year(birthday) &gt;1580 and year(birthday) &lt;1590

方式三:

select <include refid="cols"/> from user where year(birthday) >1580 and year(birthday) <1590

Mybatis不能直接支持特殊的string,需要使用对象get方法获取

(如order by/group by某个字段场景)

(解决方法:改成user对象或者map结构)
    #{}表示占位符形式,防止SQL注入;  
        select * from user order by 'name'; (不符合业务需要,'name'没有按占位符使用)
    ${}表示直接字符串拼接,存在隐患,不能防止SQL注入,慎用.order by/group by
        select * from user order by name;  (业务需要,使用对象传值)

5.javaBean类User.java

package com.swliu.mybatis.pojo;import java.util.Date;public class User {@Overridepublic String toString() {return "User [id=" + id + ", name=" + name + ", birthday=" + birthday + ", address=" + address + "]";}private Integer id;private String name;private Date birthday;private String address;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}}

6.log4j.properties日志打印

log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

7.pom.xml

<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.swliu</groupId><artifactId>mybatis</artifactId><version>0.0.1-SNAPSHOT</version><properties>  <argLine>-Dfile.encoding=UTF-8</argLine>  </properties><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.40</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.2.8</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies><!-- <build><plugins>  <plugin>  <groupId>org.apache.maven.plugins</groupId>  <artifactId>maven-surefire-plugin</artifactId>  <version>2.16</version>  <configuration>  <forkMode>once</forkMode>  <argLine>-Dfile.encoding=UTF-8</argLine>  </configuration>  </plugin>  </plugins></build>  --></project>

打印信息: 略

xxxxxx [main] DEBUG [com.swliu.mybatis.pojo.UserMapper.findAll] - ==>  Preparing: select id,name,birthday,address from user
xxxxxx [main] DEBUG [com.swliu.mybatis.pojo.UserMapper.findAll] - ==> Parameters: xxxxxx [main] DEBUG [com.swliu.mybatis.pojo.UserMapper.findCount] - ==>  Preparing: select count(id) from user
xxxxxx [main] DEBUG [com.swliu.mybatis.pojo.UserMapper.findCount] - ==> Parameters: xxxxxx [main] DEBUG [com.swliu.mybatis.pojo.UserMapper.findYear] - ==>  Preparing: select id,name,birthday,address from user where year(birthday) >1580 and year(birthday) <1590
xxxxxx [main] DEBUG [com.swliu.mybatis.pojo.UserMapper.findYear] - ==> Parameters: xxxxxx [main] DEBUG [com.swliu.mybatis.pojo.UserMapper.findOne] - ==>  Preparing: select id,name,birthday,address from user where id=?
xxxxxx [main] DEBUG [com.swliu.mybatis.pojo.UserMapper.findOne] - ==> Parameters: 2(Integer)xxxxxx [main] DEBUG [com.swliu.mybatis.pojo.UserMapper.order] - ==>  Preparing: select id,name,birthday,address from user order by name  (name非占位符)
xxxxxx [main] DEBUG [com.swliu.mybatis.pojo.UserMapper.order] - ==> Parameters:

mybatis基础动态SQLlog4j简单使用相关推荐

  1. Mybatis基础学习之一级缓存和二级缓存的简单使用

    前言: 小伙伴们,大家好,我是狂奔の蜗牛rz,当然你们可以叫我蜗牛君,我是一个学习Java半年多时间的小菜鸟,同时还有一个伟大的梦想,那就是有朝一日,成为一个优秀的Java架构师. 这个Mybatis ...

  2. 9、mybatis中动态sql的使用

    对于初学者,如何进行mybatis的学习呢?我总结了几点,会慢慢的更新出来.首先大家需要了解mybatis是什么.用mybatis来做什么.为什么要用mybatis.有什么优缺点:当知道了为什么的时候 ...

  3. javaweb实训第六天下午——Mybatis基础

    Mybatis基础 1.课程介绍 2.为什么需要Mybatis 3.初识Mybatis 3.1.Mybatis是什么 3.1.1.什么是框架 3.1.2.什么叫数据库持久化 3.1.3.什么是ORM ...

  4. MyBatis基础篇

    MyBatis基础篇 简介 注意:本篇文章主讲语法,jar包导入大家可以在网上搜索(有问题一定要学会利用搜索引擎解决!!!),全程代码会写到文章中. 1. MyBatis是一个半自动ORM框架(作为解 ...

  5. java mybatis基础

    java mybatis基础 1.1 什么是mybatis? mybatis是一个优秀的持久层框架. 避免几乎所有的JDBC代码和手动设置参数以及获取结果集的过程. 可以使用简单的xml或者注解来配置 ...

  6. MyBatis的动态SQL详解

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑. MyBatis中用于实现动态SQL的元素主要有:   if choose(when,otherwis ...

  7. Mybatis解析动态sql原理分析

    前言 废话不多说,直接进入文章. 我们在使用mybatis的时候,会在xml中编写sql语句. 比如这段动态sql代码: <update id="update" parame ...

  8. 利用MyBatis的动态SQL特性抽象统一SQL查询接口

    1. SQL查询的统一抽象 MyBatis制动动态SQL的构造,利用动态SQL和自定义的参数Bean抽象,可以将绝大部分SQL查询抽象为一个统一接口,查询参数使用一个自定义bean继承Map,使用映射 ...

  9. 2022/5/1 Mybatis框架动态SQL

    目录 1丶动态 SQL 2丶if标签 3丶choose.when.otherwise 4丶trim.where.set 5丶foreach 6丶script 7丶bind 8丶多数据库支持 9丶动态 ...

最新文章

  1. ARP监控工具ARPalert常用命令集合大学霸IT达人
  2. 如果把线程当作一个人来对待,所有问题都瞬间明白了
  3. 深入浅出mysql唐汉名_深入浅出MySQL++数据库开发、优化与管理维护+第2版+唐汉明 -- 存储引擎 - 数据类型 - 字符集和校验规则 -...
  4. 转载-项目经理与部门经理之间的关系
  5. 2.关于QT中的Dialog(模态窗口),文件选择器,颜色选择器,字体选择器,消息提示窗口
  6. 客户端控件调用服务器的参数
  7. POJ 1325 Machine Schedule(二分图最小点集覆盖)
  8. java如何解决高并发症,JAVA线上故障紧急处理详细过程!
  9. Asp.net三层结构原理与用意学习入门教程(一)
  10. 作为面向事务的客户服务器协议,湖南大学《计算机网络》实验报告.doc
  11. sort ascend matlab,MATLAB sort函数用法
  12. 代码统计工具有哪几种_DevOps:优秀代码分析工具的自我修养
  13. 什么是lambda(函数)?
  14. ftp-cmd常用命令
  15. 对话阿里云弹性计算负责人褚霸:把计算做到极致,关键还不加价!
  16. Excel批量复制公式、删除空白行
  17. iOS 通过商品短链接跳转京东商品详情页
  18. 一个较为感人的升学故事
  19. js中判断数据类型的方法
  20. LeaRun快速开发平台,快速开发.net/java项目

热门文章

  1. 珠宝店忽略的客户管理,恰恰是最重要的东西
  2. 穿越东西冲,享受最美海岸线
  3. (终稿)C++实现科学计算器主函数代码(含调用函数)
  4. 最新AI创作系统V5.0.2+支持GPT4+支持ai绘画+实时语音识别输入+文章资讯发布功能+用户会员套餐
  5. react支持android5吗,react原生应用程序在真正的android设备上崩溃
  6. 10个经典智力推理题!据说答对7道,智力在140!
  7. git如何撤销未提交的更改
  8. Intel与AMD CPU型号对照
  9. 洛谷Latex数学公式大全
  10. 2020届软开国企银行外企类的求职分享