Assignment of @CollectionId and @ElementCollection

I have a class that im is 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>(); ... } 

unit test throws the following exception:

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

I am not too sure of the best value for the β€œgenerator”, and I assume that this will affect the result.

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

I want the Property_images table to have a compound key [Property_id-Image_index], where Image_index starts with 1 for each new Property_id, but I have no idea how to implement this using @ElementCollection and @CollectionId using a generator. Maybe I should have FileAttachment as @Entity instead of @Embeddable, but id is probably not the way it is used only inside the Property class.

Hooray! Nfv

+4
source share
2 answers

From Persistence of Java Wikibook :

The JPA 2.0 specification does not allow an identifier to be defined in Embeddable. However, to remove or update an item, an ElementCollection mapping is usually required, some unique key. Otherwise, with each upgrade, the JPA will need to remove everything from CollectionTable for Entity, and then paste the values ​​back. Thus, the JPA provider will most likely assume that the combination of all the fields in Embeddable is unique, in combination with the foreign key (JoinColumn (s)). However, this could be ineffective or simply impossible if the Recessed is large, or complex. Some JPA providers may allow ID identification in Embeddable to solve this problem. Note that in this case, Id only needs to be unique for the collection, not the table, since the foreign key is included. Some may also allow a unique option in CollectionTable for this. Otherwise, if your Embeddable is complex, you might consider making it an entity and using OneToMany.

I think your IMAGE_INDEX requirement can be solved with OrderColumns :

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

This post may be helpful.

+2
source

I think you should give an implementation for the generator. We can use a sequence generator.

Try:

 @GenericGenerator(name="myGenerator",strategy="sequence") @CollectionId( columns=@Column (name="Property_image_id"), type=@Type (type="long"), generator="myGenerator" ) 
0
source

All Articles