您好,我有一个任务是使用Spring Boot和Hibernate构建应用程序。事情是我正在通过data.sql文件构建数据库以保留数据并创建数据库。现在,我需要在两个表之间创建一个关系表。考虑到工作人员可以拥有用户帐户或可能没有帐户,这应该是一对多的关系。问题在于应用程序启动时如何构建此关系表,因为引用应该是我在启动时没有的外键 user_id 和 worker_id 会自动进入休眠状态,因此无法对其进行硬编码。因此,问题是我将如何从data.sql创建此关系芯片表。
data.sql:
INSERT INTO worker (name, last_name, status) VALUES
('manuel', 'dias', 'active'),
('sailin ', 'nal', 'active'),
('abraham', 'lincon', 'active'),
('mick', 'smith', 'active'),
('jose', 'perez', 'inactive'),
('luis', 'nuñez', 'inactive'),
('ruben', 'puertas', 'inactive'),
('anders', 'stone', 'inactive'),
('luis', 'alvarez', 'deleted'),
('claudio', 'martinez', 'deleted'),
('morfeo', 'rodriguez', 'active'),
('onetys', 'estrada', 'inactive'),
('rene', 'fajardo', 'active');
INSERT INTO users (username, password, user_type, status) VALUES
('madi', 'madi', 'worker', 'active'),
('sana', 'sana', 'worker', 'active'),
('abli', 'abli', 'worker', 'active'),
('mism', 'mism', 'worker', 'active'),
('jope', 'jope', 'worker', 'active'),
('lunu', 'lunu', 'worker', 'active'),
('rupu', 'rupu', 'worker', 'active'),
('anst', 'anst', 'worker', 'active'),
('lual', 'lual', 'worker', 'active'),
('clma', 'clma', 'worker', 'active');
Users.class:
@Entity
@Table(name = "users")
public class Users implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id", nullable = false)
private int userId;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "userType")
private String userType;
@Column(name = "status")
private String status;
@ManyToOne
@JoinColumn(name = "worker_id")
private Worker worker;
Worker.class:
@Entity
@Table(name = "worker")
public class Worker implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "worker_id")
private int workerId;
@Column(name = "name")
private String name;
@Column(name = "last_name")
private String lastName;
@Column(name = "status")
private String status;
@OneToMany(mappedBy = "worker", cascade = CascadeType.ALL)
private Collection<Users> users;
所以我必须:
1::是否要创建另一个实体,以便能够在数据库中创建一个包含用户和工作人员外键的新表?
2 :可以使用data.sql中的脚本来完成此操作。
我会在users表中创建一个引用worker ID的列,但任务明确指出:
“创建第三个表来保存关系”
预先感谢
答案 0 :(得分:1)
在OneToMany关系中,您可以在多面实体上拥有所有需要的信息。创建另一个联接表仅对ManyToMany关系有意义,只会在OneToMany上添加冗余数据,并且违反了normalization。
也就是说,如果您确实需要另一个表来定义两个实体的关系,则无需使用@JoinTable
创建另一个实体就可以实现此目的。
@Entity
@Table(name = "users")
public class Users implements Serializable {
//....
@ManyToOne
@JoinTable(name = "worker_users",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "worker_id"))
private Worker worker;
}
@Entity
@Table(name = "worker")
public class Worker implements Serializable {
//...
@OneToMany(cascade = CascadeType.ALL) //remove mappedBy
@JoinTable(name = "worker_users",
joinColumns = @JoinColumn(name = "worker_id"),
inverseJoinColumns = @JoinColumn(name = "user_id"))
private Collection<Users> users;
}
它将使用此结构创建新的worker_user
表
|WORKER_ID |USER_ID |