简体   繁体   中英

Saving same entity in different tables(same schema) using Jpa

I've using spring data JPA repositories to save the data into my tables.

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.

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? 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.

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 :

@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:

    @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> {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM