Hibernate - 多对一关系,是否可以自动删除最后一个共享引用?

Hibernate - Many to One relationship, possibility to delete last shared reference automatically?

我有一个多对一的关系,我喜欢最后一个共享引用应该被休眠自动删除。问题是

示例我有一个 "Attribute"(Name/Value 对),它是一个实体,它的名称与其他属性共享一些 "Translation"。因此,如果一个属性被删除,hibernate 应该检查是否还有另一个属性存在于使用相同翻译的地方。如果没有人离开,翻译也应该被删除。

@Entity
public class Attribute {

    @Id
    @GeneratedValue
    private int id;

    private String name;

    @Lob
    private String value;

    @ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.PERSIST)
    @JoinColumn(name="name_translation_id")
    private Translation nameTranslation;
    ...
}

@Entity
public class Translation {

    @Id
    @GeneratedValue
    private int id;

    @ElementCollection (fetch=FetchType.LAZY)
    @CollectionTable(name= "translation_values", joinColumns = @JoinColumn(name = "translation_id"))
    @MapKeyColumn(name="language_code")
    @Column(name = "value")
    @Lob
    private Map<String, String> values = new HashMap<String, String>();
    ...
}

我正在使用休眠 v4.3。

我觉得 Jpa Entity Listeners 对你来说是个不错的选择

对于你的问题写一个方法并在Attribute.class

中注释@PostRemove
@PostRemove
public void removeTranslationByAttribute(Attribute attribute){

List<Attribute> attributes = AttributeRepository.getByNameTranslationId(attribute.getNameTranslation()); //get all atribute by `name_translation_id`

if(attributes.size() == 0) // when not include atrribute in list`name_translation_id`
TranslationRepository.deleteById(attribute.getNameTranslation()); // delete translation object by `name_translation_id`

}