Hibernate中的数据类型映射有哪些?如何自定义数据类型映射?代码举例讲解

在Hibernate中,常见的数据类型映射主要有:

1、 基本类型映射:

  • Byte/byte -> tinyint
  • Short/short -> smallint
  • Integer/int -> int
  • Long/long -> bigint
  • Float/float -> float
  • Double/double -> double
  • Character/char-> char
  • String -> varchar
  • Boolean/bool -> bit
  • Date -> date
  • Timestamp -> timestamp
  • 等等

2、 自定义类型映射:

  • 需要实现org.hibernate.usertype.UserType接口,并指定返回的SqlType。
  • 然后在hibernate.cfg.xml中注册自定义类型。
    例如,映射Enum类型:
public class EnumType implements UserType {
    public int[] sqlTypes() {
        return new int[] {Types.VARCHAR};
    }
    // 其他方法...
} 

在hibernate.cfg.xml中注册:

<property name="enum">
    <type type="com.demo.EnumType"/> 
</property> 

3、 复杂类型映射:

  • Set.List.Map等集合类型和组件类型。
  • 需要指定collection元素的类型或component的封装类。
    例如:
@Entity 
public class Customer {
    @Id
    private int id;
    private String name;

    @ElementCollection
    @CollectionTable(name="customer_addresses", joinColumns=@JoinColumn(name="customer_id"))
    @Column(name="address")
    private Set<String> addresses = new HashSet<>();
}
<set name="addresses">
    <key column="address"/>
    <element type="string"/> 
</set>