已经有很多很多的数据访问层了,每种或多或少都有自己的特点。
由于个人习惯,对这个功能有以下要求:
1.必须能写原生SQL
对于那种能生成sql的库不是很喜欢,尤其是比较复杂的sql,每次还要打印出sql检查一下生成的对不对。
另外最好不要像mybatis那种要把sql写在xml文件里,看起来太乱。
2.对于单表简单的CRUD,可以自动生成sql
也就是说我可以不写sql的情况下,可以自动生成sql,毕竟为了简单更新一个表,还要写更新sql也是很繁琐的。
3.必须要有orm功能
没人喜欢把抽出的数据,手动转换为entity,这个必须能够自动转换,要支持隐式匹配。
根据这些要求,最终选定了doma2。
但是doma2并没有完全符合上面的要求,比如select的话,是无法自动生成sql的,如果需要的话还要自己扩展。
另外doma2也不支持1:n的entity mapping,作者的解释是那样反而会增加使用难度。
doma2,还有一个比较特殊的地方,是使用了注释处理,就是在编译期会自动生成实现类的源程序,并且貌似orm也没有用到反射机制,效率更高一些。缺点当然是会影响一些编译速度,另外会生成大量的源代码。
和mybatis一样,doma2也提供了最基本的entity和dao文件的生成工具doma-gen。
doma2可以用在任何框架里,当然spring boot也不例外,另外已经有人写了starter库,集成起来更加的方便。
下面这个配置是一个集成doma2基本spring boot的gradle文件
buildscript {
ext {
springBootVersion = '1.5.1.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
jar {
baseName = 'test'
version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
configurations {
domaGenRuntime
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-jdbc')
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
compile('org.springframework.boot:spring-boot-starter-validation')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.seasar.doma.boot:doma-spring-boot-starter:1.1.0')
runtime('org.springframework.boot:spring-boot-devtools')
runtime('mysql:mysql-connector-java')
testCompile('org.springframework.boot:spring-boot-starter-test')
domaGenRuntime 'org.seasar.doma:doma-gen:2.15.0'
domaGenRuntime 'mysql:mysql-connector-java:5.1.39'
}
task gen << {
ant.taskdef(resource: 'domagentask.properties',
classpath: configurations.domaGenRuntime.asPath)
ant.gen(url: 'jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=UTF-8&useSSL=false',
user: 'username', password: 'password',
templatePrimaryDir: 'templates') {
entityConfig(packageName: 'jp.co.abc.entity',entitySuffix:'Entity',useListener: false)
daoConfig(packageName: 'jp.co.abc.dao', overwrite:true)
sqlConfig()
}
}
由于doma-gen没有考虑spring的集成,为了能让生成的dao文件会被spring boot扫描,需要添加注解@ConfigAutowireable,可以在doma的库里复制一个默认的dao.ftl文件,放到相应的目录下,例如上面的配置是放到了项目根目录下的templates目录下
然后在相应处添加下面两行
import org.seasar.doma.boot.ConfigAutowireable;
@ConfigAutowireable
当然,如果你不想对自动生成的java类进行侵入式注解,可以自定义一个配置类,用正则方式,扫描生成的类。
@Component
@ComponentScan(basePackages="jp.co.abc.dao", includeFilters=@Filter(type=FilterType.REGEX,pattern = "jp.co.abc.dao.*DaoImpl"))
public class DomaConfig {
}