01 简介
1.1 什么是 Mybatis
1.2 持久化
数据持久化
1.3 持久层
Dao 层、Service 层、Controller 层
1.4 为什么需要 MyBatis
02 第一个 Mybatis 程序
思路:搭建环境 --> 导入 MyBatis --> 编写代码 --> 测试
2.1 搭建环境
搭建数据库
CREATE DATABASE mybatis;
USE mybatis;
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 VALUES (1,'狂神','123456');
INSERT INTO user VALUES (2,'张三','123456');
INSERT INTO user VALUES (3,'李四','123456');
SELECT * FROM user
复制代码
新建项目
创建一个普通的 maven 项目
删除 src 目录 (就可以把此工程当做父工程了,然后创建子工程)
导入 maven 依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--父工程-->
<groupId>org.example</groupId>
<artifactId>Mybatis_Study</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>Mybatis_01</module>
</modules>
<!--导入依赖-->
<dependencies>
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!--mybatis框架-->
<!--https://mvnrepository.com/artifact/org.mybatis/mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--junit测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
复制代码
创建 Module
编写 mybatis 工具类
2.2 创建一个模块
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration core file-->
<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="123456"/>
</dataSource>
</environment>
</environments>
<!--a Mapper.xml need regist in MybatisUtils core configuration file-->
<!--每一个Mapper.xml都需要在mybatis的核心配置文件中注册-->
<mappers>
<mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>
</configuration>
复制代码
package com.kuang.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";
//用Resources类把这个资源加载进来变成流
InputStream inputStream = Resources.getResourceAsStream(resource);
//通过builder加载流
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了SqlSessionFactory,顾名思义,我们就可以从中获得SqlSession的实例
//SqlSession完全包含了面向数据库执行SQL命令所需的所有方法
public static SqlSession getsqlSession(){
return sqlSessionFactory.openSession();
}
}
复制代码
2.3 编写代码
package com.kun.pojo;
//也叫model,简单的javabean就是数据库对应的实体类
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 + '\'' +
'}';
}
复制代码
package com.kuang.dao;
import com.kuang.pojo.User;
import java.util.List;
//Dao以后相当于mapper
//DAO(Data Access Object)数据访问对象。
// 主要的功能就是用于进行数据操作的,
// 在程序的标准开发架构中属于数据层的操作
public interface UserDao {
List<User> getUserList();
}
复制代码
<?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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<!--相当于对接口的实现-->
<!--sqlSession对象来调用这个配置文件中的sql语句-->
<mapper namespace="com.kuang.dao.UserDao">
<!--命名空间绑定的接口是上面这个-->
<!--select查询语句-->
<select id="getUserList" resultType="com.kuang.pojo.User">
<!--resultType是返回值类型,对应的是接口集合的泛型-->
select * from mybatis.user
</select>
</mapper>
复制代码
2.4 注意点
异常:org.apache.ibatis.binding.BindingException: Type interface com.kun.dao.UserDao is not known to the MapperRegistry.
<mappers>
<mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>
复制代码
MapperRegistry.–>映射器注册
java.lang.ExceptionInInitializerError---->资源导出失败的问题(资源过滤问题)
maven 由于他的约定大于配置,我们之后可能遇到我的写的配置文件无法被导出或者生效的问题,jvm 最后执行 target 目录文件,其中是没有 Mapper.xml 配置文件的,需要手动导入。或者作出一下操作:
<!--在maven的build中配置resources,防止我们资源导出失败的问题-->
<!--pom.xml-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
复制代码
package com.kuang.dao;
import com.kuang.pojo.User;
import com.kuang.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();
//方式一:getMapper
//执行sql,先通过接口UserDao得到接口的返回值
UserDao userDao = sqlSession.getMapper(UserDao.class);
//通过userDao调用getUserList方法拿到sql的结果集
List<User> userList = userDao.getUserList();
//方法二:
List<User> userList = sqlSession.selectList("com.kuang.UserDao.getUserList");
//需要自己根据接口返回类型去调用不同的函数,但是第一种就直接省了这一步,根据mapper里接口类型和resultType直接返回
for(User user:userList){
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
}
复制代码
会出现的问题
配置文件没有注册
绑定接口错误
方法名不对
返回类型不对 resultType
Maven 导出资源问题
03 CRUD
3.1 namespace
namespace 中的包名要和 Dao/mapper 接口的包名一致!
3.2 select
选择,查询语句:
1.接口编写
//查询全部用户信息
List<User> getUserList();
复制代码
2.编写对应的 mapper 中的 sql 语句
<select id="getUserList" resultType="com.kun.pojo.User">
select * from mybatis.user
</select>
复制代码
3.测试
@Test
public void getUserList(){
//第一步: 获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
//方式二:了解
//List<User> userList1 = sqlSession.selectList("com.kun.dao.UserDao.getUserList");
for(User user : userList){
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
复制代码
查询单个用户
<select id="getUserById" parameterType="int" resultType="com.kun.pojo.User" >
select * from mybatis.user where id = #{id};
</select>
复制代码
@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();
}
复制代码
3.3 insert
<insert id="addUser" parameterType="com.kuang.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(4,"wangwu","888888"));
if(res>0){
System.out.println("插入成功!!!");
}
//提交事务
sqlSession.commit();
sqlSession.close();
}
复制代码
3.4 update
<update id="updateUSer" parameterType="com.kun.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);
mapper.updateUser(new User(4,"王五","123123"));
sqlSession.commit();
System.out.println("修改成功!!!");
sqlSession.close();
}
复制代码
3.5 delete
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
</delete>
复制代码
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getsqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(4);
sqlSession.commit();
System.out.println("删除成功!!!");
sqlSession.close();
}
复制代码
3.6 分析错误
3.7 万能的 Map
//万能的Map 一枝独秀
int addUSer2(Map<String,Object> map);
复制代码
<!-- 一枝独秀 -->
<insert id="addUSer2" parameterType="map">
insert into mybatis.user (id,name) values(#{userid},#{username});
</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",7);
map.put("username","牛牛");
int res = mapper.addUSer2(map);
if(res > 0){
System.out.println("提交成功");
}
//提交事物 释放资源
sqlSession.commit();
sqlSession.close();
}
复制代码
Map 传递参数,直接在 sql 中取出 key 即可! 【paramType = “map”】
对象传递参数,直接在 sql 中去对象的属性即可! 【parameterType = “Object”】
只有一个基本参数的情况下,可以直接在 sql 中取到! 【即 parameType 可省略】
多个参数用 Map,或者注解!!!
3.8 思考题
模糊查询怎么写?
1.Java 代码执行的时候,传递通配符 %%
List<User> userlist = mapper.midUser("%大%");
复制代码
2.在 sql 拼接中使用通配符!! (同上比更安全)
select * from mybatis.user where name like "%"#{value}"%"
复制代码
3.9 注意点
//增、删、改 提交事物
sqlSession.commit();
//释放资源
sqlSession.close();
复制代码
如果还出现上诉的这样的类似错误,检查 UserMapper.xml 的**#{ }**中是否写了类的属性!!!
评论