mysql
mysql-connector-java
5.1.47
org.mybatis
mybatis
3.5.2
junit
junit
4.12
test
//在父,子pom.xml里都需要加入一下代码,不然不会被maven过滤
src/main/resources
**/*.properties
**/*.xml
true
src/main/java
**/*.properties
**/*.xml
true
settings中可选的属性
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=111111
package com.jyy.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;
public class MybatisUtils {
private static SqlSessionFactory factory;
static{
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
factory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return factory.openSession(true); //true参数表示开启事务
}
}
package com.jyy.dao;
import com.jyy.pojo.User;
import java.util.List;
public interface UserDao {
List getUserList();
User getUserById(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
insert into Mybatis.user (id, name, pwd) values (#{id}, #{name}, #{pwd})
update mybatis.user set name = #{name},pwd=#{pwd} where id = #{id}
delete from mybatis.user where id = #{id}
int updateUserByMap(Map map);
update mybatis.user set pwd = #{userpwd} where id = #{userid} ;
测试时:
map.put("userid",1);
map.put("userpwd","111111");
mapper.updateUserByMap(map);
方式一:推荐
value传入 "%张三%"
方式二:不推荐,存在sql注入问题
value传入 "张三"
(1)使用STDOUT_LOGGING默认日志工厂
(2)使用LOG4J日志工厂
maven依赖
log4j
log4j
1.2.17
在resource文件夹中创建log4j.properties文件
#将等级为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/kuang.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
在mybatis-config.xml中加入配置
使用:
public class UserDaoTest {
// log4j,获取类字节码
static Logger logger = Logger.getLogger(UserDaoTest.class);
@Test
public void getUserById(){
// 第一步获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
// 最后一步关闭sqlSession
sqlSession.close();
}
@Test
public void testLog4j(){
//日志级别
logger.info("info进入了:testLog4j");
logger.debug("debug进入了:testLog4j");
logger.error("error进入了:testLog4j");
}
}
方法1:接口中的方法和mapper.xml中的写法:测试时直接传入map即可
List getUserByLimit(Map map);
方法2:RowBounds分页。不推荐,已经过时
mappers配置
package com.it.Dao;
import com.it.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
import java.util.Map;
public interface UserMapper {
// 查询全部用户
@Select("select * from user")
List getUserList();
// 存在多个参数
@Select("select * from user where id = #{id} and pwd = #{pwd}")
User getUserByIdPwd(@Param("id")int id,@Param("pwd") String pwd);
// 增:返回值类型只能用int不能用User,否则会报错org.apache.ibatis.binding.BindingException: Mapper method 'com.it.Dao.UserMapper.addUser' has an unsupported return type: class com.it.pojo.User
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{pwd})")
int addUser(User user);
// 改 @Param,只要有基本类型参数,有几个参数就写几个@Param。
@Update("update user set name=#{name} where id=#{id}")
int updateUser(@Param("name") String name,@Param("id") int id);
// 删
@Delete("delete from user where id = #{id}")
int deleteUser(@Param("id") int id);
}
首先得安装:IDEA中:File→Settings→Plugins→搜索Lombok
引入Lombok的maven依赖:
org.projectlombok
lombok
1.18.8
使用方法:
@Getter@Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor(所有参数构造)
@NoArgsConstructor(无参构造)
@Data(相当于添加了@Getter@Setter@ToString@NoArgsConstructor(无参构造))
package com.it.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
多个学生关联一个老师(让学生关联老师)
Student类和Teacher类
package com.jyy.pojo;
import lombok.Data;
@Data
public class Teacher {
private int id;
private String name;
}
package com.it.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
//通过多个学生查老师。此处使用老师类型作为参数,意为返回一个老师对象。
private Teacher teacher;
}
TeacherMapper和StudentMapper接口
public interface StudentMapper {
public List getStudent();
public List getStudent2();
}
public interface TeacherMapper {
// @Select("select * from mybatis.teacher where id = #{tid}")
Teacher getTeacher(@Param("tid") int id);
}
方式1:查询嵌套处理
因为Student类中包含teacher类,需要用resultMap映射
方式2:按结果嵌套处理,相比更简单
多个学生关联一个老师(让老师关联学生)
Student类和Teacher类
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private int tid;
}
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private int id;
private String name;
private List students;
}
TeacherMapper接口
public interface TeacherMapper {
Teacher getTeacher(@Param("tid") int id);
}
配置mapper.xml:
(1)Where-IF语句
(2)Where-choose-when-otherwise语句
(3)set-if语句
update mybatis.blog
title = #{title},
author = #{author},
create_time = #{create_time},
views = #{views}
where id = #{id}
(4)SQL片段
title = #{title},
author = #{author},
create_time = #{create_time},
views = #{views}
(5)for-each
一级缓存:
一级缓存默认开启,只在一次sqlSession中有效,也就是从getSqlSession()到close()的过程
失效情况:(1)查询不同东西
(2)增删改语句就会可能改变sql的内容。因此,执行完增删改之后,就会重新执行sql,刷新缓存。
(3)查询不同的Mapper.xml
(4)手动清理缓存:sqlSession.clearCache();
二级缓存:
步骤:
(1)首先,确保开启
(2)在想要开启的mapper.xml中加入cache标签,即开启;也可以设置参数配置
查询顺序:先找二级缓存,再找一级缓存,如果都没有,就去连接数据库
自定义缓存:
(1)导入依赖
org.mybatis.caches
mybatis-ehcache
1.1.0
(2)配置mapper.xml
(3)在resource中创建ehcache.xml文件
reference:
1. https://github.com/Davis-Samuel/Mybatis-order
2. 狂神说java:https://www.bilibili.com/video/BV1NE411Q7Nx?p=28
3.Mybatis中文手册:https://mybatis.org/mybatis-3/zh/index.html