这不是BUG!这是 DDL 生成模式的默认行为。我将向您解释常见的可能情况:
1st case
:您之前没有在数据库上创建表
当您第一次构建应用程序时不使用现有表,我认为您之前遇到的问题不会发生(只要您使用默认配置值并将应用程序设置为 DEV 模式)。直截了当,假设您有 2 个像以前一样的模型:
@Entity
public class Userr extends Model {
@Id
public Long id;
public String realName;
@OneToMany
List<Badge> badges;
}
@Entity
public class Badge extends Model {
@Id
public Long id;
@ManyToOne
Userr user;
}
在您运行应用程序时,简单的框架应该告诉 DDL 生成模式查看您连接的数据库并查找是否存在名为userr
and的表badge
。因为您之前没有创建过这两个表,所以框架会在您的数据库上自动生成这两个表。根据您的模型,框架将使用类似于 (PostgreSQL script) 的脚本生成您的表:
-- the java class name is 'Userr' generated as 'userr'
CREATE TABLE userr {
-- long on java generated as bigint
id bigint,
-- 'realName' on java generated as 'realname' and string on java generated as varchar whose length 255
realname character varying(255),
-- one to many 'badges' field is not generated
CONSTRAINT pk_userr PRIMARY KEY (id), -- id as primary key
}
-- the java class name is 'Badge' generated as 'badge'
CREATE TABLE badge {
id bigint,
-- 'Userr' Object with MayToOne relation generated as the foreign key to the id on 'userr' table
userr_id bigint,
CONSTRAINT pk_badge PRIMARY KEY (id),
CONSTRAINT fk_badge_userr FOREIGN KEY (userr_id)
REFERENCES userr (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
}
2nd case
:您在数据库上有现有表
假设您之前有 2 个名称为user_account
和的表badge
。该user_account
表如下所示:
CREATE TABLE user_account {
id bigint,
real_name character varying(100),
CONSTRAINT pk_userr PRIMARY KEY (id),
}
CREATE TABLE badge {
id bigint,
user_id bigint,
CONSTRAINT pk_badge PRIMARY KEY (id),
CONSTRAINT fk_badge_user_account FOREIGN KEY (user_id)
REFERENCES user_account (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
}
您可以使用以下代码正确使用以前的模型(经过一些修改)来处理当前表:
@javax.persistence.Entity
// define this model as table named 'user_account'
@javax.persistence.Table(name = "user_account")
public class Userr extends Model {
@Id
public Long id;
// define this field as column named 'real_name' whose length is 100
@javax.persistence.Column(name = "real_name", length = 100)
public String realName;
@OneToMany
List<Badge> badges;
}
@javax.persistence.Entity
public class Badge extends Model {
@Id
public Long id;
@ManyToOne
// define this field as column named 'user_id' and
// this act as reference to model 'Userr' using field named 'id' on it
@javax.persistence.JoinColumn(name = "user_id", referencedColumnName = "id")
Userr user;
}
希望这可以帮助您更好地理解 DDL 生成模式.. :)