Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a custom Hibernate UserType - What does isMutable() mean?

I am creating a custom UserType in Hibernate for a project. It has been relatively straightforward until I came to the isMutable method. I am trying to figure out what this method means, contract-wise.

Does it mean the class I am creating the UserType for is immutable or does it mean the object that holds a reference to an instance of this class will never point to a different instance?

I found some examples in the Hibernate Community Wiki where they returned true, because the object itself was mutable - http://www.hibernate.org/73.html.

Other examples in the community wiki returned false without addressing why, even though they were also mutable.

I have checked the JavaDoc, but it's not very clear either.

From the JavaDoc for UserType:

public boolean isMutable()
    Are objects of this type mutable?
    Returns:
        boolean

From JavaDoc for Type:

public boolean isMutable()
    Are objects of this type mutable. (With respect to the referencing
    object ... entities and collections are considered immutable because
    they manage their own internal state.)
    Returns:
        boolean
like image 671
Johann Zacharee Avatar asked Oct 22 '08 04:10

Johann Zacharee


2 Answers

Hibernate will treat types marked as "mutable" as though they could change (i.e. require an UPDATE) without pointing to a new reference. If you assign a new reference to a Hibernate-loaded property Hibernate will recognize this even if the type is immutable - this happens all the time with, for instance, String fields. But if, say, you have a StringBuilder field and you mark it as immutable Hibernate will not notice if you modify the StringBuilder.

See this blog post for more details and a sample project.

like image 135
Andrew Phillips Avatar answered Nov 14 '22 07:11

Andrew Phillips


The typical example here is the String class - it is Immutable, i.e. once the string is created you cannot change its contents or state, and if you want to then you're going to have to process it into a new copy.

isMutable returning true means you are saying this object can have its state changed by outside objects, returning false means you will have to copy this object to a new instance makign the changes to state along the way. Or as you said: "does it mean the object that holds a reference to an instance of this class will never point to a different instance".

like image 20
jmcd Avatar answered Nov 14 '22 06:11

jmcd