3

我的数据库中有以下表格

IMAGE_TABLE {
   `ID`
   `NAME`
}

IMAGE_OBJECT {
   `IMAGE_ID`
   `OBJECT_ID`
   `OBJECT_TYPE`
}

CAR {
   `ID`
   `DESCRIPTION`
}

HOUSE {
   `ID`
   `DESCRIPTION`
}

IMAGE_OBJECT 表将图像链接到汽车或房屋(取决于 OBJECT_TYPE 值)。在我的 ImageEntity 中,我想用单个实体映射字段:

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

但是这种映射会导致异常:

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

我还尝试使用@ManyToAny然后使用 setter 和 getter 将单个元素存储在集合中进行映射:

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

除非我尝试从中清除objects或删除元素,否则此方法有效:

objects.clear();

给我一个奇怪的例外:

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).

这可能是Hibernate 中的一个错误,所以我也不能使用这个映射。

有什么方法可以使用 @JoinTable 映射 Any-relation 吗?

4

1 回答 1

1

我最终得到了最后一个映射,并以下列方式编写了 setter 和 getter:

...
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);
    }
}
于 2013-09-25T14:16:54.010 回答