Mybatis开发流程:
- 引入依赖
- 创建配置文件
- 创建实体类entity
- 创建mapper映射类文件
- 初始化SessionFactory
- 利用SQLSession对象操作数据
- 注解开发方式
1.引入依赖
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
2.创建配置文件
随便起个名字, 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>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="mysql"/>
<property name="reasonable" value="true"/>
</plugin>
</plugins>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"></transactionManager>
<!-- <dataSource type="pooled">-->
<!-- <property name="driver" value="com.mysql.cj.jdbc.Driver"/>-->
<!-- <property name="url" value="jdbc:mysql://localhost:3306/babytun?-->
<!--useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"/>-->
<!-- <property name="username" value="root"/>-->
<!-- <property name="password" value="root"/>-->
<!-- </dataSource>-->
<dataSource type="com.imooc.mybatis.C3P0DataSourceFactory">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/babytun?
useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
<property name="initialPoolSize" value="5"/>
<property name="maxPoolSize" value="20"/>
<property name="minPoolSize" value="5"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/GoodsMapper.xml"/>
<mapper resource="mapper/GoodsDetailMapper.xml"/>
</mappers>
<!-- <mappers>-->
<!-- <mapper class="com.imooc.mybatis.dao.GoodsMapper"/>-->
<!-- <package name="com.imooc.mybatis.dao"/>-->
<!-- </mappers>-->
</configuration>
上面的mapper标签,是配置SQL语句文件源在resource目录下的mapper/GoodsMapper.xml以及mapper/GoodsDetailMapper.xml
被注释的内容,是"启用注解开发方式"
3.创建实体类entity
在此之前需要建立一个简单的SQLSession工具类
package com.imooc.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.Reader;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
Reader resourceAsReader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsReader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSession openSession() {
return sqlSessionFactory.openSession();
}
public static void closeSession(SqlSession session) {
if (session != null) {
session.close();
}
}
}
- 建立实体类
- 创建XML文件
- 编写SQL语句
- 开启驼峰命名映射
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
- 新建<mapper.xml>
- SqlSession执行
4.创建mapper映射类文件
<?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="com.imooc.mybatis.dao.GoodsMapper">
<cache eviction="LRU" flushInterval="600000" size="512" readOnly="true">
</cache>
上面是设置命名空间,命名空间在使用SQLsession对象时,需要用到
其次是mybatis二级缓存的设置,所用算法为LRU,容量是512个对象,刷新时间是600000毫秒,也就是600秒,10分钟
5.初始化SessionFactory
package com.imooc.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.Reader;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
Reader resourceAsReader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsReader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSession openSession() {
return sqlSessionFactory.openSession();
}
public static void closeSession(SqlSession session) {
if (session != null) {
session.close();
}
}
}
这里建立一个简单的工具类,用于新建一个session对象,或者关闭它
6.利用SQLSession对象操作数据
@Test
public void test2() {
SqlSession session = null;
session = MybatisUtils.openSession();
List<Goods> objects = session.selectList("com.imooc.mybatis.dao.GoodsMapper.selectAll");
for (Goods object : objects) {
System.out.println(object);
}
}
上面的java代码,是调用了mapper.XML里面的名为selectAll的SQL语句
<select id="selectAll" resultType="com.imooc.mybatis.entity.Goods" useCache="false">
select *
from t_goods
order by goods_id desc
limit 10
</select>
7.注解开发方式
将XML配置文件里的mapper标签替换成如下
<mappers>
<mapper class="com.imooc.mybatis.dao.GoodsMapper"/>
<package name="com.imooc.mybatis.dao"/>
</mappers>
以如此的方法让mybatis知道interface接口的位置
以上方法二选一,要么是覆盖包,要么是指明单个类,使用时注释掉其中一行
package com.imooc.mybatis.dao;
import com.imooc.mybatis.dto.GoodsDTO;
import com.imooc.mybatis.entity.Goods;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface GoodsDAO {
@Select("select * from t_goods where current_price between #{min} and #{max} order by current_price limit 0,#{limt}")
public List<Goods> selectByPriceRange(@Param("min") Float min ,@Param("max") Float max ,@Param("limt") Integer limt);
@Insert("INSERT INTO t_goods(title, sub_title, original_cost, current_price, discount, is_free_delivery, category_id) VALUES (#{title} , #{subTitle} , #{originalCost}, #{currentPrice}, #{discount}, #{isFreeDelivery}, #{categoryId})")
//<selectKey>
@SelectKey(statement = "select last_insert_id()" , before = false , keyProperty = "goodsId" , resultType = Integer.class)
public int insert(Goods goods);
@Select("select * from t_goods")
//<resultMap>
@Results({
//<id>
@Result(column = "goods_id" ,property = "goodsId" , id = true) ,
//<result>
@Result(column = "title" ,property = "title"),
@Result(column = "current_price" ,property = "currentPrice")
})
public List<GoodsDTO> selectAll();
}
然后再以如下的方式调用
package com.imooc.mybatis;
import com.imooc.mybatis.dao.GoodsDAO;
import com.imooc.mybatis.dto.GoodsDTO;
import com.imooc.mybatis.entity.Goods;
import com.imooc.mybatis.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
//JUNIT单元测试类
public class MyBatisTestor {
@Test
public void testSelectByPriceRange() throws Exception {
SqlSession session = null;
try{
session = MyBatisUtils.openSession();
GoodsDAO goodsDAO = session.getMapper(GoodsDAO.class);
List<Goods> list = goodsDAO.selectByPriceRange(100f, 500f, 20);
System.out.println(list.size());
}catch (Exception e){
throw e;
} finally {
MyBatisUtils.closeSession(session);
}
}
/**
* 新增数据
* @throws Exception
*/
@Test
public void testInsert() throws Exception {
SqlSession session = null;
try{
session = MyBatisUtils.openSession();
Goods goods = new Goods();
goods.setTitle("测试商品");
goods.setSubTitle("测试子标题");
goods.setOriginalCost(200f);
goods.setCurrentPrice(100f);
goods.setDiscount(0.5f);
goods.setIsFreeDelivery(1);
goods.setCategoryId(43);
GoodsDAO goodsDAO = session.getMapper(GoodsDAO.class);
//insert()方法返回值代表本次成功插入的记录总数
int num = goodsDAO.insert(goods);
session.commit();//提交事务数据
System.out.println(goods.getGoodsId());
}catch (Exception e){
if(session != null){
session.rollback();//回滚事务
}
throw e;
}finally {
MyBatisUtils.closeSession(session);
}
}
@Test
public void testSelectAll() throws Exception {
SqlSession session = null;
try{
session = MyBatisUtils.openSession();
GoodsDAO goodsDAO = session.getMapper(GoodsDAO.class);
List<GoodsDTO> list = goodsDAO.selectAll();
System.out.println(list.size());
}catch (Exception e){
throw e;
} finally {
MyBatisUtils.closeSession(session);
}
}
}
这里再附上GoodsDTO与Goods类的基本内容
public class GoodsDTO {
private Integer goodsId;//商品编号
private String title;//标题
private Float currentPrice;//当前价格
public class Goods {
private Integer goodsId;//商品编号
private String title;//标题
private String subTitle;//子标题
private Float originalCost;//原始价格
private Float currentPrice;//当前价格
private Float discount;//折扣率
private Integer isFreeDelivery;//是否包邮 ,1-包邮 0-不包邮
private Integer categoryId;//分类编号