java - 将 @CollectionId 分配给和 @ElementCollection

标签 java hibernate

我有一个我正在尝试实现的类,(类似于“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>();

    ...
}

单元测试失败抛出以下异常:

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

我不太确定“generator”的最佳值,我认为这会影响结果。

此外,当我开始工作时,FileAttachment 对象能否访问 Property_image_id?你如何将它分配给一个属性,因为它是在 Property 类中定义的?

我想要的是 Property_images 表有一个复合键 [Property_id-Image_index],其中 Image_index 对于每个新的 Property_id 从 1 开始,但我不知道如何使用 @ElementCollection 和 @CollectionId 来实现它发电机。也许我必须将 FileAttachment 作为 @Entity 而不是 @Embeddable,但 id 而不是它仅在 Property 类中使​​用。

干杯! 网络功能虚拟化

最佳答案

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

试一试:

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

关于java - 将 @CollectionId 分配给和 @ElementCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13751081/

相关文章:

java - 为什么 Hibernate 执行 JNDI 查找?

java - 删除实体@OneToMany @ManyToOne。键仍然从表中引用

java - CONSTANT_MethodHandle_info 和 CONSTANT_MethodType_info

java - Java 中的动态数组?使用 ArrayList 与 int[] array = new int[n]

hibernate - Grails具有许多值为0的条件

java - H2 数据库仅在文件中不能在内存中工作

java - 以字符集安全的方式获取 Windows 上的进程列表

java - travis-ci 中的 gradle 检查失败

java - 如何修复Flink 'error: cannot infer type arguments for FlinkKafkaConsumer011<>'

java - 没有可用的事务性 EntityManager - 使用 JPA Api,Hibernate Session 出错