[英]How to create a bean remotely without changing the actual class in Spring Boot?
[英]How to extend a class in Spring Boot without changing the MySQL schema?
例如,我有用户 class,如下所示:
@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
我有客户 class:
@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
Now, what I want to do is the Client class to extends the User class, so I can add a Client with name, username, email, etc. But I want two separate tables in MySQL, one for the users and its attributes, and其他只为客户提供客户信息,如电话或公司。 问题是当我在客户端 class 中扩展用户 class 时,MySQL 数据库更新并在用户表中创建电话、公司等字段。 我怎样才能避免这种情况?
使用@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
}
和Client
:
@Entity
@Table(name = "cliente")
public class Cliente extends BaseEntity {
// client specific fields here
}
有关更多信息,请阅读如何使用带有 JPA 和 Hibernate 的 @MappedSuperclass 从基本 class 实体继承属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.