4 通用mapper
4.1 概述
-
通用Mapper对MyBatis进行简化的第三方工具包。
-
通用Mapper提供了一个名为 Mapper 的接口,用于自动完成单表的增删改查操作。
public interface UserMapper extends Mapper<User> {
}
- 如果通用Mapper中的方法不足以满足你的需求,直接添加自定义方法即可。
4.2 搭建环境
4.2.1 导入jar
4.2.2 修改工具类
- 添加内容从官方文档中拷贝
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 tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
import tk.mybatis.mapper.entity.Config;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import java.io.InputStream;
public class MyBatisUtils {
// 会话工厂
private static SqlSessionFactory factory;
static{
try {
// 1.1 加载核心配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
// 1.2 获得工厂
factory = new SqlSessionFactoryBuilder().build(is);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static ThreadLocal<SqlSession> local = new ThreadLocal<>();
/**
* 获得新会话
* @return
*/
private static SqlSession openSession(){
SqlSession sqlSession = local.get();
if(sqlSession == null){
sqlSession = factory.openSession();
//创建一个MapperHelper
MapperHelper mapperHelper = new MapperHelper();
//特殊配置
Config config = new Config();
// 设置UUID生成策略
// 配置UUID生成策略需要使用OGNL表达式
// 默认值32位长度:@java.util.UUID@randomUUID().toString().replace("-",
"")
//config.setUUID("");
// 主键自增回写方法,默认值MYSQL,详细说明请看文档
// config.setIDENTITY("HSQLDB");
// 支持方法上的注解
// 3.3.1版本增加
config.setEnableMethodAnnotation(true);
config.setNotEmpty(true);
// 序列的获取规则,使用{num}格式化参数,默认值为{0}.nextval,针对Oracle
// 可选参数一共3个,对应0,1,2,分别为SequenceName,ColumnName,
PropertyName
//config.setSeqFormat("NEXT VALUE FOR {0}");
// 设置全局的catalog,默认为空,如果设置了值,操作表时的sql会是
catalog.tablename
//config.setCatalog("");
// 设置全局的schema,默认为空,如果设置了值,操作表时的sql会是schema.tablename
// 如果同时设置了catalog,优先使用catalog.tablename
//config.setSchema("");
// 主键自增回写方法执行顺序,默认AFTER,可选值为(BEFORE|AFTER)
//config.setOrder("AFTER");
//设置配置
mapperHelper.setConfig(config);
// 注册通用tk.mybatis.mapper.common.Mapper接口 - 可以自动注册继承的接口
mapperHelper.registerMapper(Mapper.class);
mapperHelper.registerMapper(MySqlMapper.class);
// mapperHelper.registerMapper(SqlServerMapper.class);
// mapperHelper.registerMapper(IdsMapper.class);
//配置完成后,执行下面的操作
mapperHelper.processConfiguration(sqlSession.getConfiguration());
local.set(sqlSession);
}
return sqlSession;
}
/**
* 获得mapper
* @param clazz
* @return
8.3 编写Mapper
编写接口,继承tk.mybatis.mapper.common.Mapper接口即可
注意:Mapper接口以==tk==开头
*/
public static <T> T getMapper(Class<T> clazz){
return openSession().getMapper(clazz);
}
/**
* 释放资源
*/
public static void close() {
SqlSession sqlSession = openSession();
if(sqlSession != null){
sqlSession.close();
}
}
/**
* 提交并释放资源
*/
public static void commitAndclose() {
SqlSession sqlSession = openSession();
if(sqlSession != null){
sqlSession.commit();
close();
}
}
/**
* 回滚并释放资源
*/
public static void rollbackAndclose() {
SqlSession sqlSession = openSession();
if(sqlSession != null){
sqlSession.rollback();
close();
}
}
}
4.3 编写Mapper
编写接口,继承tk.mybatis.mapper.common.Mapper接口即可
注意:Mapper接口以**tk**开头
import com.czxy.ssm.domain.User;
import tk.mybatis.mapper.common.Mapper;
public interface UserMapper2 extends Mapper<User> {
}
4.4操作
4.4.1 通过主键查询
1)确定主键,否则所有字段都是主键
2)测试
import com.czxy.ssm.domain.User;
import com.czxy.ssm.mapper.UserMapper;
import com.czxy.ssm.mapper.UserMapper2;
import com.czxy.ssm.utils.MyBatisUtils;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class Test13_Mapper {
@Test
public void testSelectByPrimaryKey() {
UserMapper2 userMapper2 = MyBatisUtils.getMapper(UserMapper2.class);
User user = userMapper2.selectByPrimaryKey("1");
System.out.println(user);
MyBatisUtils.commitAndclose();
}
}
4.4.2查询所有
@Test
public void testSelectAll() {
UserMapper2 userMapper2 = MyBatisUtils.getMapper(UserMapper2.class);
List<User> list = userMapper2.selectAll();
// 打印
list.forEach(System.out::println);
MyBatisUtils.commitAndclose();
}
4.4.3添加
@Test
public void testInsert() {
UserMapper2 userMapper2 = MyBatisUtils.getMapper(UserMapper2.class);
User user = new User();
user.setUid("2");
user.setUsername("jack");
user.setPassword("1234");
user.setName("杰克");
user.setEmail("itcast_lt@163.com");
user.setBirthday(new Date());
user.setSex("男");
user.setSex("0");
int result = userMapper2.insert(user);
// 打印
System.out.println(result);
MyBatisUtils.commitAndclose();
}
4.4.4 修改
@Test
public void testUpdate() {
UserMapper2 userMapper2 = MyBatisUtils.getMapper(UserMapper2.class);
User user = new User();
user.setUid("2");
user.setUsername("jack");
user.setPassword("1234");
user.setName("杰克");
user.setEmail("itcast_lt@163.com");
user.setBirthday(new Date());
user.setSex("男");
user.setSex("0");
int result = userMapper2.updateByPrimaryKey(user);
// 打印
System.out.println(result);
MyBatisUtils.commitAndclose();
}
4.4.5 删除
@Test
public void testDelete() {
UserMapper2 userMapper2 = MyBatisUtils.getMapper(UserMapper2.class);
int result = userMapper2.deleteByPrimaryKey("2");
// 打印
System.out.println(result);
MyBatisUtils.commitAndclose();
}
4.4.6 多条件查询
语法:
// 获得多条件对象
Example example = new Example(对象.class);
Example.Criteria criteria = example.createCriteria();
// 常见条件方法
andLike() //模糊查询
andEqualTo() //等值查询
andLessThanOrEqualTo() //<=查询
andGreaterThanOrEqualTo() //>=查询
andBetween() //区间查询
使用:
@Test
public void testCondition() {
UserMapper2 userMapper2 = MyBatisUtils.getMapper(UserMapper2.class);
Example example = new Example(User.class);
Example.Criteria criteria = example.createCriteria();
criteria.andLike("name", "%王%");
criteria.andEqualTo("sex", "男");
List<User> list = userMapper2.selectByExample(example);
for (User user : list) {
System.out.println(user);
}
MyBatisUtils.commitAndclose();
}