简体   繁体   中英

In JPA mapping class to primitive

I want to mapping a class to a primitive type

@Entity
@Table(name="PERSON")
public class Person implements Serializable {
    ...
   private Email email = null;
    ...
   @Column(name="email")
   public Email getEmail() {
      return email;
   }
   public void setEmail(Email email) {
      this.email=email;
   }
}

In this example I want to save the email like a String

I wish something like:

interface someInterface{

   String getValue();
   void setValue(String p);

}

Then if I implement this interface in Email it can be save and loaded transparently (I haven't find something like this).

I don't want to serialize the class

I use Email as a example, but I have in mind many other class, to little to be a whole entity.

Any idea?

JPA2.1 provides AttributeConverter which means that a field can be marked with a converter persisting it as, for example, a String. All JPA implementations have their own variant currently, but DataNucleus JPA provides the JPA2.1 feature already, see the foot of this page .

Make two variables. Email which is object and that you mark as @Transient and emailStr that you store in the database. The emailStr getter and setter should be private, and the getEmail creates the email object (lazily) based on the emailStr.

Another solution, if you have email in many entities is to create a custom UserType.

Just google hibernate UserType..

There's nothing stopping you from using String in your Classes as far as JPA is concerned. Or any other primitive type for that matter...

EDIT: You mean something like this hopefully

@Entity
@Table(name="PERSON")
public class Person implements Serializable {
    ...
   private String email = null;
    ...
   @Column(name="email")
   public String getEmail() {
      return email;
   }
   public void setEmail(String email) {
      this.email=email;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM