Spring JPA TableGenerator中存在奇怪的验证冲突



我有一个遗留数据库,表project中有复合主键。(BaseEntity包含lastModifiedDate和lastModifiedBy的通用属性(

@Entity
@IdClass(ProjectPk.class)
public class Project extends BaseEntity {
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="nextProjectId")
@TableGenerator(
name="nextProjectId",
table="projectId",
pkColumnName = "proj_Id",
pkColumnValue="proj_id"
)
private Long  projId;
@Id
private int version;
//other properties, getters and setters omitted for clarity
}

PK类

public class ProjectPk implements java.io.Serializable {
private int  projId;
private int  version;
//both constructoirs, equals, hashcode, getters and setters omitted for clarity
}
  • 我有flyway迁移文件来模拟生产数据库
drop table if exists project;
CREATE TABLE project
(
proj_id             bigint,
version             int,
-- other columns omitted for clarity
PRIMARY KEY (`proj_id`, `version`)
) ENGINE=InnoDB;
drop table if exists project_id;
CREATE TABLE project_id
(
proj_id             bigint
) ENGINE=InnoDB;
  • flyway按照迁移文件中的顺序创建表
Table: project_id
Columns:
proj_id bigint
...

Table: project
Columns:
proj_id bigint PK 
version int PK
...

在maven构建过程中,我收到了验证错误

  • Schema-validation: wrong column type encountered in column [proj_id] in table [project_id]; found [bigint (Types#BIGINT)], but expecting [varchar(255) (Types#VARCHAR)]

我做错了什么让hibernate期望[varchar(255) (Types#VARCHAR)]

这是SpringBoot项目2.6.6与MySql数据库

我发现您的代码存在以下问题:

  1. Project.projId(Long类型(和ProjectPk.projId(int类型(之间的类型不匹配
  2. project_id表使用了错误的表结构

您可以在下面看到一个工作示例。

假设您有以下表格:

CREATE TABLE test_project
(
proj_id   bigint,
version   int,
title     VARCHAR(50),

PRIMARY KEY (proj_id, version)
);
create table table_identifier (
table_name varchar(255) not null,
product_id bigint,
primary key (table_name)
);
insert into table_identifier values ('test_project', 20);

以及以下映射:

@Entity
@Table(name = "test_project")
@IdClass(ProjectPk.class)
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "nextProjectId")
@TableGenerator(
name="nextProjectId",
table="table_identifier",
pkColumnName = "table_name",
valueColumnName="product_id",
allocationSize = 5
)
@Column(name = "proj_id")
private Long  projId;
@Id
private int version;
// other fields, getters, setters ...
}

您将能够持久化如下实体:

Project project = new Project();
project.setVersion(1);
// ...
entityManager.persist(project);

最新更新