ORM选择ebean,当然也有很多其它ORM框架可选,这里不谈,看个人,团队的环境需求。

        

        model:

        这个模型的表关系有一对多,多对一

@Table(name = "Test")

class AppModel (
    @Id var id: Long? = null,
    @Column(name = "name", length = 100, nullable = false, unique = true)
    var name: String,    @Column(name = "status", nullable = true)
    var status: Test.Status,
    @CreatedTimestamp
    @Column(name = "createTime", nullable = true)
    var createTime: Long = System.currentTimeMillis(),
    @UpdatedTimestamp
    @Column(name = "updateTime", nullable = true)
    var updateTime: Long = System.currentTimeMillis(),
    @OneToMany(cascade= arrayOf(CascadeType.ALL), mappedBy = "r")
    val appR: MutableSet<RModel> = mutableSetOf(),
    @OneToMany(cascade = arrayOf(CascadeType.ALL), mappedBy = "a")
    var appW: MutableSet<WModel> = mutableSetOf()

    

        ebean学习http://ebean-orm.github.io/

 

         数据库配置:

         ebean.dev.properties

ebean.autotune.querytuning=false
ebean.autotune.profiling=true
ebean.autotune.profilingUpdateFrequency=5
ebean.ddl.generate=true
ebean.ddl.run=true
datasource.username=root
datasource.password=123456datasource.databaseUrl=jdbc:mysql://127.0.0.1:3306/test?useUnicode=yes&characterEncoding=utf8&useSSL=false
datasource.databaseDriver=com.mysql.jdbc.Driver

         

       这里的数据库配置有点特别,ebean.dev.properites,中间为什么有个dev,这主要是为了上线动态替换配置。如果有了配置管理系统,如Disconf,不用这么写了。怎样动态替换呢?

class EbeanServerProvider : Provider<EbeanServer> {

override fun get(): EbeanServer {
        val config = ServerConfig()
        val profile = System.getProperty("profile") ?: "dev"
val props = Properties()
        props.load(javaClass.getResourceAsStream("/ebean.$profile.properties"))
        config.loadFromProperties(props)
        config.name = "default"
config.isDefaultServer = true
config.isRegister = true
        return EbeanServerFactory.create(config)
    }
}

        启动应用时,动态把标签加载进JVM

        

        怎样动态写入JVM呢?

        在启动脚本里加入这段

        classpath: JAVA_OPTS="-Dprofile=testing"

 

       初始化数据库

       

companion object {

@JvmStatic fun main(args: Array<String>) {
        val logger = LoggerFactory.getLogger(Application::class.java)!!
        if (!AgentLoader.loadAgentFromClasspath("ebean-agent","debug=1;packages=com.ymatou.op.app.server.domain")) {
            logger.error("ebean-agent not found in classpath - not dynamically loaded")
            System.exit(1)
        }
        val application = Application()
        application.start()
        application.blockUntilShutdown()
    }
}

 

     不只这点配置,只是注解,单例模式,高度模块化了,这里不方便贴出来。

      

      其中数据库工作,整个框架工作原理,我还在消化阶段

 

       ebean 增删查改

pagedList = ebean.find(ApModel::class.java)

.order().desc("id")
        .setFirstRow((page - 1) * size)
        .setMaxRows(size)
        .findPagedList()