3

I have a many-to-one relationship and I like that the last shared reference should get deleted by hibernate automatically. The questions are

  • is this is supported by hibernate?
  • if not can I achieve this by adding some kind of api callbacks from JPA/Hibernate rather then fully code it in the DAOs by myself?

Example I have an "Attribute" (Name/Value Pair) which is an entity and its shares some "Translation" for its name with other Attributes. So if an attribute get deleted hibernate should check if still another attribute exists where the same translation is used. If there is no one left the translation should be deleted as well.

@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>();
    ...
}

I am using hibernate v4.3.

megloff
  • 1,400
  • 4
  • 27
  • 44

1 Answers1

1

I think Jpa Entity Listeners good choice for you

for your question write one metod and anotate @PostRemove in Attribute.class

@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`

}
kakashi hatake
  • 1,175
  • 2
  • 10
  • 18