Spring Data - hibernate.cfg.xml在不同的包中。

问题描述 投票:0回答:1

我是Spring的新手,想用Spring数据创建一个六边形的架构

我有一个gradle多模块的设置,其中一个包用于域,一个包用于持久性,另一个包用于配置,DddApplication就在那里。

当启动它时,我得到 Not a managed type: class com.example.ddd.domain.model.Customer除非我用javax.persistence.@Entity等来注释这个类。

但是我不希望在类中做注解,我已经在hibernate.cfg.xml和Customer.hbm.xml中设置了实体。我在hibernate.cfg.xml和Customer.hbm.xml中设置了实体。persistence 包。

我认为Spring Boot没有使用其他包中的hibernate.cfg.xml。

有什么方法可以配置Spring Boot,让它根据包中的hibernate.cfg.xml来识别实体。persistence 包?

package com.example.ddd.configuration

// ...

@SpringBootApplication
@EntityScan("com.example.ddd.domain.model")
@EnableJpaRepositories("com.example.ddd.persistence.repository")
class DddApplication {
    private val log: Logger = LoggerFactory.getLogger(DddApplication::class.java)

    @Bean
    fun loadData(repository: CustomerRepositoryJpa): CommandLineRunner? {
        return CommandLineRunner { args: Array<String?>? ->
//...
        }
    }
}

fun main(args: Array<String>) {
    runApplication<DddApplication>(*args)
}
package com.example.ddd.persistence.repository

//...

@Repository
interface CustomerRepositoryJpa : JpaRepository<Customer?, Long?> {}
package com.example.ddd.domain.model

open class Customer private constructor() {
    val id: Long? = null
    lateinit var firstName: String
    lateinit var lastName: String
    override fun toString(): String {
        return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id,
                firstName, lastName)
    }

    companion object {
        fun new(firstName: String, lastName: String) : Customer {
            val e = Customer()
            e.firstName = firstName
            e.lastName = lastName
            return e
        }
    }
}

application.properties和hibernate.cfg.xml的资源中。persistence 包。

hibernate kotlin spring-data hexagonal-architecture
1个回答
1
投票

你可以看一下这个答案和附件的代码片段 此处.我们的想法是让spring-data使用orm.xml配置文件,在这里你可以定义你的域对象JPA的特殊性。

一些评论

这里唯一困扰你的是JPA注解.这些注解是一个 声明式 的方式来表明您的域对象(实体、值类型)也可以被视为JPA实体。

你可能会遵守DDD,六边形架构&amp。KISS 原则,让它们驻留在你的领域中。事实上,它们不会对任何技术持久化框架(如Hibernate)产生强烈的依赖性;因为它们是注解,也因为仅有的 jpa规范库 是需要的,作为你的域的依赖。这样的域仓库以后可以用Hibernate以外的其他东西来实现(NoSQL、AWS S3什么的......),将这些注释保留到你的域中。

这是代码简单性和六边形原则应用之间的交易,因为XML orm文件看起来比注释更难维护。然而这样的文件可以避免JPA注解对你的领域的污染,或者在六边形之外增加一个额外的JPA实体层。


0
投票

你可以在一个XML配置文件("orm.xml")中定义映射、字段等,而不是把JPA注解放在实体类中。我不会用JPA的东西来玷污实体,因为JPA是关于持久性的,它是技术,它应该在六边形之外的适配器中。

© www.soinside.com 2019 - 2024. All rights reserved.