【问题标题】:Spring boot OneToOne relationship problemSpring boot OneToOne 关系问题
【发布时间】:2019-10-17 04:53:06
【问题描述】:

我需要从没有某些字段的数据库中获取数据,但我收到或收到所有数据(有关系)或错误。

import org.springframework.data.domain.Persistable
import org.springframework.data.util.ProxyUtils
import java.io.Serializable
import javax.persistence.GeneratedValue
import javax.persistence.Id
import javax.persistence.MappedSuperclass
import javax.persistence.Transient

@MappedSuperclass
abstract class AbstractEntity<T : Serializable>() : Persistable<T> {

    companion object {
        private val serialVersionUID = -5554308939380869754L
    }

    @Id
    @GeneratedValue
    private var id: T? = null

    override fun getId(): T? {
        return id
    }

    fun setId(id:T){
        this.id = id
    }

    /**
     * Must be [Transient] in order to ensure that no JPA provider complains because of a missing setter.
     *
     * @see org.springframework.data.domain.Persistable.isNew
     */
    @Transient
    override fun isNew() = null == getId()

    override fun toString() = "Entity of type ${this.javaClass.name} with id: $id"

    override fun equals(other: Any?): Boolean {
        other ?: return false

        if (this === other) return true

        if (javaClass != ProxyUtils.getUserClass(other)) return false

        other as AbstractEntity<*>

        return if (null == this.getId()) false else this.getId() == other.getId()
    }

    override fun hashCode(): Int {
        return 31
    }
}

产品实体:

@Entity
@Table(name = "product")
class ProductEntity : AbstractEntity<Long> {
    @Column(name = "product_name")
    var productName: String = ""
    @Column(name = "description", length = 65535, columnDefinition = "text")
    var description: String = ""
    @Column(name = "product_model")
    var productModel: String = ""
    @Column(name = "product_articul")
    var productArticul: String = ""
    @Column(name = "product_count")
    var productCount: Int = 0
    @Column(name = "is_available")
    var isAvailable: Boolean = false
    @Column(name = "product_price")
    var productPrice: Float = 0f
    @Column(name = "product_extra")
    var productExtra: Float = 0f
    @Column(name = "product_total_price")
    var productTotalPrice: Float = 0f
    @OneToOne(cascade = [CascadeType.PERSIST, CascadeType.MERGE], orphanRemoval = false, fetch = FetchType.LAZY)
    var productCategoryProperty: ProductCategoryPropertyEntity = ProductCategoryPropertyEntity()
    @OneToOne(cascade = [CascadeType.PERSIST, CascadeType.MERGE], fetch = FetchType.LAZY)
    var category: CategoryEntity = CategoryEntity()
    @Column(name = "images")
    var images: Array<String?> = arrayOf()
    @Column(name = "keywords", length = 65535, columnDefinition = "text")
    var keywords: String? = ""

    constructor() : super() {
    }

    fun convertToDto(): ProductDto {
        return ProductDto(id, productName, description, productModel, productArticul,
                productCount, productPrice, productExtra, productTotalPrice, isAvailable,
                productCategoryProperty?.convertToDto(), category?.convertToDto(), images, keywords)
    }
}

ProductCategoryPropertyEntity:

import ua.jdroidcoder.jdcshop.dto.ProductCategoryPropertyDto
import javax.persistence.*

@Entity
@Table(name = "product_category_property")
class ProductCategoryPropertyEntity : AbstractEntity<Long> {

    @OneToMany(cascade = [CascadeType.PERSIST, CascadeType.MERGE], orphanRemoval = false)
    var simpleProperties: MutableList<ProductPropertySimpleEntity> = ArrayList()

    @OneToMany(cascade = [CascadeType.PERSIST, CascadeType.MERGE], orphanRemoval = false)
    var advancedProperties: MutableList<ProductPropertySimpleEntity> = ArrayList()

    constructor() : super() {
    }

    fun convertToDto(): ProductCategoryPropertyDto {
        val simple = ProductCategoryPropertyDto()
        simple.id = id
        simpleProperties?.forEach {
            simple.simpleProperties.add(it.convertToDto())
        }
        advancedProperties?.forEach {
            simple.advancedProperties.add(it.convertToDto())
        }
        return simple
    }
}

ProductPropertySimpleEntity:

import ua.jdroidcoder.jdcshop.dto.PropertySimpleDto
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Table

@Entity
@Table(name = "product_property_simple")
class ProductPropertySimpleEntity : AbstractEntity<Long> {
    @Column(name = "property_name")
    var propertyName: String = ""

    @Column(name = "property_value")
    var propertyValue: String = ""

    @Column(name = "parent_id")
    var parentId: Long? = null

    @Column(name = "parent_id_in_category")
    var parentIdInCategory: Long? = null

    @Column(name = "id_in_category")
    var idInCategory: Long? = null

    constructor() : super() {
    }

    fun convertToDto(): PropertySimpleDto {
       return PropertySimpleDto(id!!,propertyName,parentId,propertyValue)
    }
}

当我尝试 make select 时,我看到:

Hibernate: select productent0_.id as id1_3_, productent0_.category_id as categor13_3_, productent0_.description as descript2_3_, productent0_.images as images3_3_, productent0_.is_available as is_avail4_3_, productent0_.keywords as keywords5_3_, productent0_.product_articul as product_6_3_, productent0_.product_category_property_id as product14_3_, productent0_.product_count as product_7_3_, productent0_.product_extra as product_8_3_, productent0_.product_model as product_9_3_, productent0_.product_name as product10_3_, productent0_.product_price as product11_3_, productent0_.product_total_price as product12_3_ from product productent0_
Hibernate: select categoryen0_.id as id1_0_0_, categoryen0_.category_name as category2_0_0_, categoryen0_.prom_category_id as prom_cat3_0_0_ from category categoryen0_ where categoryen0_.id=?
Hibernate: select productcat0_.id as id1_4_0_ from product_category_property productcat0_ where productcat0_.id=?
Hibernate: select simpleprop0_.product_category_property_entity_id as product_1_6_0_, simpleprop0_.simple_properties_id as simple_p2_6_0_, productpro1_.id as id1_7_1_, productpro1_.id_in_category as id_in_ca2_7_1_, productpro1_.parent_id as parent_i3_7_1_, productpro1_.parent_id_in_category as parent_i4_7_1_, productpro1_.property_name as property5_7_1_, productpro1_.property_value as property6_7_1_ from product_category_property_simple_properties simpleprop0_ inner join product_property_simple productpro1_ on simpleprop0_.simple_properties_id=productpro1_.id where simpleprop0_.product_category_property_entity_id=?
Hibernate: select advancedpr0_.product_category_property_entity_id as product_1_5_0_, advancedpr0_.advanced_properties_id as advanced2_5_0_, productpro1_.id as id1_7_1_, productpro1_.id_in_category as id_in_ca2_7_1_, productpro1_.parent_id as parent_i3_7_1_, productpro1_.parent_id_in_category as parent_i4_7_1_, productpro1_.property_name as property5_7_1_, productpro1_.property_value as property6_7_1_ from product_category_property_advanced_properties advancedpr0_ inner join product_property_simple productpro1_ on advancedpr0_.advanced_properties_id=productpro1_.id where advancedpr0_.product_category_property_entity_id=?

我知道这是通过@OneToOne 发生的,但我无法寻求解决方案;(

我只需要接收一些字段,例如:productName、description、productModel、productArticul、productCount...

谢谢大家的帮助!

【问题讨论】:

    标签: spring spring-boot jpa kotlin spring-data-jpa


    【解决方案1】:

    如果您允许null 值,@OneToOne 会很棘手。

    JPA 必须尝试从另一个表访问记录,即使该属性是用 lazy-initialization 签名的,因为它必须决定是否将属性设置为null 或代理对象。

    它不能自动设置它null,因为那里可以是一个关联的对象。 它也不能自动创建代理对象,因为在表中没有为该属性的id指定列(因为默认情况下,共享PK映射了一对一的关系)。

    因此,确定关联实体是否存在的唯一方法是尝试从其自己的表中加载其id。如果此查询返回 null 则没有关联实体,否则 JPA 可以从该 id 创建代理对象。

    如果您确实需要避免这个额外的请求,请将product_category_property 表的外键添加到product 表中。

    @OneToOne(cascade = [CascadeType.PERSIST, CascadeType.MERGE], orphanRemoval = false, fetch = FetchType.LAZY)
    @JoinColumn(name='product_category_property')
    var productCategoryProperty: ProductCategoryPropertyEntity = ProductCategoryPropertyEntity()
    

    您可以找到更多解释in this topic

    【讨论】:

      猜你喜欢
      • 2017-11-10
      • 2022-01-24
      • 2020-01-05
      • 2019-08-12
      • 2021-01-17
      • 2021-06-15
      • 2021-05-22
      • 1970-01-01
      • 2014-11-09
      相关资源
      最近更新 更多