Mybatis封装了JDBC。
详细介绍:https://blog.csdn.net/qq_19387933/article/details/123256034
一.??初始化
首先创建一个maven的Module,然后执行下面步骤:
1. 在pom.xml中添加依赖
<dependencies>
<!-- Mybatis核心 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.8</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version> <!-- 可以与自己电脑的mysql版本一致 -->
</dependency>
</dependencies>
2. 创建MyBatis核心配置文件
?在main目录下的resources目录下创建一个mybatis-config.xml文件
<?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>
<!--设置连接数据库的环境-->
<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/studymybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
3. 创建表
?在studymybatis数据库下创建一个user表
CREATE TABLE `studymybatis`.`user` (
`id` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(20) NULL, UNIQUE,
`password` VARCHAR(20) NULL,
`age` INT NULL,
`sex` CHAR(1) NULL,
`email` VARCHAR(20) NULL,
PRIMARY KEY (`id`),
4. 创建JavaBean对象
在main目录下的java目录下的pojo目录下创建一个User类
package pojo;
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
private Character sex;
private String email;
public User() {
}
public User(Integer id, String username, String password, Integer age, Character sex, String email) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
this.sex = sex;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Character getSex() {
return sex;
}
public void setSex(Character sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", sex=" + sex +
", email='" + email + '\'' +
'}';
}
}
5. 创建Mapper接口
在main目录下的java目录下的mapper目录下创建一个UserMapper接口(Mapper接口相当于DAO),在该接口中编写操作数据库的方法? ? ? ?
package mapper;
import pojo.User;
import java.util.List;
public interface UserMapper {
int insertUser(); //添加用户信息
void updateUser(); //修改用户信息
void deleteUser(); //删除用户信息
User queryUserByName(); //根据用户名查询用户信息
List<User> queryAllUser(); //查询所有用户信息
}
6. 创建Mapper接口的映射文件
映射文件与mapper接口、接口中的方法对应,并在映射文件中编写sql语句。
注:一个表 对应 一个实体类 对应 一个mapper接口 对应 一个映射文件
①在resources目录下创建一个mapper目录(该目录名与存放mapper接口的包名一致,其用于存放每个接口所对应的映射文件)
②在resources目录下的mapper目录下创建一个映射文件:UserMapper.xml(该映射文件的名字与mapper接口同名)
③映射文件里的namespace要和mapper接口的全类名保持一致,这里为:mapper.UserMapper?
④映射文件里的SQL语句的id要和mapper接口中的方法名一致
⑤映射文件里查询功能的返回值类型是数据库表对应的JavaBean对象
<?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="mapper.UserMapper">
<insert id="insertUser">
insert into user values(null,'张三','1234',23,'男','zhang@163.com')
</insert>
<update id="updateUser">
update user set age=22 where username='张三'
</update>
<delete id="deleteUser">
delete from user where username='张三'
</delete>
<!-- 查询必须设置resultType或者resultMap,resultType:设置默认的映射关系,resultMap:设置自定义的映射关系-->
<select id="queryUserByName" resultType="pojo.User">
select * from user where username='张三'
</select>
<select id="queryAllUser" resultType="pojo.User">
select * from user
</select>
</mapper>
7. 在MyBatis核心配置文件引入映射文件
在mybatis-config.xml文件中添加以下内容
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
即mybatis-config.xml文件变为:
<?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>
<!--设置连接数据库的环境-->
<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/studymybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
8. 测试接口中的方法——操作数据库
import mapper.UserMapper;
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 org.junit.Test;
import pojo.User;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest {
@Test
public void testInsert() throws IOException {
//加载核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//获取SqlSession(Java程序和数据库之间的会话),为true表示自动提交事务,默认为false
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//获取Mapper接口对应的对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//操作数据库
mapper.insertUser();
}
@Test
public void testUpdate() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用方法操作数据库
mapper.updateUser();
}
@Test
public void testDelete() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用方法操作数据库
mapper.deleteUser();
}
@Test
public void testQueryByName() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用方法操作数据库
User user = mapper.queryUserByName();
System.out.println(user);
}
@Test
public void testQueryAll() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用方法操作数据库
List<User> list = mapper.queryAllUser();
list.forEach(user -> System.out.println(user));
}
}
二. 对上述配置进行优化
1. 优化核心配置文件
首先在resources目录下创建一个jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/studymybatis
jdbc.username=root
jdbc.password=123456
然后将核心配置文件改为如下
<?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>
<properties resource="jdbc.properties"/>
<!--设置别名,以包为单位设置别名,这样不管该包下有多少个JavaBean,其别名都为其自身的类名-->
<typeAliases>
<package name="pojo"/> <!-- name的值为实体对象类所在的包(全路径,只是这里只有一个目录pojo) -->
</typeAliases>
<!--设置连接数据库的环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<!-- 由于mapper下可以有多个映射文件,且映射文件名与mapper接口名一致,可以直接写包名,一次引入所有映射文件 -->
<mappers>
<package name="mapper"/>
</mappers>
</configuration>
将映射文件修改为
<?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="mapper.UserMapper"> <!--为mapper接口的全类名-->
<insert id="insertUser">
insert into user values(null,'张三','1234',23,'男','zhang@163.com')
</insert>
<update id="updateUser">
update user set age=22 where username='张三'
</update>
<delete id="deleteUser">
delete from user where username='张三'
</delete>
<!-- 查询必须设置resultType或者resultMap,resultType:设置默认的映射关系,resultMap:设置自定义的映射关系-->
<!-- 由于在核心配置文件下设置了别名,这里resultType可以直接写成自身的类名-->
<select id="queryUserByName" resultType="User">
select * from user where username='张三'
</select>
<select id="queryAllUser" resultType="User">
select * from user
</select>
</mapper>
2. 编写工具类
由于操作数据库前都需要先获取SqlSession,所以可以将其编写成一个工具类SqlSessionUtils
package 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 SqlSessionUtils {
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
try {
//加载核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//获取SqlSession(Java程序和数据库之间的会话),为true表示自动提交事务,默认为false
sqlSession = sqlSessionFactory.openSession(true);
} catch (IOException e) {
e.printStackTrace();
}
return sqlSession;
}
}
import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import pojo.User;
import utils.SqlSessionUtils;
import java.util.List;
public class MybatisTest {
@Test
public void testInsert() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
//获取Mapper接口对应的对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//操作数据库
mapper.insertUser();
}
@Test
public void testUpdate() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用方法操作数据库
mapper.updateUser();
}
@Test
public void testDelete() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用方法操作数据库
mapper.deleteUser();
}
@Test
public void testQueryByName() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用方法操作数据库
User user = mapper.queryUserByName();
System.out.println(user);
}
@Test
public void testQueryAll() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用方法操作数据库
List<User> list = mapper.queryAllUser();
list.forEach(user -> System.out.println(user));
}
}
|