I’m pretty new with hibernate, and I’m trying to transform a JDBC project I have into Hibernate.
I’m using annotations, and I managed to annotate the basic stuff, however, I’m stuck now with the more heavy objects, I don’t know how to annotate them.
Here’s the Class:
@Entity
@Table(name = "person")
public class Person {
public Person{
}
// THIS WILL BE SOON INJECTED BY SPRING
private static transient PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
private static transient EmailValidator validator = EmailValidator.getInstance();
@Id
@Column(name = "person_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "private_name", nullable = false, length = 20)
private String privateName;
@Column(name = "middle_name", length = 20)
private String middleName;
@Column(name = "family_name", nullable = false, length = 20)
private String familyName;
@Column(name = "age", nullable = false)
private int age;
@Column(name = "address1", nullable = false)
private String address1;
@Column(name = "address2")
private String address2;
//How do I annotate this ? --> Google LIBPHONENUMBER
private PhoneNumber phone;
// How do I annotate this ? --> This is a normal PNG image file.
private File image;
Edit:
The File was previously mapped as a BLOB.
The PhoneNumber was previously persisted as String, and was transformed using the PhoneNumber constructor to Phonenumber.
The other comments about using @Lob are correct for the File type. It is also correct that if you can change the schema to not save the file data in the DB, then you probably should.
To map your PhoneNumber class to a database field, you’re going to need to use a Hibernate custom UserType. It basically tells Hibernate HOW to do the object<–>db mapping for classes that it doesn’t already know about. Telling the PhoneNumber field in Person to use a custom user type is easy:
This assumes a very simple one-column storage of the phone number.
To write PhoneNumberType, you’ll need to implement UserType. It looks overwhelming, with the assemble/disassemble/deepCopy, but the main part you care about is nullSetGet/Set, returnedClass and sqlTypes. You’ll end up with some code like this inside your custom type:
You can find plenty of information about how to implement the other methods via google, stackoverflow and the hibernate javadocs. It isn’t that hard to do.
UPDATE: Multi-column user type
Implement
CompositeUserTypeinstead of justUserType. There are a few method changes that you care about. First you’ll want to define the multiple property names and types:There’s also
getPropertyValue/setPropertyValueto implement. Your nullSafeXxxx implementations would change to read and write two properties instead of one: