java JPA:如何映射 SQL Server 唯一标识符类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10451772/
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-31 01:05:39  来源:igfitidea点击:

JPA: how to map SQL Server uniqueidentifier type

javasql-serverhibernate

提问by George Armhold

I've inherited a SQL Server database that I'm trying to map via JPA. Many of the tables have a uniqueidentifiercolumn. I'm trying to map them like so:

我继承了一个试图通过 JPA 映射的 SQL Server 数据库。许多表都有一uniqueidentifier列。我试图像这样映射它们:

@Id
@GenericGenerator(name = "generator", strategy = "guid", parameters = {})
@GeneratedValue(generator = "generator")
@Column(name = "APPLICATION_ID")
private String id;

Hibernate complains with:

Hibernate 抱怨:

Found: uniqueidentifier, expected: varchar(255)

回答by Ken Chan

The data type of the primary key property in the POJO determines the data type of its mapped DB column, which is specified by the Dialectclass. According to the SQLServerDialectprovided by hibernate, it does not have any data type that maps to uniqueidentifier, and Stringby default maps to varchar(255)

POJO 中主键属性的数据类型决定了其映射的 DB 列的数据类型,由Dialect类指定。按照SQLServerDialect由Hibernate提供,它不具有任何数据类型映射到uniqueidentifier,并且String在默认情况下映射到varchar(255)

I think guidstrategy on a Stringprimary key only means that hibernate will generate a GUID value for POJO's primary key property and this generated GUID value will be inserted to the varchar(255)column to simulate the effect of uniqueidentifier

我认为 guidString主键的策略仅意味着 hibernate 将为 POJO 的主键属性生成一个 GUID 值,并且这个生成的 GUID 值将插入到varchar(255)列中以模拟uniqueidentifier

You can try to override the mapping specified by the Dialectclass by using the columnDefinitionattribute of @Column

您可以尝试使用的columnDefinition属性覆盖由方言类指定的映射@Column

 @Id
 @GenericGenerator(name = "generator", strategy = "guid", parameters = {})
 @GeneratedValue(generator = "generator")
 @Column(name = "APPLICATION_ID" , columnDefinition="uniqueidentifier")
 private String id;