环境:
- JDK1.8
- MySQL 5.7
- maven 3.6.1
- IDEA
回顾
- JDBC
- Mysql
- java基础
- Maven
- Junit
第一个Mybatis程序
搭建环境
- 搭建数据库
create database mybatis;
use mybatis;
create table user (
id int(20) not null primary key,
name varchar(20) default null,
pwd varchar(40) default null
)engine=Innodb default charset=utf8;
insert into user values
(1,'zhangsan','123456'),
(2,'lisi','123456'),
(3,'wangwu','123456');
- 新建一个Maven项目
- 导入jar包依赖
创建一个模块
- 编写Mybatis核心配置文件
- 编写Mybatis工具类
package com.lili.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 {
//获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
private static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
-
编写代码
- 实体类
- Dao接口
- Dao实现类
CRUD
- 编写接口
package com.lili.dao;
import com.lili.pojo.User;
import java.util.List;
public interface UserDao {
//查询全部用户
List<User> getUserList();
//根据ID查询用户
User getUserById(int id);
//insert 一个用户
int addUser(User user);
//update一个用户
int updateUser(User user);
//删除一个用户
int deleteUser(int id);
}
- 编写对应的sql语句
<?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.lili.dao.UserDao">
<select id="getUserList" resultType="com.lili.pojo.User">
select * from mybatis.user
</select>
<select id="getUserById" parameterType="int" resultType="com.lili.pojo.User">
select * from mybatis.user where id = #{id}
</select>
<insert id="addUser" parameterType="com.lili.pojo.User">
insert into mybatis.user values (#{id},#{name},#{pwd});
</insert>
<update id="updateUser" parameterType="com.lili.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>
</mapper>
- 测试
package com.lili.dao;
import com.lili.pojo.User;
import com.lili.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 = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
User userById = mapper.getUserById(1);
System.out.println(userById);
sqlSession.close();
}
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int add = mapper.addUser(new User(4, "得到", "123456"));
if (add>0){
System.out.println("数据插入成功!");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int did = mapper.updateUser(new User(4, "地点", "123123"));
if (did>0){
System.out.println("成功修改!");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
mapper.deleteUser(4);
sqlSession.commit();
sqlSession.close();
}
}
- 万能map
//万能map
int addUser2(Map<String,Object> map);
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id,pwd) values (#{id},#{pwd});
</insert>
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
Map<String, Object> map = new HashMap<>();
map.put("id",5);
map.put("pwd","123123");
mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
环境配置(envirouments)
属性(properties)
类型别名(typeAliases)
设置(settings)
映射器(mappers)
日志
logImpl
-
SLF4J
-
LOG4J【掌握】
-
LOG4J2
-
JDK_LOGGING
-
COMMONS_LOGGING
-
STDOUT_LOGGING [掌握]
-
NO_LOGGING
STDOUT_LOGGING
标准日志输出
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
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 1027591600.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3d3fcdb0]
==> Preparing: select * from mybatis.user where id = ?
==> Parameters: 1(Integer)
<== Columns: id, name, pwd
<== Row: 1, zhangsan, 123456
<== Total: 1
User(id=1, name=zhangsan, pwd=123456)
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3d3fcdb0]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3d3fcdb0]
Returned connection 1027591600 to pool.
LOG4J
先导包
分页
-
//分页 List<User> getUserByLimit(Map<String,Integer> map); //分页2 List<User> getUserRowBounds();
注解的用法
复杂查询环境搭建
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 students(
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 students (id,name,tid) values
('1','小明','1'),
('2','小红','1'),
('3','小王','1'),
('4','小虎','1'),
('5','小天','1');
按照查询嵌套处理
<select id="getStudents" resultMap="StudentsTeacher">
select * from mybatis.students
</select>
<resultMap id="StudentsTeacher" type="Students">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="tid" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from mybatis.teacher where id = #{id}
</select>
缓存
查询数据库,耗资源
一次查询,把数据放在一个缓存的地方
一定程度解决了三高问题,高并发,高可用,高性能