官方文档传送:ActiveRecord 概述
<!--实现jfinal activerecord-->
<dependency>
<groupId>com.jfinal</groupId>
<artifactId>activerecord</artifactId>
<version>4.9.06</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.4</version>
</dependency>
/**
* 集成 JFinal 的 ActiveRecordPlugin 实现轻量级db操作
*/
@Configuration
class JActiveRecordConfig {
private val logger = LoggerFactory.getLogger(JActiveRecordConfig::class.java)
@Value(“\${spring.datasource.business.jdbc-url}”)
private lateinit var jdbcUrl: String
@Value(“\${spring.datasource.business.username}”)
private lateinit var username: String
@Value(“\${spring.datasource.business.password}”)
private lateinit var password: String
@Value(“\${spring.datasource.business.driver-class-name}”)
private lateinit var driverClassName: String
@Bean
fun initActiveRecordPlugin(): ActiveRecordPlugin {
// 配置druid数据库连接池插件
val druidPlugin = DruidPlugin(jdbcUrl, username, password, driverClassName)
// 加强数据库安全
val wallFilter = WallFilter()
wallFilter.dbType = “mysql”
druidPlugin.addFilter(wallFilter)
druidPlugin.start()
// 配置ActiveRecord插件
val arp = ActiveRecordPlugin(druidPlugin)
arp.setTransactionLevel(Connection.TRANSACTION_READ_COMMITTED)
arp.setShowSql(true)
arp.devMode = true
// 所有映射在 MappingKit 中自动化搞定
_MappingKit.mapping(arp)
// 与 jfinal web 环境唯一的不同是要手动调用一次相关插件的start()方法
arp.start()
logger.info(“**** JFinal Active Record Init complete! ****”)
return arp
}
}
class _MappingKit {
companion object{
fun mapping(arp: ActiveRecordPlugin) {
arp.addMapping(JHolder.TABLE_NAME, JHolder::class.java)
}
}
}
class JHolder : Model<JHolder>() {
companion object {
const val TABLE_NAME = “base_holder”
val dao = JHolder().dao()
}
}
至此,集成已经完成,可以直接在项目中使用了!
// 创建name属性为James,age属性为25的User对象并添加到数据库
new User().set(“name”, “James”).set(“age”, 25).save();
// 删除id值为25的User
User.dao.deleteById(25);
// 查询id值为25的User将其name属性改为James并更新到数据库
User.dao.findById(25).set(“name”, “James”).update();
// 查询id值为25的user, 且仅仅取name与age两个字段的值
User user = User.dao.findByIdLoadColumns(25, “name, age”);
// 获取user的name属性
String userName = user.getStr(“name”);
// 获取user的age属性
Integer userAge = user.getInt(“age”);
// 查询所有年龄大于18岁的user
List<User> users = User.dao.find(“select * from user where age>18”);
// 分页查询年龄大于18的user,当前页号为1,每页10个user
Page<User> userPage = User.dao.paginate(1, 10, “select *”, “from user where age > ?”, 18);