CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user` (
`id` INT ( 20 ) NOT NULL PRIMARY KEY,
`NAME` VARCHAR ( 20 ) DEFAULT NULL,
`psd` VARCHAR ( 20 ) DEFAULT NULL
) ENGINE = INNODB DEFAULT CHARSET = utf8;
INSERT INTO `user` ( `id`, `name`, `psd` ) VALUES
( 1, '张作鹏', '123456' ),
( 2, '张三', '123456' ),
( 3, '李四', '123456' )
1.新建一个普通maven项目
2.删除src目录(建立父工程)
3.导入maven依赖
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.0modelVersion>
<groupId>com.zhanggroupId>
<artifactId>Mybatis-StudyartifactId>
<packaging>pompackaging>
<version>1.0-SNAPSHOTversion>
<modules>
<module>mybatis-01module>
modules>
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.49version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
project>
mybatis-config.xml
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="UserMapper.xml"/>
mappers>
configuration>
MybatisUtils.java
package com.zhang.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
//sqlSessionFactory --> sqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static{
try{
//使用Mybatis第一步:获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e){
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
//SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
//你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
User.java
package com.zhang.pojo;
//实体类
public class User {
private int id;
private String name;
private String psd;
public User(){
}
public User(int id, String name, String psd){
this.id = id;
this.name = name;
this.psd = psd;
}
public int getId(){ return id; }
public void setId(int id){ this.id = id; }
public String getName(){ return name; }
public void setName(String name){ this.name = name; }
public String getPsd(){ return psd; }
public void setPsd(String psd){ this.psd = psd; }
@Override
public String toString(){
return "User{" +
"id=" + id +
",name='" + name + '\'' +
",psd='" + psd + '\'' +
"}";
}
}
UserDao.java
package com.zhang.dao;
import com.zhang.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
(由原来的UserDaolmpl转变为一个Mapper配置文件)
UserMapper.xml
<mapper namespace="com.zhang.dao.UserDao">
<select id="getUserList" resultType="com.zhang.pojo.User">
select * from mybatis.user
select>
mapper>
注意点:org.apache.ibatis.binding.BindingException: Type interface com.zhang.dao.UserDao is not known to the MapperRegistry.
junit测试
UserDaoTest.java
package com.zhang.dao;
import com.zhang.pojo.User;
import com.zhang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
//方式一:getMapper
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
//方式二
//List userList = sqlSession.selectList("com.zhang.dao.UserDao.getUserList");
for (User user : userList){
System.out.println(user);
}
}catch (Exception e){
e.printStackTrace();
}finally {
//关闭SqlSession
sqlSession.close();
}
}
}
建立好的目录一览
PS:菜死了我,写了一天,发现是目录写错了,还有一个地方写错了一个字母,报错不停,教学视频看了三次,第一次预习,第二次跟着写代码,第三次查错误,终于晚上十一点搞出来了结果,路漫漫其修远兮。
CRUD是指:增加(Create)、检索(Retrieve)、更新(Update)和删除(Delete)
即:增删改查
namespace中的包名要和Dao/Mapper接口的包名一致。
id:就是对应的namespace中的方法名;
resultTpye:sql语句执行的返回值;
parameterType:参数类型。
//根据id查询用户
User getUserById(int id);
<select id="getUserById" parameterType="int" resultType="com.zhang.pojo.User">
select * from mybatis.user where id=#{id}
select>
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
<insert id="addUser" parameterType="com.zhang.pojo.User">
insert into mybatis.user (id, name, psd) value (#{id},#{name},#{psd});
insert>
<update id="updateUser" parameterType="com.zhang.pojo.User">
update mybatis.user set name=#{name}, psd=#{psd} where id=#{id};
update>
<delete id="deleteUser" parameterType="com.zhang.pojo.User">
delete from mybatis.user where id=#{id}
delete>
//模糊查询
List<User> getUserLike(String value);
<select id="getUserLike" resultType="com.zhang.pojo.User">
select * from mybatis.user where name like #{value}
select>
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserLike("%李%");
for (User user : userList){
System.out.println(user);
}
sqlSession.close();
}
List<User> userList = userMapper.getUserLike("%李%");
select * from mybatis.user where name like "%"#{value}"%"
mybatis-config.xml
MyBatis的配置文件包含了会深深影响MyBatis行为的设置和属性信息
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
MyBatis 可以配置成适应多种环境 尽
管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境
有两个值,JDBC和MANAGED
MyBatis使用JDBC
<transactionManager type="JDBC"/>
有三个值,UNPOOLED、POOLED和JNDI
MyBatis使用POOLED
<dataSource type="POOLED">
······
dataSource>
我们可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF8
username=root
password=123456
mybatis-config.xml
<properties resource="db.properties" />
<mappers>
<mapper resource="UserMapper.xml"/>
mappers>
理解我们之前讨论过的不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder
SqlSessionFactory
SqlSession
private int id;
private String name;
private String password;
select id,name,psd as password from mybatis.user where id=#{id}
<resultMap id="UserMap" type="com.zhang.pojo.User">
<result column="psd" property="password"/>
resultMap>
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id=#{id}
select>
如果一个数据库操作,出现了异常,我们需要排错,日志就是最好的助手!
曾经:sout、debug
现在:日志工厂
在MyBatis中具体使用哪一个日志实现,在设置中设定。
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
何为log4j?
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/zhang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
<settings>
<setting name="logImpl" value="LOG4J"/>
settings>
import org.apache.log4j.Logger;
static Logger logger = Logger.getLogger(UserDaoTest.class);
@Test
public void testLog4j(){
logger.info("info:进入了testLog4j");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");
}
@Select("select * from user")
List<User> getUsers();
<mappers>
<mapper class="com.zhang.dao.UserMapper"/>
mappers>
本质:反射机制实现
底层:动态代理
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
注意:必须将接口类注册到核心配置文件中
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO teacher(`id`, `name`) VALUES (1, '张老师');
CREATE TABLE `student` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
Teacher.java(部分代码)
package com.zhang.pojo;
public class Teacher {
private int id;
private String name;
}
Student.java(部分代码)
package com.zhang.pojo;
public class Student {
private int id;
private String name;
private Teacher teacher;
}
StudentMapper.java(略)
TeacherMapper.java(部分代码)
@Select("select * from teacher where id=#{tid}")
Teacher getTeacher(@Param("tid") int id);
<mappers>
<mapper resource="com/zhang/dao/StudentMapper.xml"/>
<mapper resource="com/zhang/dao/TeacherMapper.xml"/>
mappers>
此时,我们要根据学生查出老师,即:在输出学生信息时,输出老师的信息
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
select>
<resultMap id="StudentTeacher" type="com.zhang.pojo.Student">
<id property="id" column="id"/>
<id property="name" column="name"/>
<association property="teacher" column="tid" javaType="com.zhang.pojo.Teacher" select="getTeacher"/>
resultMap>
<select id="getTeacher" resultType="com.zhang.pojo.Teacher">
select * from teacher where id=#{id};
select>
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid=t.id;
select>
<resultMap id="StudentTeacher2" type="com.zhang.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="com.zhang.pojo.Teacher">
<result property="name" column="tname"/>
<result property="id" column="tid"/>
association>
resultMap>
此时,我们要根据老师查询学生,即:在输出老师信息时,输出学生的信息
Teacher.java(部分代码)
package com.zhang.pojo;
public class Teacher {
private int id;
private String name;
private List<Student> studentList;
}
Student.java(部分代码)
package com.zhang.pojo;
public class Student {
private int id;
private String name;
private int sid;
}
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid=t.id and t.id=#{tid}
select>
<resultMap id="TeacherStudent" type="com.zhang.pojo.Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="studentList" ofType="com.zhang.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
collection>
resultMap>
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id=#{tid}
select>
<resultMap id="TeacherStudent2" type="com.zhang.pojo.Teacher">
<collection property="studentList" javaType="ArrayList" ofType="com.zhang.pojo.Student" select="getStudentByTeacherId" column="id"/>
resultMap>
<select id="getStudentByTeacherId" resultType="com.zhang.pojo.Student">
select * from student where tid=#{tid}
select>
官方描述
动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
简言之
动态 SQL就是根据不同的条件生成不同的SQL语句。
CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8
package com.zhang.pojo;
public class Blog {
private int id;
private String title;
private String author;
private String createTime;
private int views;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
}
select * from mybatis.blog where 1=1
<if test="title != null">
and title=#{title}
if>
<if test="author != null">
and author=#{author}
if>
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
title=#{title}
when>
<when test="author != null">
and author=#{author}
when>
<otherwise>
and views=#{views}
otherwise>
choose>
where>
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。
而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
where
select * from mybatis.blog
<where>
<if test="title != null">
title=#{title}
if>
<if test="author != null">
and author=#{author}
if>
where>
set
update mybatis.blog
<set>
<if test="title!=null">
title=#{title},
if>
<if test="author!=null">
author=#{author}
if>
set>
where id=#{id}
有时候,我们将部分sql语句抽出来,方便复用
<sql id="if-title-author">
<if test="title != null">
title=#{title}
if>
<if test="author != null">
and author=#{author}
if>
sql>
<select id="queryBlogIF" parameterType="map" resultType="com.zhang.pojo.Blog">
select * from mybatis.blog
<where>
<include refid="if-title-author"/>
where>
select>
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)
<select id="queryBlogForeach" parameterType="map" resultType="com.zhang.pojo.Blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator=" or ">
id=#{id}
foreach>
where>
select>
@Test
public void queryBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<Integer>();
map.put("ids",ids);
ids.add(1);
ids.add(2);
ids.add(3);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了。
建议:
一次查询的结果,给他暂存在一个可以直接取到的地方!内存–>缓存
再次查询相同数据时,直接走缓存,就不查询数据库了
1.什么是缓存[ Cache ]?
MyBatis包含一个非常强大的查询缓存特性, 它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
一级缓存也叫本地缓存:
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
System.out.println("===========================");
User user2 = mapper.queryUserById(1);
System.out.println(user2);
sqlSession.close();
}
观察可得出,查询相同用户,sql语句只执行了一次,查询两个用户,sql语句执行了两次。
缓存失效情况:
sqlSession.clearCache();
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="cacheEnabled" value="true"/>
settings>
<cache/>
或
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession2 = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
sqlSession.close();
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User user2 = mapper2.queryUserById(1);
System.out.println(user2);
sqlSession2.close();
}