Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate component mapping of an immutable object

Tags:

java

hibernate

I have an immutable object which is a member of a Hibernate persisted object using component mapping. Example, PinDrop corresponds to a table, which has a field of type 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
}

In my 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>

This doesn't work because at runtime Hibernate complains that Point doesn't have setters for x and y. Is there a way to use an immutable object as a component of a Hibernate persistent object?

Follow-up: I'm not using annotations, but rather hbm.xml. Neither mutable nor immutable are valid attributes on component and property in hbm.xml.

like image 660
Steve Kuo Avatar asked Mar 21 '13 22:03

Steve Kuo


People also ask

How can a class be mapped as immutable in hibernate?

You can tell Hibernate that a specific entity is immutable by using @Entity(mutable=false) or @Immutable annotations. Note that both are Hibernate extensions to JPA standard.

What is immutable in hibernate?

Annotation Type ImmutableMark an Entity, a Collection, or an Attribute type as immutable. No annotation means the element is mutable. An immutable entity may not be updated by the application. Updates to an immutable entity will be ignored, but no exception is thrown.

What is or mapping give an example of hibernate XML mapping file?

This mapping file instructs Hibernate — how to map the defined class or classes to the database tables? Though many Hibernate users choose to write the XML by hand, but a number of tools exist to generate the mapping document. These include XDoclet, Middlegen and AndroMDA for the advanced Hibernate users.


1 Answers

You can tell hibernate to use field access (attribute access=field in your hbm) so hibernate won't complains about missing accessors.

Hibernate use reflection to modify the final fields so it should work.

like image 144
ben75 Avatar answered Oct 10 '22 14:10

ben75