Announcement Announcement Module
No announcement yet.
JpaRepository and Hibernate UserType Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • JpaRepository and Hibernate UserType

    I have a type that is very much like an enum. In order to allow my entities to have a property of this type, I've created a UserType and registered it globally in the following manner:

    @TypeDef(defaultForType=My.class, typeClass=MyType.class)
    public class MyType implements UserType {
        // code that marshals to/from a VARCHAR via a name() field on a My object
    Now let's say that I have an entity:

    public class MyEntity {
        private My my;
        public My getMy() {
            return my;
        protected void setMy(My my) {
   = my;
        // ... other fields
    This works perfectly with Hibernate. Objects are persisted and deserialized correctly. Now let's create a nice Spring Data Repository:

    public interface MyRepository extends JpaRepository<MyEntity, Integer> {
        MyEntity findByMy(My my);
    This does not work. Instead of using the globally-specified MyType for serializing the My object, Spring uses its own logic. This obviously fails. Moreover, when I try to replace the My with a String and call findByMy with, Spring tries to be too smart for its own good and declares that the given parameter doesn't match the class of the property.

    The conflation of these two issues seems to make it impossible to effectively use UserTypes with Spring Data. Am I missing some XML or other configuration incantation that I must perform to make this work?

  • #2
    This actually turned out to be a limitation with my type. I need to implement not just UserType, but also LiteralType. After implementing that interface as well, all queries work exactly as expected.