Слияние кода завершено, страница обновится автоматически
一个简单的Mybatis通用接口插件,无需编写也不会生成Dao实现类,继承BaseDao即可拥有对单表的CURD方法
pom.xml 添加依赖
需先将工程install到本地仓库。将项目下载到本地,解压后执行mvn install
<dependency>
<groupId>com.cml</groupId>
<artifactId>batisext</artifactId>
<version>1.1</version>
</dependency>
@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
@GenerateDao(beanType = Student.class)
public interface StudentDao extends BaseDao<Student>{
}
@Autowired
private StudentDao studentDao;
Student s = studentDao.selectById(1L);
<?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
@GenerateDao(beanType = Student.class)
public interface StudentDao extends BaseDao<Student>{
public String myOwnSql();
}
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
# dataSource 配置已省略
mybatis:
mapperLocations: classpath*:mapper/*.xml
typeAliasesPackage: com.your.dto
//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);
}
}
@Transactional(rollbackFor = Exception.class)
pom.xml 添加依赖 同上
application.yml 配置无需再配置mybatis项 删除此配置,该配置将通过Config Bean
# dataSource 配置已省略
mybatis:
mapperLocations: classpath*:mapper/*.xml
typeAliasesPackage: com.your.dto
@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);
}
}
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Комментарии ( 0 )