4

I have a class which im trying to implement, (similar to the example in 'Java Persistence with Hibernate' 6.3.3)

public class Property
{
    ...

    @ElementCollection(fetch=FetchType.EAGER)
    @CollectionId(
        columns=@Column(name="Property_image_id"),
        type=@Type(type="long"),
        generator="native"
    )
    private Collection<FileAttachment> images = new ArrayList<FileAttachment>();

    ...
}

The unit test fails throwing the following exception:

java.lang.ClassCastException: org.hibernate.id.IdentifierGeneratorHelper$2 
    cannot be cast to java.lang.Long

Im not too sure about the best value for 'generator', and I assume this will affect the outcome.

Also when i get this working, can the FileAttachment object access the Property_image_id? And how do you assign it to a property, since its defined in the Property class?

What I'd like is for the Property_images table to have a composite key [Property_id-Image_index], where Image_index starts at 1 for each new Property_id but I have no idea how to implement this using @ElementCollection and @CollectionId with a generator. Maybe i have to have FileAttachment as an @Entity instead of @Embeddable, but id rather not as its only used inside the Property class.

Cheers! NFV

4

2 回答 2

2

来自Java 持久性 Wikibook

JPA 2.0 规范没有提供在 Embeddable 中定义 Id 的方法。但是,要删除或更新 ElementCollection 映射的元素,通常需要一些唯一键。否则,在每次更新时,JPA 提供者都需要从实体的 CollectionTable 中删除所有内容,然后将值插入回来。因此,JPA 提供者很可能会假设 Embeddable 中所有字段的组合是唯一的,并结合外键 (JoinColumn(s))。但是,如果 Embeddable 很大或很复杂,这可能效率低下,或者根本不可行。一些 JPA 提供程序可能允许在 Embeddable 中指定 Id,以解决此问题。请注意,在这种情况下,ID 只需要对集合而不是表是唯一的,因为包含外键。有些人可能还允许为此使用 CollectionTable 上的唯一选项。否则,如果您的 Embeddable 很复杂,您可以考虑将其设为实体并改用 OneToMany。

我认为您的IMAGE_INDEX要求可以通过OrderColumns来解决:

@ElementCollection(fetch=FetchType.EAGER)
@OrderColumn(name = "IMAGE_INDEX")
private List<FileAttachment> images;

这篇文章可能有用。

于 2012-12-06T19:47:51.270 回答
2

我想您应该为生成器提供一个实现。我们可以使用“序列”生成器。

试试这个:

@GenericGenerator(name="myGenerator",strategy="sequence")
@CollectionId(
    columns=@Column(name="Property_image_id"),
    type=@Type(type="long"),
    generator="myGenerator"
)
于 2016-11-27T04:37:21.523 回答