What's wrong with my custom type for JPA/Hibernate?
My custom type is (no default constructor!):
package com.XXX.common;
public class Email implements Serializable {
private String e;
public Email(String str) {
e = str;
}
}
My entity in Hibernate 3.5.6:
package com.XXX.persistence;
import com.XXX.common;
@Entity
@TypeDef(
name = "email",
defaultForType = Email.class,
typeClass = Email.class
)
public class User {
@Id private Integer id;
@Type(type = "email")
private Email email;
}
Hibernate says:
org.hibernate.MappingException: Could not de开发者_Go百科termine type for:
com.XXX.common.Email, at table: user, for columns:
[org.hibernate.mapping.Column(email)]
What am I doing wrong?
My custom type is (no default constructor!) (...)
A custom type must implement one of the interfaces from org.hibernate.usertype
(implementing UserType
would be enough for your specific example), your Email
class is NOT a custom type. In other words, you'll need to create some EmailType
class that Hibernate will use to persist a field or property of type Email
.
PS: There is IMO not much value at wrapping a String
with a class but let's say it was an example.
References
- Hibernate Core Reference Guide
- 5.2.3. Custom value types
Resources
- Hibernate CompositeUserType and Annotations
- user_type examples on the Hibernate Wiki
typeClass
must point to something that extends UserType
(this handler class contains the mapping from and to the database).
精彩评论