mybatis官网:https://mybatis.org/mybatis-3/zh/getting-started.html
如何获取mybatis?
maven仓库:
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
Github:https://github.com/mybatis/mybatis-3/releases
中文文档:https://mybatis.org/mybatis-3/zh/getting-started.html
数据持久化
为什么需要持久化?
有一些对象,不能让他丢掉
内存太贵
dao层、service层、controller层
1.4 为什么需要mybatis?
帮助程序员将数据存入到数据库中
方便
传统的jdbc代码,太复杂,简化,框架,自动化
不用mybatis也可以,学了更容易上手
优点:
最重要的一点:使用的人多
思路:环境搭建–>导入mybatis–>编写代码–>测试!
搭建数据库
CREATE TABLE `user1`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL ,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user1`(`id`,`name`,`pwd`)
VALUES
(1,'梁伟大','123'),
(2,'大碗面','321'),
(3,'彭于晏','555')
新建项目
1.搭建一个maven项目
2.删除src目录。让他成为父工程
3.导入maven依赖
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.46version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
编写mybatis的核心配置文件
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<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=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
configuration>
编写mybatis工具类哦
package com.liang.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(){
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
// return sqlSessionFactory.openSession();
}
}
实体类
package pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
//实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
resultType:返回一个结果
resultMap:返回一个结果集
public interface UserDao {
List<User> getUserList();
}
接口实现类有原来的UserMapperImpl转变成一个Mapper配置文件
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.liang.dao.UserDao">
<select id="getUserList" resultType="com.liang.pojo.User">
select * from mybatis.user;
select>
mapper>
注意点:
org.apache.ibatis.binding.BindingException: Type interface com.liang.dao.UserDao is not known to the MapperRegistry.
MapperRegistry是什么?
核心配置文件中注册mappers
junit测试
package com.liang.dao;
import com.liang.pojo.User;
import com.liang.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();
//方式一:执行sql
UserDao userdao = sqlSession.getMapper(UserDao.class);
List<User> userList = userdao.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭sqlsession
sqlSession.close();
}
}
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
选择,查询语句;
//查询全部用户
List<User> getUserList();
//UserMapper.xml
<select id="getUserList" resultType="com.liang.pojo.User">
select *
from mybatis.user
</select>
//Test
@Test //查询user全部数据
public void test() {
//第一步:获得sqlsession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:执行sql
UserMapper userdao = sqlSession.getMapper(UserMapper.class);
List<User> userList = userdao.getUserList();
//方式2:
// List userList = sqlSession.selectList("com.liang.dao.UserDao.getUserList");
for (User user : userList) {
System.out.println(user);
}
//关闭sqlsession
sqlSession.close();
}
//根据id查询用户
User getUserById(int id);
//UserMapper.xml
<select id="getUserById" parameterType="int" resultType="com.liang.pojo.User">
select * from mybatis.user where id= #{id}
</select>
@Test //根据id查询用户
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
//增加一个用户
int addUser(User user);
//UserMapper.xml
<insert id="addUser" parameterType="com.liang.pojo.User">
insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
@Test //增删改需要事务
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.addUser(new User(20, "啦啦啦", "1111"));
if (res>0){
System.out.println("插入成功");
}
//提交事务
sqlSession.commit();
sqlSession.close();
}
//修改用户
int updateUser(User user);
//UserMapper.xml
<update id="updateUser" parameterType="com.liang.pojo.User">
update mybatis.user
set name = #{name },pwd=#{pwd}
where id=#{id};
</update>
@Test //修改用户
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.updateUser(new User(1, "l222", "12212"));
if (i>0){
System.out.println("修改成功");
}
//提交事务
sqlSession.commit();
sqlSession.close();
}
//删除用户
int deleteUser(int id);
//UserMapper.xml
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
</delete>
//根据id删除
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.deleteUser(3);
if (i>0){
System.out.println("删除成功");
}
//增删改需要提交 事务
sqlSession.commit();
sqlSession.close();
}
注意点:
- 增删改需要提交事务!
假设我们的实体类,或者数据库表中的表,字段或者参数过多,我们应该适当
//万能的map
int addUser2(Map<String,Object> map);
//对象中的属性,可以直接取出来 传递map的key
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id,name,pwd) values (#{userid},#{username},#{password})
insert>
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String,Object> map=new HashMap<String,Object>();
map.put("userid", 30);
map.put("username","www");
map.put("password", "888");
mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
Map传递参数,直接在sql取出key即可 【parameterType=“map”】
对象传递参数,直接在sql中取对象的属性即可 [parameterType=“object”]
只有一个基本类型的参数的情况下,可以直接在sql取到
多个参数用Map,或者注解
模糊查询怎么写?
java代码执行的时候,传递通配符%%
//模糊查询
List<User> getUserLike(String value);
<select id="getUserLike"resultType="com.liang.pojo.User">
select * from mybatis.user where name like #{value}
select>
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userlist = mapper.getUserLike("吴%");
for (User user : userlist) {
System.out.println(user);
}
sqlSession.commit();
sqlSession.close();
}
在sql拼接中使用通配符
select * from mybatis.user where name like "%"#{value}"%"
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
MyBatis 可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
mybatis默认的事务管理器就是jdbc,连接池:pooled
我们可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.properties】
编写一个配置文件
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=root
mybatis-config.xml
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="pwd" value="1221"/>
</properties>
<typeAliases>
<typeAlias type="com.liang.pojo.User" alias="User"/>
typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,
扫描实体类的包,它的默认别名就是为了这个类的 类名,首字母小写!
<typeAliases>
<package name="com.liang.pojo"/>
typeAliases>
在实体类较少的时候,使用第一种方式
如果实体类十分多,建议使用第二种
第一种可以diy别名,第二种则不行,如果非要改,则在实体类上增加注解
@Alias("user")
public class User {}
理解我们之前讨论过的不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder:
SqlSessionFactory:
SqlSession:
public class User {
private int id;
private String name;
private String password;
}
测试出现问题
// select * from mybatis.user where id=#{id}
//类型处理器
// select id,name,pwd from mybatis.user where id=#{id}
<select id="getUserById"resultType="com.liang.pojo.User">
select id,name,pwd as password from mybatis.user where id=#{id}
</select>
结果映射值
id name pwd
id name password
<resultMap id="UserMap" type="User">
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
resultMap>
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id=#{id}
select>
resultMap
元素是 MyBatis 中最重要最强大的元素如果一个数据库操作,出现了异常,我们需要拍错,日志就是最好的助手!
曾经:sout、debug
现在:日志工厂
在mybatis中具体使用哪一个日志实现,在设置中设定!
STDOUT_LOGGING标准日志输出
标准的日志实现
<!--mybatis日志-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
什么是logj?
1.先导入log4j包
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
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/liang.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
3.配置log4j为日志的实现
<settings>
<setting name="logImpl" value="LOG4J"/>
settings>
4.Log4j的使用,直接测试运行刚才的查询
简单使用
1.在要使用Log4j的类中,导入包import org.apache.log4j.Logger
2.日志对象,参数为当前类的class
提到上面,因为一个方法不能在多个类里使用,提升作用域,就可以了
static Logger logger=Logger.getLogger(UserDaoTest.class);
package com.liang.dao;
import com.liang.pojo.User;
import com.liang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;
public class UserDaoTest {
static Logger logger=Logger.getLogger(UserDaoTest.class);//提升作用域
//据id查询用户
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(2);
System.out.println(user);
sqlSession.close();
}
// select * from mybatis.user where id=#{id}
//类型处理器
// select id,name,pwd from mybatis.user where id=#{id}
@Test
public void testLog4j(){
logger.info("info:进入了testLog4j");
logger.debug("info:进入了testLog4j");
logger.error("info:进入了testLog4j");
}
}
思考:为什么要分页?
语法:select * from user limit startIndex,pageSize;
select * from user limit 10;[0,10]
使用mybatis实现分页,核心sql
1.接口
//分页
List<User> getUserByLimit(Map<String,Integer>map);
2.mapper.xml
<resultMap id="UserMap" type="User">
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
resultMap>
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{startIndex},#{pageSize}
select>
3.测试
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize", 3);
List<User> userList=mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
不再使用sql实现分页
1.接口
//分页
List<User> getUserByLimit(Map<String,Integer>map);
2.mapper.xml
<select id="getUserRowBounds" resultMap="UserMap">
select * from mybatis.user
select>
3.测试
@Test
public void getUserRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//RowBounds实现
RowBounds rowBounds = new RowBounds(1,2);
//通过java代码实现代码层面实现分页
List<Object> list = sqlSession.selectList("com.liang.dao.UserMapper.getUserRowBounds",null,rowBounds);
for (Object o : list) {
System.out.println(o);
}
sqlSession.close();
}
注解在接口上实现
@Select("select * from user")
List<User> getUser();
需要在核心配置文件中绑定接口!
<mappers>
<mapper class="dao.UserMapper"/>
mappers>
本质:反射机制实现
底层:动态代理
mybatis详细执行流程!
我们可以在工具类创建的时候实现自动提交事务!
public static SqlSession getSqlSession() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
return sqlSession;
编写接口,增加注解
@Select("select * from user")
List<User> getUser();
//方法存在多个参数,所有的参数前面必须要加上@param("id")注解
@Select("select * from user where id=#{id}")
User getUserByID(@Param("id")int id);
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
int addUser(User user);
@Update("update user set name=#{name},pwd=#{password} where id=#{id}")
int updateUser(User user);
@Delete("delete from user where id =#{id}")
int delateUser(@Param("id") int id);
测试类
【注意:我们必须要将接口注册绑定到我们的核心配置文件中!】
关于@Param()注解
基本类型的参数或者string类型,需要加上
引用类型不需要加
如果只有一个基本类型的话,可以忽略,但是建议大家加上
我们在sql中引用的就是我们这里的@Param()设定的属性名
#{} ${}区别
使用步骤:
在idea中安装lombok插件
在项目中导入lombok的包
3.在实体类上加注解
多对一:
sql:
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 `student1` (
`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 `student1` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student1` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student1` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student1` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student1` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
导入lombok
新建实体类Teacher,Student
package com.liang.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private Teacher teacher;
}
package com.liang.pojo;
import lombok.Data;
@Data
public class Teacher {
private int id;
private String name;
}
建立Mapper接口
package com.liang.dao;
public interface StudentMapper {
}
package com.liang.dao;
import com.liang.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface TeacherMapper {
@Select("select * from teacher where id=#{tid}")
Teacher getTeacher(@Param("tid")int id);
}
在resources同文件目录下,建立Mapper.xml文件
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.liang.dao.StudentMapper">
mapper>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.liang.dao.TeacherMapper">
mapper>
在核心配置文件中绑定注册我们的Mapper接口或者文件【方法很多,随心选】
<mappers>
<mapper class="com.liang.dao.TeacherMapper"/>
<mapper class="com.liang.dao.StudentMapper"/>
mappers>
测试查询结果是否能成功
import com.liang.dao.TeacherMapper;
import com.liang.pojo.Teacher;
import com.liang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
public class MyTest {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
}
D:\JavaEnvironment\jdk1.8.0_152\bin\java.exe "-javaagent:D:\Study software\IntelliJ IDEA 2020.3\lib\idea_rt.jar=57633:D:\Study software\IntelliJ IDEA 2020.3\bin" -Dfile.encoding=UTF-8 -classpath D:\JavaEnvironment\jdk1.8.0_152\jre\lib\charsets.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\deploy.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\ext\access-bridge-64.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\ext\cldrdata.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\ext\dnsns.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\ext\jaccess.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\ext\jfxrt.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\ext\localedata.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\ext\nashorn.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\ext\sunec.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\ext\sunjce_provider.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\ext\sunmscapi.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\ext\sunpkcs11.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\ext\zipfs.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\javaws.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\jce.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\jfr.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\jfxswt.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\jsse.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\management-agent.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\plugin.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\resources.jar;D:\JavaEnvironment\jdk1.8.0_152\jre\lib\rt.jar;D:\IdeaWorkSpace2\Mybatis-Study\mybatis-06\target\test-classes;D:\IdeaWorkSpace2\Mybatis-Study\mybatis-06\target\classes;D:\JavaEnvironment\maven\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar;D:\JavaEnvironment\maven\org\mybatis\mybatis\3.5.2\mybatis-3.5.2.jar;D:\JavaEnvironment\maven\junit\junit\4.12\junit-4.12.jar;D:\JavaEnvironment\maven\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\JavaEnvironment\maven\org\projectlombok\lombok\1.18.12\lombok-1.18.12.jar;D:\JavaEnvironment\maven\log4j\log4j\1.2.17\log4j-1.2.17.jar MyTest
log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Class not found: org.jboss.vfs.VFS
JBoss 6 VFS API is not available in this environment.
Class not found: org.jboss.vfs.VirtualFile
VFS implementation org.apache.ibatis.io.JBoss6VFS is not valid in this environment.
Using VFS adapter org.apache.ibatis.io.DefaultVFS
Find JAR URL: file:/D:/IdeaWorkSpace2/Mybatis-Study/mybatis-06/target/classes/com/liang/pojo
Not a JAR: file:/D:/IdeaWorkSpace2/Mybatis-Study/mybatis-06/target/classes/com/liang/pojo
Reader entry: Student.class
Reader entry: Teacher.class
Listing file:/D:/IdeaWorkSpace2/Mybatis-Study/mybatis-06/target/classes/com/liang/pojo
Find JAR URL: file:/D:/IdeaWorkSpace2/Mybatis-Study/mybatis-06/target/classes/com/liang/pojo/Student.class
Not a JAR: file:/D:/IdeaWorkSpace2/Mybatis-Study/mybatis-06/target/classes/com/liang/pojo/Student.class
Reader entry: ���� 4 ^
Find JAR URL: file:/D:/IdeaWorkSpace2/Mybatis-Study/mybatis-06/target/classes/com/liang/pojo/Teacher.class
Not a JAR: file:/D:/IdeaWorkSpace2/Mybatis-Study/mybatis-06/target/classes/com/liang/pojo/Teacher.class
Reader entry: ���� 4 L
Checking to see if class com.liang.pojo.Student matches criteria [is assignable to Object]
Checking to see if class com.liang.pojo.Teacher matches criteria [is assignable to Object]
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1604125387.
==> Preparing: select * from teacher where id=?
==> Parameters: 1(Integer)
<== Columns: id, name
<== Row: 1, 秦老师
<== Total: 1
Teacher(id=1, name=秦老师)
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@5f9d02cb]
Returned connection 1604125387 to pool.
Process finished with exit code 0
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.liang.dao.StudentMapper">
<select id="getStudent" resultMap="StudentTeacher">
select * from student1;
select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id}
select>
mapper>
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname
from student1 s,teacher t where s.tid=t.id;
select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
association>
resultMap>
回顾Mysql多对一查询方式:
比如:一个老师拥有多个学生!
对于老师来说,就是一对多关系
1.环境搭建,和刚才一样
实体类
package com.liang.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private int tid;
}
package com.liang.pojo;
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student> students;
}
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="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 mybatis.teacher where id=#{tid}
select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from mybatis.student1 where tid =#{tid}
select>
小结
注意点:
什么是动态sql:动态sql就是指根据不同的条件生成不同deSQL语句
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.liang.pojo;
import lombok.Data;
import java.util.Date;
@Data
public class Blog {
private int id;
private String title;
private String author;
private Date createTime;
private int views;
}
编写实体类对应Mapper接口和Mapper.XML文件
如何开启驼峰命名
<settings> <setting name="logImpl" value="STDOUT_LOGGING"/> <setting name="mapUnderscoreToCamelCase" value="true"/> settings>
//查询博客
List<Blog> queryBlogIF(Map map);
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog where 1=1
<if test="title!= null">
and title = #{title}
if>
<if test="author != null">
and author = #{author}
if>
select>
@Test
public void queryBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap<>();
map.put("title", "Java");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
<select id="queryBlogChoose" parameterType="map" resultType="blog">
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>
select>
select * from mybatis.blog
<where>
<if test="title!= null">
title = #{title}
if>
<if test="author != null">
and author = #{author}
if>
where>
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title !=null">
title=#{title},
if>
<if test="author !=null">
author =#{author}
if>
set>
where id=#{id}
update>
所谓的动态sql,本质还是sql语句,只是我们可以在sql层面,去执行一个逻辑代码
有的时候,我们可能将一些功能的部分抽出来,方便复用!
1.使用sql标签抽取公共部分
<sql id="if-title-author">
<if test="title !=null">
title=#{title}
</if>
<if test="author !=null">
author =#{author}
</if>
</sql>
2.在需要使用的地方使用include标签引用即可
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
注意事项:
select * from user where 1=1
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
foreach>
where>
select>
动态sql就是在拼接sql语句,我们只要保证sql的正确性,按照sql的格式,去排列组合就可以了
查询:连接数据库,耗资源
一次查询的结果,给他暂存在一个可以直接去到他的地方!–》内存:缓存
我们再次查询相同的数据的时候,直接走缓存,就不用走数据库
三高:高并发、高可用、高性能
读写分离,主从复制
LUR mybatis默认清除策略,最少使用的清除
开启日志
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
测试在一个sqlsession中查询两次的相同记录
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> user = mapper.queryUserById(1);
System.out.println(user);
System.out.println("============");
List<User> user1 = mapper.queryUserById(1);
System.out.println(user1);
System.out.println(user==user1);
sqlSession.close();
}
查看日志输出
缓存失效的情况:
sqlSession.clearCache();//手动清理缓存
小结:一级缓存是默认开启的,只在一次sqlsession中有效,也就是在拿到连接到关闭这个区间段有效!
一级缓存相当于一个map。
1.开启全局缓存
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="cacheEnabled" value="true"/>
settings>
2.在要使用二级缓存的mapper中开启
<cache/>
3.测试
报错:java.io.NotSerializableException: com.liang.pojo.User
小结:
<dependency>
<groupId>org.mybatis.cachesgroupId>
<artifactId>mybatis-ehcacheartifactId>
<version>1.1.0version>
dependency>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
ehcache>
在mapper.xml配置
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
Redis数据库做缓存! k-v结构
总结: