保存带有缓存对象的实体导致分离的实体异常

use*_*499 1 spring hibernate jpa spring-data spring-data-jpa

我正在尝试使用 Spring Data/Crud Repository(.save) 在 DB 中保存一个实体,其中包含另一个通过 @Cache 方法加载的实体。换句话说,我试图保存一个包含 Attributes 实体的 Ad Entity,并且这些属性是使用 Spring @Cache 加载的。

因此,我将分离的实体传递给持久性异常。

我的问题是,有没有办法保存实体仍然使用@Cache 作为属性?

我查了一下,但找不到任何人做同样的事情,特别是我知道我使用的 CrudRepository 只有方法 .save(),据我所知,它管理持久化、更新、合并等。

很感谢任何形式的帮助。

提前致谢。

广告.java

@Entity
@DynamicInsert
@DynamicUpdate
@Table(name = "ad")
public class Ad implements SearchableAdDefinition {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    private User user;

    @OneToMany(mappedBy = "ad", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private Set<AdAttribute> adAttributes;

(.....) }
Run Code Online (Sandbox Code Playgroud)

广告属性.java

@Entity
@Table(name = "attrib_ad")
@IdClass(CompositeAdAttributePk.class)
public class AdAttribute {

    @Id
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ad_id")
    private Ad ad;

    @Id
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "attrib_id")
    private Attribute attribute;

    @Column(name = "value", length = 75)
    private String value;

    public Ad getAd() {
        return ad;
    }

    public void setAd(Ad ad) {
        this.ad = ad;
    }

    public Attribute getAttribute() {
        return attribute;
    }

    public void setAttribute(Attribute attribute) {
        this.attribute = attribute;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}


@Embeddable
 class CompositeAdAttributePk implements Serializable {
    private Ad ad;
    private Attribute attribute;

    public CompositeAdAttributePk() {

    }

    public CompositeAdAttributePk(Ad ad, Attribute attribute) {
        this.ad = ad;
        this.attribute = attribute;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CompositeAdAttributePk compositeAdAttributePk = (CompositeAdAttributePk) o;
        return ad.getId().equals(compositeAdAttributePk.ad.getId()) && attribute.getId().equals(compositeAdAttributePk.attribute.getId());

    }

    @Override
    public int hashCode() {
        return Objects.hash(ad.getId(), attribute.getId());
    }

}
Run Code Online (Sandbox Code Playgroud)

用于加载属性的方法:

@Cacheable(value = "requiredAttributePerCategory", key = "#category.id")
public List<CategoryAttribute> findRequiredCategoryAttributesByCategory(Category category) {

    return categoryAttributeRepository.findCategoryAttributesByCategoryAndAttribute_Required(category, 1);
}
Run Code Online (Sandbox Code Playgroud)

用于创建/保留广告的方法:

@Transactional
public Ad create(String title, User user, Category category, AdStatus status, String description, String url, Double price, AdPriceType priceType, Integer photoCount, Double minimumBid, Integer options, Importer importer, Set<AdAttribute> adAtributes) {
    //Assert.notNull(title, "Ad title must not be null");

    Ad ad = adCreationService.createAd(title, user, category, status, description, url, price, priceType, photoCount, minimumBid, options, importer, adAtributes);

    for (AdAttribute adAttribute : ad.getAdAttributes()) {
        adAttribute.setAd(ad);

/* If I add this here, I don't face any exception, but then I don't take benefit from using cache:
        Attribute attribute = attributeRepository.findById(adAttribute.getAttribute().getId()).get();
        adAttribute.setAttribute(attribute);
*/

    }

    ad = adRepository.save(ad);

    solrAdDocumentRepository.save(AdDocument.adDocumentBuilder(ad));

    return ad;
}
Run Code Online (Sandbox Code Playgroud)

Ash*_*lam 5

我不知道你是否还需要这个答案,因为已经很长时间了,你问了这个问题。然而,我要在这里留下我的评论,其他人可能会从中得到帮助。

让我们假设,您从应用程序的其他部分调用了findRequiredCategoryAttributesByCategory方法。Spring 将首先检查缓存,并且什么也找不到。然后它会尝试从数据库中获取它。所以它将创建一个休眠会话,打开一个事务,获取数据,关闭事务和会话。最后从函数返回后,它将结果集存储在缓存中以备将来使用。

您必须记住,这些值目前在缓存中,它们是使用休眠会话获取的,该会话现已关闭。所以它们与任何会话都没有关系,现在处于分离状态。

现在,您正在尝试保存和Ad实体。为此,spring 创建了一个新的休眠会话,并将Ad实体附加到此特定会话。但是您从缓存中获取的属性对象是分离的。这就是为什么当您尝试保留 Ad 实体时,您会收到Detached Entity Exception

要解决此问题,您需要将这些对象重新附加到当前的休眠会话。我使用merge()方法来执行此操作。从这里的休眠文档https://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Session.html

将给定对象的状态复制到具有相同标识符的持久对象上。如果当前没有与会话关联的持久实例,它将被加载。返回持久化实例。如果给定的实例未保存,则保存一个副本并将其作为新的持久实例返回。给定的实例不会与会话关联。如果关联映射为cascade="merge",则此操作级联到关联的实例。

简而言之,这会将您的对象附加到休眠会话。你应该做什么,在调用你的findRequiredCategoryAttributesByCategory方法之后,写一些类似的东西

List attributesFromCache = someService.findRequiredCategoryAttributesByCategory();
List attributesAttached = entityManager.merge( attributesFromCache );
Run Code Online (Sandbox Code Playgroud)

现在将 attributesAttached 设置到您的 Ad 对象。这不会抛出异常,因为属性列表现在是当前 Hibernate 会话的一部分。