[英]Saving same entity in different tables(same schema) using Jpa
I've using spring data JPA repositories to save the data into my tables.我使用 spring 数据 JPA 存储库将数据保存到我的表中。
In one of the situation, I've to store data in two different tables.在一种情况下,我必须将数据存储在两个不同的表中。 These two tables have the exact same schema.
这两个表具有完全相同的架构。 But I can only store in one table as JpaRepository maps to just one table.
但是我只能存储在一张表中,因为 JpaRepository 只映射到一张表。
Example:例子:
@Entity
@Table(name="users")
class User {
private Long userId;
private String firstName;
private String lastName;
}
interface MyRepo1 extends JpaRepositories<User,Long> {
}
interface MyRepo2 extends JpaRepositories<User,Long> {
}
Is there a way to map a single entity into multiple JpaRepositories?有没有办法将单个实体映射到多个 JpaRepositories? So, when I call MyRepo1.save(user) it saves in Users table and when I call MyRepo2.save(user), it saves in BackupUsers(exact same schema as Users) table.
因此,当我调用 MyRepo1.save(user) 时,它保存在 Users 表中,当我调用 MyRepo2.save(user) 时,它保存在 BackupUsers(与用户完全相同的架构)表中。
Thanks谢谢
You should have two different entities, for instance, User entity AppUser entity, each one of them pointing to the different tables like this, assuming that the two table names are users
and app_users
:您应该有两个不同的实体,例如 User 实体 AppUser 实体,每个实体都指向不同的表,如下所示,假设两个表名是
users
和app_users
:
@Entity
@Table(name="users")
public class User extends SuperUser {...}
and和
@Entity
@Table(name="app_users")
public class AppUser extends SuperClass {...}
Of course, to avoid code duplication you can put your table fields in a superclass named SuperClass
, for example:当然,为了避免代码重复,您可以将表字段放在名为
SuperClass
的超类中,例如:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class SuperUser {
@Id
private Long userId;
private String firstName;
private String lastName;
// getters and setters, constructors
}
After, you need to create two repositories for each entity class:之后,您需要为每个实体类创建两个存储库:
public interface UserRepository extends JpaRepositories<User, Long> {
}
public interface AppUserRepository extends JpaRepositories<AppUser,Long> {
}
NOTE: To finish, it's not recommended at all to have two tables that hold the same fields.注意:最后,完全不建议拥有两个包含相同字段的表。
I don't think you can save in different tables with two different repositories, because you can't specify the table name in repository, but in the entity, I would suggest to use :我不认为你可以用两个不同的存储库保存在不同的表中,因为你不能在存储库中指定表名,但在实体中,我建议使用:
// class which hold common fields
class User {
private Long userId;
private String firstName;
private String lastName;
}
// entity for table 1
@Entity
@Table(name="table1")
class User1 extends User {}
// entity for table 1
@Entity
@Table(name="table2")
class User2 extends User {}
// repo for entity 1
interface MyRepo1 extends JpaRepositories<User1,Long> {}
// repo for entity 2
interface MyRepo2 extends JpaRepositories<User2 ,Long> {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.