MyBatis
MyBatis历史
- MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。2013年11月迁移到Github。
- iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)
MyBatis特性
- 支持定制化SQL,存储过程及高级映射的优秀持久层框架
- 避免了几乎所有的JDBC代码和手动设置参数以及获取结果集
- 使用简单的XML和注解用于配置和原始映射,将接口和Java的POJO映射到数据库中记录
- 是一个半自动化的ORM(Object Relation Mapping)框架
MyBatis-Maven配置
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
MyBatis的核心配置文件
- 建议名称mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置连接数据库环境 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/> <!-- 使用原始JDBC的方式管理事务,代码提交时需要手动提交-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.29.201:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 引入映射文件 -->
<mappers>
<mapper resource="mappers/UserMapper.xml"/>
</mappers>
</configuration>
<!-- log4j.xml配置文件-- >
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS}
%m (%F:%L) \n"/>
</layout>
</appender>
<logger name="java.sql">
<level value="debug"/>
</logger>
<logger name="org.apache.ibatis">
<level value="info"/>
</logger>
<root>
<level value="debug"/>
<appender-ref ref="STDOUT"/>
</root>
</log4j:configuration>
创建mapper接口
# 创建数据库和表
mysql> create database mybatis;
Query OK, 1 row affected (0.00 sec)
mysql> use mybatis;
Database changed
mysql> create table t_user(id int primary key auto_increment,username varchar(20),password varchar(20),age int,sex char,email varchar(20));
Query OK, 0 rows affected (0.01 sec)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lotus.mybatis.mapper.UserMapper">
<!--int insertUser();-->
<insert id="insertUser">
insert into t_user values(null,'edison','123456',23,'男','edison@qq.com')
</insert>
<!--int updateUser();-->
<update id="updateUser">
update t_user set username = 'dizzy' where id = 3
</update>
<!--int deleteUser();-->
<delete id="deleteUser">
delete from t_user where id = 3
</delete>
<!-- getUserById -->
<!--
查询功能标签必须设置resultType或resultMap
resultType:设置默认的映射关系
resultMap:设置自定义的映射关系
-->
<select id="getUserById" resultType="com.lotus.mybatis.pojo.User">
select * from t_user where id = 4
</select>
<!-- List<User> getAllUser(); -->
<select id="getAllUser" resultType="com.lotus.mybatis.pojo.User">
select * from t_user
</select>
</mapper>
package com.lotus.mybatis.mapper;
/**
* MyBatis面向接口编程的两个一致
* ①映射文件的namespace要和Mapper接口全类名一致
* ②映射文件中SQL语句的id要和mapper中的方法名一致
*/
public interface UserMapper {
/**
* 添加用户信息
*/
int insertUser();
/**
* 删除用户
*/
int deleteUser();
/**
* 修改用户
*/
int updateUser();
/**
* 查询数据
*/
User getUserById();
/**
* 查询所有用户信息
*/
List<User> getAllUser();
}
package com.lotus.mybatis.pojo;
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
private String sex;
private String email;
public User() {
}
public User(Integer id, String username, String password, Integer age, String 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 String getSex() {
return sex;
}
public void setSex(String 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 + '\'' +
'}';
}
}
创建MyBatis映射文件
-
ORM对象映射关系
- 对象:Java实体类对象
- 关系:关系型数据库
- 映射:二者之间的对应关系
-
映射文件命名规则
- 表所对应的实体类名+Mapper.xml-----如表t_user,映射的实体类为User,
-
MyBatis可以面向接口操作数据,要保证两个一致
-
SqlSession:代表Java程序和数据库之前的会话
-
SqlSessionFactory:生产SqlSession的工厂
-
工厂模式:创建某一个对象,使用的过程基本固定,那么我们就可以创建这个对象的相关代码封装到一个“工厂类”中,以后使用这个工厂类生产我们需要的对象
//SqlSession默认不自动提交事务,需要自动提交事务,使用openSession(true)自动提交事务
public class MyBatisTest {
@Test
public void testMyBatis() throws IOException {
//加载核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//SqlSessionFactory
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取Mapper接口对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//测试功能
int res = mapper.insertUser();
//提交事务
sqlSession.commit();
System.out.println(res);
}
@Test
public void testCRUD() throws IOException {
//加载核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//SqlSessionFactory
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//获取Mapper接口对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//int res = mapper.updateUser();
//int res = mapper.deleteUser();
/*User user = mapper.getUserById();
System.out.println(user);*/
//System.out.println(res);
List<User> users = mapper.getAllUser();
users.forEach(user-> System.out.println(user));
}
}