gpt4 book ai didi

java - 如何在 Spring Boot 中扩展类而不更改 MySQL 架构?

转载 作者:行者123 更新时间:2023-11-29 06:27:56 24 4
gpt4 key购买 nike

例如,我有 User 类,如下所示:

    @Entity
@Table(name = "users")
public class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@NotBlank
@Size(max = 40)
@Column(name = "name")
private String name;

@NotBlank
@Size(max = 15)
@Column(name = "username")
private String username;

@NaturalId
@NotBlank
@Size(max = 40)
@Email
@Column(name = "email")
private String email;

@NotBlank
@Size(max = 100)
@Column(name = "password")
private String password;

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();

//Constructor
//Getters and Setters

我有 Client 类:

@Entity
@Table(name = "cliente")
public class Cliente {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "empresa")
private String empresa;
@Column(name = "telefono")
private Integer telefono;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(unique = true)
private Licencia licencia;

@OneToMany(cascade = {
CascadeType.PERSIST,
CascadeType.REMOVE
} ,fetch = FetchType.EAGER)
@JoinTable(name = "user_cliente",
joinColumns = @JoinColumn(name = "cliente_id"),
inverseJoinColumns = @JoinColumn(name = "user_id"))
private Set<User> users = new HashSet<>();

public Cliente(String empresa, Integer telefono) {
this.empresa = empresa;
this.telefono = telefono;
}

//Constructor
//Getters and Setters

现在,我想要做的是 Client 类来扩展 User 类,这样我就可以添加一个包含名称、用户名、电子邮件等的 Client。但是我想要在 MySQL 中创建两个单独的表,一个用于用户及其表属性,以及其他仅针对客户的信息,例如电话或公司。问题是当我在 Client 类中扩展 User 类时,MySQL 数据库会更新并在 User 表中创建电话、公司等字段。我怎样才能避免这种情况?

最佳答案

使用@MappedSuperclass:

@MappedSuperclass
public class BaseEntity {
// here you can add common fields for your entities
}

然后从中扩展:

@Entity
public class User extends BaseEntity {
// user specific fields goes here
}

客户端:

@Entity
@Table(name = "cliente")
public class Cliente extends BaseEntity {
// client specific fields here
}

有关更多信息,请阅读 How to inherit properties from a base class entity using @MappedSuperclass with JPA and Hibernate

关于java - 如何在 Spring Boot 中扩展类而不更改 MySQL 架构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58399631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com