1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/sd3560531-batisext

Присоединиться к Gitlife
Откройте для себя и примите участие в публичных проектах с открытым исходным кодом с участием более 10 миллионов разработчиков. Приватные репозитории также полностью бесплатны :)
Присоединиться бесплатно
Клонировать/Скачать
README.md 5.8 КБ
Копировать Редактировать Web IDE Исходные данные Просмотреть построчно История
AndyTao Отправлено 21.09.2017 19:20 94db6c4

BatisExt

一个简单的Mybatis通用接口插件,无需编写也不会生成Dao实现类,继承BaseDao即可拥有对单表的CURD方法

  • 基于Spring Boot
  • 利用Spring Boot的EnableAutoConfiguration功能,没有任何侵入式代码和配置,只需引入依赖包
  • 支持Mybatis Spring Boot Starter
  • 支持乐观锁校验
  • 灵活的查询方式

实现原理

  • 利用了Mybatis3新特性@SelectProvider等一系列@xxxxxProvider注解。这些注解标注在Mapper方法上,用于指定根据参数生成sql语句的类(SqlProvider)。
  • 唯一的问题就是,在SqlProvider类中,无法获取拼接sql所需要的表结构信息。
  • 因此,利用了mybatis的拦截器,在执行所有通用接口方法(selectById等方法)之前,将表信息(也就是实体类)设置到一个ThreadLocal变量中,在SqlProvider中就可以获取到了。

项目地址

引入BatisExt

  • pom.xml 添加依赖

    需先将工程install到本地仓库。将项目下载到本地,解压后执行mvn install

<dependency>
    <groupId>com.cml</groupId>
    <artifactId>batisext</artifactId>
    <version>1.1</version>
</dependency>

使用BatisExt

  • 创建与数据库表对应的实体
@DbTable(table = "Student")
public class Student extends DatabaseBean{
	private static final long serialVersionUID = 1L;
	
	@DbField
	public String name;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
  • 创建Mapper
    继承BaseDao并指定泛型后,即可使用对应泛型类型的CURD操作
@Mapper
@GenerateDao(beanType = Student.class)
public interface StudentDao extends BaseDao<Student>{
}
  • 注入和使用
@Autowired
private StudentDao studentDao;
Student s = studentDao.selectById(1L);

添加自定义SQL(与正常使用Mybatis一致)

  • 添加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" >
<mapper namespace="com.your.dao.StudentDao" >
	<select id="myOwnSql"  resultType="string" >
		select '!!!!!!hello to CML Mybatis Exts world!!!!!!'
	</select>
</mapper>
  • 在Mapper中添加方法
@Mapper
@GenerateDao(beanType = Student.class)
public interface StudentDao extends BaseDao<Student>{
	public String myOwnSql();
}

BatisExt正常使用的前提是Spring boot Mybatis正确配置,下面将Spring boot Mybatis的配置列出,以便新司机参考

通过mybatis-spring-boot-starter 配置Mybatis

  • pom.xml 添加依赖
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
  • application.yml 配置
# dataSource 配置已省略
mybatis:
    mapperLocations: classpath*:mapper/*.xml
    typeAliasesPackage: com.your.dto
  • Spring Boot 启动类
//SpringBoot会默认扫描启动类所在包及其子孙包下的组件,如果你的Mapper和Spring其他组件不在启动类包及其子孙包下,需要指定这两个注解
@MapperScan(basePackages={"com.your.dao"})
@SpringBootApplication(scanBasePackages={"com.your.component"})
public class Main extends SpringBootServletInitializer {
    public static void main(String[] args) throws IOException {
        SpringApplication.run(Main.class, args);
    }
}
  • 事务 mybatis-spring-boot-starter已经自动配置好事务管理器,在需要事务的方法上添加注解:
@Transactional(rollbackFor = Exception.class)

不通过Mybatis starter

  • pom.xml 添加依赖 同上

  • application.yml 配置无需再配置mybatis项 删除此配置,该配置将通过Config Bean

# dataSource 配置已省略
mybatis:
    mapperLocations: classpath*:mapper/*.xml
    typeAliasesPackage: com.your.dto
  • 添加Spring boot 配置 Bean
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages={"com.your.dao","com.cml.batisext.demo"})
public class MyBatisConfig implements TransactionManagementConfigurer{

	@Autowired
	DataSource dataSource;

	@Bean
	public SqlSessionFactory sqlSessionFactory() throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		//com.cml.batisext.core.bean是为了把Demo用到的几个类扫描进去,实际使用时可以不指定
		bean.setTypeAliasesPackage("com.your.entry,com.cml.batisext.core.bean");
		//设置BatisExt拦截器,实现通CURD接口
		bean.setPlugins(new Interceptor[]{new BaseDaoInterceptor()});

		try {
			ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			Resource[]  rs1 = resolver.getResources("classpath:mapper/*.xml");
			//把Demo用到的几个xml扫描进去,实际使用时可以不指定
			Resource[]  rs2 = resolver.getResources("classpath:demo/mapper/*.xml");
			Resource[] rs = new Resource[rs1.length+rs2.length];
			int index = 0;
			for(int i = 0 ; i < rs1.length ; i ++){
				rs[index ++] = rs1[i];
			}
			for(int i = 0 ; i < rs2.length ; i ++){
				rs[index ++] = rs2[i];
			}
			bean.setMapperLocations(rs);
			return bean.getObject();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("创建mybatis sessionFactory失败");
		}
	}

	@Bean
	public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory){
		return new SqlSessionTemplate(sqlSessionFactory);
	}

	@Bean
	@Override
	public PlatformTransactionManager annotationDrivenTransactionManager() {

		return new DataSourceTransactionManager(dataSource);
	}
}
  • 其他内容与使用Starter的方式一致

Опубликовать ( 0 )

Вы можете оставить комментарий после Вход в систему

1
https://api.gitlife.ru/oschina-mirror/sd3560531-batisext.git
git@api.gitlife.ru:oschina-mirror/sd3560531-batisext.git
oschina-mirror
sd3560531-batisext
sd3560531-batisext
master