一、什么是MyBatis?
MyBatis是一款优秀的 持久层 框架,用于简化JDBC开发。
三层架构:表现层(显示)、业务层(逻辑)、持久层(操作数据库)。
简化JDBC开发:
- 硬编码:注册驱动,获取连接、SQL语句 => 写到配置文件去
- 操作繁琐:手动设置参数、手动封装结果集 => 自动完成
二、MyBatis快速入门
1. 查询user表中所有数据案例,步骤:
1.1 准备user表
1.2 创建模块,导入jar包信息
1.3 编写MyBatis核心配置文件 —> 替换连接信息,解决硬编码问题
1.4 编写SQL映射文件 —> 统一管理SQL语句,解决硬编码问题
1.5 编码
1.5.1 定义POJO类,即实体类
1.5.2 加载核心配置文件,获取SqlSessionFactory对象
1.5.3 获取SqlSession对象,执行SQL
1.5.4 释放资源
2. Maven+Mybatis实操:
(1)Maven依赖管理文件pom.xml
<?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>maven-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!-- junit 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!--添加slf4j日志api-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.20</version>
</dependency>
<!--添加logback-classic依赖-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!--添加logback-core依赖-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
</project>
(2)logback.xml日志配置文件
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- CONSOLE:表示当前的日志信息是可以输出到控制台的。 -->
<appender name="Console" class="ch.gos.logback.core.ConsleAppender">
<encoder>
<pattern>[%level] %blue(%d{HH:mm:ss.SSS})%cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
</encoder>
</appender>
<logger name="com.hung" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
</logger>
</configuration>
(3)user实体类
package com.hung.pojo;
public class User {
private int id;
private String username;
private String password;
private String gender;
private String addr;
public int getId() {
return id;
}
public void setId(int 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 String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", gender='" + gender + '\'' +
", addr='" + addr + '\'' +
'}';
}
}
(4)mybatis核心配置文件
<?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:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载sql映射文件 -->
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
(5)UserMapper映射文件
<?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:命名空间
id:该sql语句的唯一标识
resultType:返回结果类型
-->
<!-- tb_user 报红,可在右侧点击database配置当前项目连接的数据库解决 -->
<mapper namespace="test">
<select id="selectAll" resultType="com.hung.pojo.User">
select * from tb_user;
</select>
</mapper>
(6)MybatisDemo测试类
package com.hung;
import com.hung.pojo.User;
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;
import java.util.List;
/**
* Mybatis 入门
*/
public class MybatisDemo {
public static void main(String[] args) throws IOException {
// 1.加载myBatis核心配置文件,获取SqlSessionFactory (参照官网即可)
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2.获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.执行sql
List<User> users = sqlSession.selectList("test.selectAll");
System.out.println(users);
// 4.释放资源
sqlSession.close();
}
}
三、Mapper代理开发
1. 步骤
- 定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下
- 设置SQL映射文件的namespace属性为Mapper接口全限定名
- 在Mapper接口中定义方法,方法名就是SQL映射文件中sq语句的id,并保持参数类型和返回值类型一致
- 编码
1. 通过SqlSession的getMapper方法获取Mapper接口的代理对象
2. 调用对应方法完成sql的执行
2. Maven+Mybatis+Mapper实操(续二实操)
(1)移动了UserMapper.xml文件,需相应修改mybatis-config.xml配置文件的加载sql映射的配置
<mappers>
<!-- 加载sql映射文件 -->
<!-- <mapper resource="com/hung/mapper/UserMapper.xml"/> -->
<!-- 当接口文件和配置文件符合“同名”同“目录”时,用包扫描方式更方便 -->
</mappers>
(2)修改UserMapper.xml里的命名空间
<?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:命名空间
id:该sql语句的唯一标识
resultType:返回结果类型
-->
<mapper namespace="com.hung.mapper.UserMapper">
<select id="selectAll" resultType="com.hung.pojo.User">
select * from tb_user;
</select>
</mapper>
(3)UserMapper接口文件
package com.hung.mapper;
import com.hung.pojo.User;
import java.util.List;
public interface UserMapper {
// 返回值跟 UserMapper.xml 中定义的相同,这里返回装了多个User的List集合
List<User> selectAll();
}
(3)MybatisDemo2测试类
package com.hung;
import com.hung.mapper.UserMapper;
import com.hung.pojo.User;
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;
import java.util.List;
/**
* Mybatis 入门
*/
public class MybatisDemo2 {
public static void main(String[] args) throws IOException {
// 1.加载myBatis核心配置文件,获取SqlSessionFactory (参照官网即可)
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2.获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.获取UserMapper接口的代理对象对象(变化处)
// List<User> users = sqlSession.selectList("test.selectAll");
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> users = userMapper.selectAll();
System.out.println(users);
// 4.释放资源
sqlSession.close();
}
}
四、MyBatis核心配置文件
参考官网即可
五、案例
使用配置进行增删改查、使用注解进行增删改查、动态SQL:已上传gitee
标签:Mapper,String,配置文件,UserMapper,Maven,org,MyBatis,import,public From: https://www.cnblogs.com/suihung/p/16595884.html