MyBatis介绍
MyBatis历史
Mybatis特性
Mybatis下载
https://github.com/mybatis/mybatis-3/releases
和其他持久化层技术对比
搭建MyBatis
开发环境
创建maven工程
pom.xml 1、打包方式:jar
<groupId>com.bijing.mybatis</groupId>
<artifactId>mybatis_helloworld</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
2、引入依赖
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
创建Mybatis的核心配置文件
resource下的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"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
加入log4j日志功能
加入依赖
pom.xml
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
加入log4j配置文件
resource下的log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM
"http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration debug="true">
<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>
日志的级别
FATAL(致命) > ERROR(错误) > WARN(警告) > INFO(信息) > DEBUG(调试) 从左到右打印的内容越来越详细
创建mapper接口
MyBatis中的mapper接口相当于以前的dao,但是区别在于,mapper仅仅是接口,我们不需要提供实现类
package com.bijing.mapper;
public interface UserMapper {
int insertUser();
}
创建MyBatis的映射文件
UserMapper.xml
<?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.bijing.mapper.UserMapper">
<insert id="insertUser">
insert into t_user values(null,'admin','123456',23,'男','123456@qq.com');
</insert>
</mapper>
通过unit测试功能
测试文件夹下的MyBatisTest.java
import com.bijing.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 java.io.IOException;
import java.io.InputStream;
public class MyBatisTest {
@Test
public void testInsert() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int result = mapper.insertUser();
System.out.println("结果:" + result);
sqlSession.close();
}
}
封装SessionUtil工具类
package com.bijing.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 SqlSessionUtil {
public static SqlSession getSqlSession(String config) {
SqlSession sqlSession = null;
try {
InputStream inputStream = Resources.getResourceAsStream(config);
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
sqlSession = sqlSessionFactory.openSession(true);
} catch (IOException e) {
e.printStackTrace();
}
return sqlSession;
}
public static SqlSession getSqlSession() {
return getSqlSession("mybatis-config.xml");
}
}
测试查询
- resultType:设置结果类型,即查询的数据要转换为的java类型
- esultMap:自定义映射,处理多对一或者一对多的映射关系
<?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接口和映射文件对应
1.mapper接口的全类名和映射文件的namespace一致
2.mapper接口中的方法的方法名要和映射文件中的sql的id保持一致
3.记得在mybatis-config.xml中引入映射文件
-->
<mapper namespace="com.bijing.mapper.UserMapper">
<!-- int insertUser();-->
<!-- 调用UserMapper接口中的insertUser方法时,会根据UserMapper接口的全类名来找到找到映射文件UserMapper.xml,
然后根据当前要调用的方法insertUser的方法名找到UserMapper.xml中的sql语句 然后获取标签中的sql来执行sql-->
<insert id="insertUser">
insert into t_user values(null,'蔡徐坤','123456',31,'女','666@qq.com');
</insert>
<!-- updateUser-->
<update id="updateUser">
update t_user set username ='root',password='123' where id =2;
</update>
<!-- deleteUser-->
<delete id="deleteUser">
delete from t_user where id=2;
</delete>
<!-- User getUserById();-->
<!-- resultType:设置结果类型,即查询的数据要转换为的java类型-->
<!-- resultMap:自定义映射,处理多对一或者一对多的映射关系-->
<select id="getUserById" resultType="com.bijing.pojo.User">
select * from t_user where id=2;
</select>
<!-- List<User> getAllUsers();-->
<select id="getAllUsers" resultType="com.bijing.pojo.User">
select * from t_user;
</select>
</mapper>
import com.bijing.mapper.UserMapper;
import com.bijing.pojo.User;
import com.bijing.utils.SqlSessionUtil;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyBatisTest {
@Test
public void testInsert() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int result = mapper.insertUser();
System.out.println("结果:" + result);
sqlSession.close();
}
@Test
public void testUpdate() {
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int result = mapper.updateUser();
System.out.println("结果:" + result);
sqlSession.close();
}
@Test
public void testDelete() {
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int result = mapper.deleteUser();
System.out.println("结果:" + result);
sqlSession.close();
}
@Test
public void getUserById() {
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById();
System.out.println("结果:" + user);
sqlSession.close();
}
@Test
public void getAllUsers() {
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getAllUsers();
users.forEach(System.out::println);
sqlSession.close();
}
}
MyBatis核心配置文件标签详解和优化
<?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>
<properties resource="jdbc.properties">
</properties>
<typeAliases>
<package name="com.bijing.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>
<mappers>
<package name="com.bijing.mapper"/>
</mappers>
</configuration>
|