介绍一个开源的jdbc操作工具类fastjdbc,一个基于SpringBoot框架开发的jdbc疾速开发工具包
它实际上是对spring框架提供的NamedJdbcTemplate类的二次封装,提供一种基于注解形式的API配置形式去操作sql,而不是调用NamedJdbcTemplate的办法去传递sql语句。
装置
<dependency> <groupId>com.github.paganini2008.springdessert</groupId> <artifactId>fastjdbc-spring-boot-starter</artifactId> <version>2.0.3</version> </dependency>
(以最新版为准)
疾速开始
上面举几个例子,看看fastjdbc-spring-boot-starter是怎么应用的
@Daopublic interface UserDao { @Insert("insert into tb_user(username,password,age) values (:username,:password,:age)") int saveUser(@Example User user); @Update("update tb_user set username=:username, password=:password where id=:id") int updateUser(@Example User user); @Update("delete from tb_user where id=:id") int deleteUser(@Arg("id") int id); @Batch("insert into tb_user(username,password,age) values (:username,:password,:age)") int batchSaveUser(@Args List<User> userList); @Get("select * from tb_user where id=:id") User getById(@Arg int id); @Query("select * from tb_user order by create_time desc") List<Map<String, Object>> queryUser(); @Query("select * from tb_user where 1=1 @sql order by create_time desc") List<Map<String, Object>> queryUserByCondition(@Sql String whereCondition, @Example Map<String,Object> queryExample); @Select("select * from tb_user order by create_time desc") ResultSetSlice<User> selectUser();}
API很简略,但须要的注意事项:
- @Insert 返回的是主键ID, 能够是int或long类型的
- @Update 返回的是受影响的行数,它能够执行insert, update, delete 语句
- @Batch 返回的也是受影响的行数
- @Get 能够返回对象也能够返回单个值(包装类型或根底类型),设置属性javaType=true即可
- @Example 参数能够是Pojo对象也能够是Map, @Arg示意一个参数,@Args示意多个参数,用于批处理
- @Query 返回列表,其中@Sql示意是动静sql, 比方你能够依据查问条件动静拼装sql
- @Query和@Select很像,@Query,是不分页的,@Select既反对分页,又反对列表,返回ResultSetSlice对象,这个对象异样弱小,有趣味的敌人能够钻研一下
- sql语句的写法和Spring框架中NamedParameterJdbcTemplate的写法统一,本质上还是通过它来执行sql语句的
(API具体用法能够参考源码)
最初,在你Spring Boot利用中,在你本人的Configuration类上中退出Dao扫描器即可,比方:
@DaoScan(basePackages = "com.yourcompany.project.base.dao")@Configuration(proxyBeanMethods = false)public class YourConfiguration {}
git地址:https://github.com/paganini20...