java 如何在 JPA 列中使用自定义类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3828675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:34:12  来源:igfitidea点击:

How to use custom type in JPA column?

javahibernatejpa

提问by yegor256

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:

我想在 JPA 列中使用它:

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

This is what Hibernate says:

这是 Hibernate 所说的:

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.

如何让它理解我的自定义类型。我认为这很简单,但在文档中找不到。

回答by Bozho

Well, there are a number of ways:

嗯,有很多方法:

  • annotate the Emailclass with @Embeddable, and have:

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

  • 用 注释Email该类@Embeddable,并具有:

     @Embedded
     private Email email;
    
  • 声明自定义值类型 - 请参见此处(使用@Type

回答by pakore

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

您可以使电子邮件成为一个实体,它会起作用……但效率很低。

@Entity
public class Email {
  ...
}

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

或者你可以Email切换到String,它会起作用。(无论如何包装一个字符串有什么意义?)

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

您可以阅读本教程,了解 Hibernate 中的自定义用户类型(因为您标记了它)。

Or you can use @Embebbedas Bozho says.

或者你可以@Embebbed像 Bozho 所说的那样使用。