环境:
回顾:
获取Mybatis?
maven仓库:
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
数据持久化:
为什么需要持久化?
Dao层、Service层、Controller层
搭建数据库:
Create Table
CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT INTO `user` (`id`,`name`,`pwd`) VALUES
(1,'张三','123456'),
(2,'李四','123456'),
(3,'王五','123456')
新建项目:
mysql mysql-connector-java 5.1.47 org.mybatis mybatis 3.5.4 junit junit 4.12
编写核心配置文件
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties"/>
<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=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value=""/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/baidu/dao/UserMapper.xml"/>
mappers>
configuration>
编写Mybatis工具类
package com.baidu.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 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();
}
}
package com.baidu.pojo;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
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 getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
public interface UserMapper {
//查询全部用户
List<User> getUserList();
//根据ID查询用户
User getUserById(int id);
//插入一个用户
int addUser(User user);
//修改一个用户
int updateUser(User user);
//删除一个用户
int deleteUser(int id);
//分页
List<User> getUserByLimit(Map<String,Integer> map);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.baidu.dao.UserMapper">
<resultMap id="UserMap" type="User">
</resultMap>
<select id="getUserList" resultType="com.baidu.pojo.User" >
select * from mybatis.user;
</select>
<select id="getUserById" resultType="com.baidu.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id}
</select>
<insert id="addUser" parameterType="com.baidu.pojo.User">
insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd});
</insert >
<update id="updateUser" parameterType="com.baidu.pojo.User">
update mybatis.user set name = #{name},pwd = #{pwd} where id = #{id};
</update>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
</delete>
<select id="getUserByLimit" parameterType="map" resultType="UserMap">
select * from mybatis.user limit #{startIndex},#{pageSize};
</select>
</mapper>
MapperRegistry是什么?
核心配置文件中注册mappers
@Test
public void test(){
//获取sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//getMapper
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
namespace中的包名要和mapper接口的报名一致
选择、查询语句
1.编写接口
//根据ID查询用户
User getUserById(int id);
2.编写对应的mapper中的sql语句
<select id="getUserById" resultType="com.baidu.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id}
</select>
3.测试
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
<insert id="addUser" parameterType="com.baidu.pojo.User">
insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd});
<update id="updateUser" parameterType="com.baidu.pojo.User">
update mybatis.user set name = #{name},pwd = #{pwd} where id = #{id};
</update>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
</delete>
注意:增删改需要提交事务
MyBatis可以配置成适应多种环境
尽管可以配置多个环境,但每个SqlSessionFactory实例只能选择一种环境
Mybatis默认的事务管理器就是JDBC,连接池;POOLED
可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替换的,既可以在典型的Java属性文件配置,也可通过properties元素的子元素来传递【db.properties】
配置文件:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=
<typeAliases>
<typeAlias type="com.baidu.pojo.User" alias="User"/>
typeAliases>
也可以指定一个包名,Mybatis会在包名下面搜索需要的Java Bean,比如:扫描实体类的包,它的默认别名为这个类的类名,首字母小写。
<typeAliases>
<typeAlias name="com.baidu.pojo"/>
typeAliases>
实体类比较少的情况下使用第一种
实体类较多的话使用第二种
Mybatis中极为重要的设置,他们会改变Mybatis的行为
MapperRegistry:
方式一:xml核心配置文件
<mapper resource="com/baidu/dao/UserMapper.xml"/>
方式二:使用class文件绑定注册
<mapper class="com.baidu.dao.UserMapper"/>
注意点:
方式三:使用扫描包进行注入绑定
<package name="com.baidu.dao"/>
注意点同上
生命周期和作用域的错误使用会导致严重的并发问题
SqlSessionFactoryBulider:
SqlSessionFactory:
SqlSession:
每一个mapper代表一个具体的业务!
设置实体类字段不一致
private int id;
private String name;
private String password;
出现问题:
User{id=1, name='张三', password='null'}
解决办法:起别名
select id,name,pwd as password from mybatis.user where id = #{id}
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--column数据库中的字段,property实体类中的属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
在mybatis中使用哪个日志,在设置中设定!
STDOUT_LOGGING标准日志输出
在mybatis核心配置文件中配置我们的日志
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
<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/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
在这里插入代码片
<settings>
<setting name="logImpl" value=""/>
settings>
static Logger logger = Logger.getLogger(UserDaoTest.class);
logger.info("info:进入");
logger.debug("debug:进入");
logger.error("error:进入");
目的就是减少数据的处理量
使用Mybatis实现分页,核心SQL
//分页
List<User> getUserByLimit(Map<String,Integer> map);
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
@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",2);
List<User> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Select("select * from user")
List<User> getUsers();
<mappers>
<mapper class="com.baidu.dao.UserMapper"/>
mappers>
步骤:
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
@Data
@AllArgsConstructor
@NoArgsConstructor
按照查询嵌套处理:
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
</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>
按照结果嵌套处理:
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sname,s.name sname,t.name tname
from student s,teacher t
where s.tid = t.id;
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="id"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
环境搭建
实体类:
public class Student {
private int id;
private String name;
private int tid;
}
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student> students;
}
<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="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>
根据不同的条件来生成不同的SQL
基础工程“
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
<!--开启缓存-->
<setting name="cacheEnabled" value="true"/>