Display hibernation using @Any and @JoinTable

I have the following tables in my database

IMAGE_TABLE { `ID` `NAME` } IMAGE_OBJECT { `IMAGE_ID` `OBJECT_ID` `OBJECT_TYPE` } CAR { `ID` `DESCRIPTION` } HOUSE { `ID` `DESCRIPTION` } 

The IMAGE_OBJECT table associates an image with a car or with a house (depending on the value of OBJECT_TYPE). In my ImageEntity I want to display a field with a single object:

  @Any( metaColumn = @Column( table="IMAGE_OBJECT", name = "OBJECT_TYPE" ) ) @AnyMetaDef( idType = "long", metaType = "string", metaValues = { @MetaValue( value = "car", targetEntity = CarEntity.class ), @MetaValue( value = "house", targetEntity = HouseEntity.class ) } ) @JoinTable(name = "IMAGE_OBJECT", joinColumns = { @JoinColumn(name = "IMAGE_ID", unique = true) }, inverseJoinColumns = { @JoinColumn(name = "OBJECT_ID") } ) private AbstractEntity object; 

But this mapping leads to an exception:

 org.hibernate.AnnotationException: @Any requires an explicit @JoinColumn(s) 

I also tried matching using @ManyToAny and then using setter and getter to store one item in a collection:

  @ManyToAny( metaColumn = @Column( table="IMAGE_OBJECT", name = "OBJECT_TYPE" ) ) @AnyMetaDef( idType = "long", metaType = "string", metaValues = { @MetaValue( value = "car", targetEntity = CarEntity.class ), @MetaValue( value = "house", targetEntity = HouseEntity.class ) } ) @JoinTable(name = "IMAGE_OBJECT", joinColumns = { @JoinColumn(name = "IMAGE_ID", unique = true) }, inverseJoinColumns = { @JoinColumn(name = "OBJECT_ID") } ) private Set<AbstractEntity> objects; 

This works if I do not try to clear objects or remove an element from it:

 objects.clear(); 

Giving me a weird exception:

 org.springframework.orm.hibernate3.HibernateJdbcException: JDBC exception on Hibernate data access: SQLException for SQL [delete from IMAGE_OBJECT where IMAGE_ID=? and OBJECT_ID=?]; ... Caused by: java.sql.SQLException: Parameter index out of range (3 > number of parameters, which is 2). 

Perhaps this is a bug in Hibernate , so I cannot use this mapping.

Is there any way to match any relation using @JoinTable?

+4
source share
1 answer

In the end, I got the latest mapping and wrote down the setter and getter as follows:

 ... private Set<AbstractEntity> objects = new HashSet<AbstractEntity>(); ... public AbstractEntity getObject() { return objects.isEmpty() ? null : objects.get(0); } public void setObject(AbstractEntity object) { // objects.clear() results in weird exception objects = new HashSet<AbstractEntity>(); if (object != null) { objects.add(object); } } 
+1
source

Source: https://habr.com/ru/post/1488130/


All Articles