环境
回顾:
SSM框架:配置文件的。最好的方式:看文档官网;
MyBatis 是一款优秀的持久层框架
什么叫持久层框架
为什么要使用持久化框架?
它支持自定义 SQL、存储过程以及高级映射。
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名为MyBatis 。
2013年11月迁移到Github。
iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)
如何获得Mybatis?
maven仓库:Maven Repository: org.mybatis ? mybatis ? 3.5.2 (mvnrepository.com)
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
数据持久化
为什么需要持久化
Dao层,Service层,Controller层...
https://www.bilibili.com/video/BV1NE411Q7Nx
最重要的一点:使用的人多!
Spring SpringMVC SpringBoot
搭建数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) 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,‘lxw‘,‘123456‘),
(2,‘tom‘,‘123456‘),
(3,‘lee‘,‘123456‘)
新建项目
新建一个普通的maven项目
删除src目录,把项目当父工程
导入依赖
<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
编写mybatis核心配置文件:mybatis-config
<?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核心配置文件-->
<configuration>
<!--environments环境,可以多个-->
<environments default="development">
<environment id="development">
<!--transactionManager事务管理-->
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!--允许安全链接useSSL=true
useSSL=false
MySQL在高版本需要指明是否进行SSL连接
1.true 需要连接
2.false 不需要连接
在xml配置文件中配置数据库URL时,要使用&的转义字符也就是&
让他们使用Unicode编码,useUnicode=true
-->
<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="root"/>
</dataSource>
</environment>
</environments>
</configuration>
编写mybatis工具类
package com.lxw.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.InputStream;
//SqlSessionFactory-->生产sqlSession
public class MybatisUtils {
//定义全局变量,提升作用域
private static SqlSessionFactory sqlSessionFactory;
static {
String resource = null;
try {
//使用mybatis第一步,使用Mybatis获取sqlSessionFactory对象
resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例了。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL
public static SqlSession getSqlSession(){
//优化SqlSession sqlSession = sqlSessionFactory.openSession();
//return sqlSession
return sqlSessionFactory.openSession();
}
}
实体类
package com.lxw.pojo;
//实体类
public class User {
//private 私有的
private int id;
private String name;
private String pwd;
//无参构造 alt+insert Constructor->Constructor
public User() {
}
//有参构造 alt+insert Constructor->全选
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
//get\set alt+insert 选Getter和Setter然后全选
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;
}
//toString:异常打印信息alt+insert 选toString 然后全选
@Override
public String toString() {
return "User{" +
"id=" + id +
", name=‘" + name + ‘\‘‘ +
", pwd=‘" + pwd + ‘\‘‘ +
‘}‘;
}
}
Dao接口
package com.lxw.dao;
import com.lxw.pojo.User;
import java.util.List;
public interface UserDao {
//Lsit<>这是泛型
List<User> getUserList();
}
接口实现类由原来的UserDaoImpl转变为一个Mapper配置文件
<?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接口-->
<mapper namespace="com.lxw.dao.UserDao">
<!--select查询语句
返回结果
resultType类型,返回一个,一般都使用type
resultMap集合,返回多个
-->
<select id="getUserList" resultType="com.lxw.pojo.User">
select * from mybatis.user
</select>
</mapper>
新建一个测试:
注意点:
org.apache.ibatis.binding.BindingException: Type interface com.lxw.dao.UserDao is not known to the MapperRegistry.
MapperRegistry是什么?
org.apache.ibatis.exceptions.PersistenceException:
在target/calsses/com/lxw/dao/里面找不到UserMapper.xml,它不会自动生成
在pom.xml中添加以下代码可解决问题
<!--在build中配置resources,来防止我们资源导出失败的问题 -->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
关于Cause: java.sql.SQLException: The server time zone value 的解决办法
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC"/>
<!--解决办法:在jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC 加上UTC,让数据库时区和本地时区一样就可以。-->
//解决方法:https://blog.csdn.net/qq_24880589/article/details/81735535
加上UTC,让数据库时区和本地时区一样就可以。
com.mysql.jdbc.Driver
. This is deprecated警告处理,jdbc更新处```xml
处理:提示信息表明数据库驱动com.mysql.jdbc.Driver‘已经被弃用了、应当使用新的驱动com.mysql.cj.jdbc.Driver‘
所以,按照提示更改jdbc.properties配置 .com.mysql.jdbc.Driver 改为 com.mysql.cj.jdbc.Driver
原文链接:https://blog.csdn.net/weixin_42323802/article/details/82500458
把src/main/resources/mybatis-config.xml里<property name="driver" value="com.mysql.jdbc.Driver"/>
改成<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
//解决方法:https://blog.csdn.net/weixin_42323802/article/details/82500458
```

Error building SqlSession. ### Cause: org.apache.ibatis.builder.BuilderException(学习MyBatis遇见错误)
Error building SqlSession. ### Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 1 字节的 UTF-8 序列的字节 1 无效。
由于我的项目是Maven构建的,所以在项目依赖配置文件pom.xml上加入构建项目编码属性:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
junit测试
原文:https://www.cnblogs.com/snbg/p/15032531.html