Hibernate组件映射不可变对象

Ste*_*Kuo 5 java hibernate

我有一个不可变对象,它是使用组件映射的Hibernate持久化对象的成员.示例,PinDrop对应于一个表,其中包含一个类型为immutable的字段Point:

public class PinDrop {
    private String name;
    private Point location;
    // Getters and setters for name and location
}

// Immutable Point
public class Point {
    private final double x;
    private final double y;
    // Getters for x and y, no setters
}
Run Code Online (Sandbox Code Playgroud)

在我的PinDrop.hbm.xml:

<property name="name" column="name" type="string"/>
<component name="location" class="Point>
    <property name="x" column="location_x" type="double"/>
    <property name="y" column="location_y" type="double"/>
</component>
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为在运行时Hibernate抱怨Point没有set x和for y.有没有办法使用不可变对象作为Hibernate持久对象的组件?

后续行动:我没有使用注释,而是使用注释hbm.xml.无论是mutable也不immutable是在有效的属性componentpropertyhbm.xml.

ben*_*n75 7

你可以告诉hibernate使用字段访问(access=field你的hbm中的属性),所以hibernate不会抱怨缺少访问者.

Hibernate使用反射来修改最终字段,以便它可以工作.

  • 我不相信这会起作用,但确实如此.显然可以使用反射修改最终字段.我想知道这对Java内存模型有什么影响,因为最终字段保证是线程安全的,并且适用于所有线程. (4认同)