Mybatis简介
1.什么是 MyBatis?
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
2.安装Mybatis
要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于类路径(classpath)中即可。
如果使用 Maven 来构建项目,则需将下面的依赖代码置于 pom.xml 文件中:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
3.Mybatis第一个应用程序
搭建数据库环境
1.创建数据库表
CREATE DATABASE `mybatis`;
USE `mybatis`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(20) NOT NULL,
`username` varchar(30) DEFAULT NULL,
`password` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `user`(`id`,`name`,`pwd`) values (1,'王五','123456'),(2,'张三','abcdef'),(3,'李四','987654');
导入其它需要的包
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--数据库连接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--日志文件
https://mvnrepository.com/artifact/log4j/log4j
-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
编写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>
<!--引入外部配置文件-->
<properties resource="JDBC.properties"/>
<!--开启日志-->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<!--<typeAliases>
可以给实例类起别名
<typeAlias type="com.Gby.User.Stu" alias="user"></typeAlias>
给实体类包名起别名,默认别名为这个类的类名,首字母小写
<package name="com.Gby.User"/>
</typeAliases>-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--使用class和扫描包注入绑定-->
<!--
1.接口和他的Mapper配置文件必须同名
2.接口和他的Mapper配置文件必须在同一个包下
-->
<mapper resource="StuMapper.xml"/>
</mappers>
</configuration>
外部配置文件
username = root
password = gby20010704..
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/kuang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
编写Mybatis工具类
在实际开发中,我们为了简化代码,提高代码的可复用性,我们将其获取sqlSession对象的方法封装成一个类,在使用时调用即可。
package com.Gby.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;
public class mybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try{
//使用mybatis第一步:获取sqlSessionFactory对象
String 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(){
return sqlSessionFactory.openSession(true);
}
}
创建实体类
package com.Gby.User;
public class Stu {
private Integer id;
private String username;
private String password;
//生成我们所需要的get set方法
public Stu() {
}
public Stu(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
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;
}
@Override
public String toString() {
return "Stu{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
编写Mapper接口类
package com.Gby.Dao;
import com.Gby.User.Stu;
import java.util.List;
import java.util.Map;
public interface StuMapper {
//查看全部用户
List<Stu> getStuList();
//根据id查询用户
Stu getStuById(int id);
//插入用户
int getInsert(Stu stu);
//修改用户
int UpdateUser(Stu stu);
//删除用户
int deleteStu(int id);
//插入用户(map方法)
int getInsert2(Map<String,Object> map);
//模糊查询
List<Stu> getStuLike(String value);
}
编写Mapper.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=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.Gby.Dao.StuMapper">
<!--
id-就是对应的namespace中的方法名
resultType-Sql语句执行的返回值类型
ParameterType-参数类型
-->
<select id="getStuList" resultType="com.Gby.User.Stu">
select * from student
</select>
<select id="getStuById" resultType="com.Gby.User.Stu">
select * from student where id = #{id}
</select>
<insert id="getInsert" >
insert into student(id,username,password) values(#{id},#{username},#{password})
</insert>
<update id="UpdateUser">
update student set username=#{username},password=#{password}where id=#{id}
</update>
<delete id="deleteStu" parameterType="int">
delete from student where id = #{id};
</delete>
<insert id="getInsert2" parameterType="map">
insert into student(id,username,password) values(#{first},#{two},#{three})
</insert>
<select id="getStuLike" resultType="com.Gby.User.Stu">
select * from student where username like #{value}
</select>
</mapper>
进行测试
package com.Gby.StuDao;
import com.Gby.Dao.StuMapper;
import com.Gby.User.Stu;
import com.Gby.Utils.mybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StuMapperTest {
/**
* 查询所有用户
*/
@Test
public void test(){
//第一步获取SqlSession对象
SqlSession sqlSession = mybatisUtils.getSqlSession();
//执行sql
StuMapper mapper = sqlSession.getMapper(StuMapper.class);
List<Stu> stuList = mapper.getStuList();
stuList.forEach(System.out::println);
sqlSession.close();
}
/**
* 根据用户id查询
*/
@Test
public void getStuByIdTest(){
//第一步获取SqlSession对象
SqlSession sqlSession = mybatisUtils.getSqlSession();
//执行sql
StuMapper mapper = sqlSession.getMapper(StuMapper.class);
Stu stuById = mapper.getStuById(2);
System.out.println(stuById);
sqlSession.close();
}
/**
* 插入数据
*/
@Test
public void getInsert(){
//第一步获取SqlSession对象
SqlSession sqlSession = mybatisUtils.getSqlSession();
//执行sql
StuMapper mapper = sqlSession.getMapper(StuMapper.class);
int res = mapper.getInsert(new Stu(null,"张三","123456"));
if(res>0){
System.out.println("插入成功");
}else {
System.out.println("插入失败");
}
sqlSession.close();
}
/**
* 修改数据
*/
@Test
public void UpdateUserTest(){
//第一步获取SqlSession对象
SqlSession sqlSession = mybatisUtils.getSqlSession();
//执行sql
StuMapper mapper = sqlSession.getMapper(StuMapper.class);
mapper.UpdateUser(new Stu(4, "哈哈", "789456"));
sqlSession.close();
}
/**
* 删除用户
*/
@Test
public void deleteStuTest(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
StuMapper mapper = sqlSession.getMapper(StuMapper.class);
mapper.deleteStu(5);
sqlSession.close();
}
/**
* 插入用户(map方法)
*/
@Test
public void getInsert2Test(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
StuMapper mapper = sqlSession.getMapper(StuMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("first",null);
map.put("two","lin");
map.put("three","123456");
mapper.getInsert2(map);
sqlSession.close();
}
/**
* 模糊查询
*/
@Test
public void getStuLikeTest(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
StuMapper mapper = sqlSession.getMapper(StuMapper.class);
List<Stu> stuLike = mapper.getStuLike("%li%");
stuLike.forEach(System.out::println);
sqlSession.close();
}
}
因为Maven的特性是:“约定大于配置”,所以可能出现问题:Maven静态资源过滤问题。我们需要在pom.xml配置文件中添加如下内容
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
官方文档
Mybatis官方文档 : http://www.mybatis.org/mybatis-3/zh/index.html
GitHub : https://github.com/mybatis/mybatis-3
希望可以帮到初学者,请勿白嫖。