视频
MyBatis原理分析(通俗易懂)
入门JDBC
create table `user`(
`id` int(20) not null PRIMARY KEY,
`name` varchar(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
insert into `user`(`id`,`name`,`pwd`) VALUES
(1,'张若尘','123hho'),
(2,'唐三','21h3u1h'),
(3,'石昊','h32h4'),
(4,'萧炎','4h5oi'),
(5,'林动','j4l65jho'),
(6,'霍雨浩','5ho34ho')
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.25version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.7version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
<scope>testscope>
dependency>
dependencies>
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
settings>
<typeAliases>
<package name="com.pojo"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/dao/UserMapper.xml"/>
mappers>
configuration>
pojo:写每一个数据库表对应的类
dao:是对数据库增删查改的接口
impl:实现对dao层的接口
从 XML 中构建 SqlSessionFactory,从 SqlSessionFactory 中获取 SqlSession
主要是为了获取执行sql语句的对象
package com.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{
//获取sqlSessionFactory对象
String resource = "config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e){
e.printStackTrace();
}
}
//获取SqlSession实例
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
package com.pojo;
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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
<?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.dao.UserDao">
<select id="getUserList" resultType="com.pojo.User">
select * from user
</select>
</mapper>
<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>
package com.dao;
import com.pojo.User;
import com.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserTest {
@Test
public void getUserList(){
SqlSession sqlSession = MybatisUtils.getSqlSession();//获取能够执行sql语句的对象
//执行sql
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭sqlSession
sqlSession.close();
}
}
注意:增删改需要提交事物
//增删改需要提交失物
@Test
public void addTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();//获取能够执行sql语句的对象
//执行sql
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user = new User();
user.setId(7);
user.setName("李逍遥");
user.setPwd("4g3ui12gi");
boolean flag = userDao.add(user);
if(flag){
System.out.println("插入成功");
}
//提交事务
sqlSession.commit();
//关闭sqlSession
sqlSession.close();
}
Dao层
理解参数是一个map和返回值是一个map特别有作用
public boolean add2(Map<String,Object> map);
public User findById2(Map<String,Object> map);
public Map<String,Object> findById(int id);
Mapper层
这个就可以不用和实体类定义的属性名保持一致了,
<insert id="add2" parameterType="map">
insert into user(id,name,pwd) values(#{Userid},#{Username},#{Userpwd})
</insert>
<select id="findById2" parameterType="map" resultType="com.pojo.User">
select * from user where id = #{userId};
</select>
<select id="findById" resultType="map">
select name,pwd from user where id = #{id}
</select>
@Test
public void add2Test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();//获取能够执行sql语句的对象
//执行sql
UserDao userDao = sqlSession.getMapper(UserDao.class);
Map<String,Object> map = new HashMap<String,Object>();
map.put("Userid",7);
map.put("Username","张楚岚");
map.put("Userpwd","32yh4oy");
boolean flag = userDao.add2(map);
if(flag){
System.out.println("插入成功");
}else{
System.out.println("插入失败");
}
//提交事务
sqlSession.commit();
//关闭sqlSession
sqlSession.close();
}
@Test
public void findById2Test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();//获取能够执行sql语句的对象
//执行sql
UserDao userDao = sqlSession.getMapper(UserDao.class);
Map<String,Object> map = new HashMap<>();
map.put("userId",1);
User user = userDao.findById2(map);
System.out.println(user);
}
@Test
public void findByIdTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();//获取能够执行sql语句的对象
//执行sql
UserDao userDao = sqlSession.getMapper(UserDao.class);
Map<String, Object> map = userDao.findById(2);
map.forEach((key,value) ->{
System.out.println(key + ":" +value);
});
//关闭sqlSession
sqlSession.close();
}
注意点:
在pom.xml文件中build中配置resources,来防止我们资源导出失败的问题
在config.xml主要记得编辑数据库、用户名、密码、注册映射器
在Mapper.xml文件中要记得编辑实现哪个接口