views:

52

answers:

2

I have a class:

public class Email {
  private String name;
  private String domain;
  public String toString() {
    return name + "@" + domain;
  }  
}

I want to use it in JPA column:

@Entity
public class User {
  @Id private Integer id;
  private Email email;
}

This is what Hibernate says:

org.hibernate.MappingException: Could not determine type for: com.XXX.Email

How to make it understand my custom type. I think that it's something very simple, but can't find in documentation.

+1  A: 

You can make email an entity and it will work...but it's pretty ineficcient.

@Entity
public class Email {
  ...
}

Or you can swtich from Email to String and it will work. (What's the point of wrapping a String anyway?)

You can read this tutorial about custom user types in Hibernate (since you tagged it).

Or you can use @Embebbed as Bozho says.

pakore
+3  A: 

Well, there are a number of ways:

  • annotate the Email class with @Embeddable, and have:

     @Embedded
     private Email email;
    
  • declare a custom value type - see here (using @Type)

Bozho
@Bozho I wonder whether the second approach proposed is possible with just JPA (without Hibernate-specific annotations)?
Vincenzo
@Vincenzo no. See this answer http://stackoverflow.com/questions/3628344/jpa2-0-support-of-custom-user-types-and-second-level-cache
Bozho
@Bozho Can't I implement the same behavior through setters/getters?
Vincenzo
it would be uglier than using the embeddable option. :) But you can
Bozho
Well summarized +1
Pascal Thivent