How to use @SecondaryTable with CrudRepository?

2019-09-12 13:16发布

I'm using SecondaryTable to map bean schema to multiple tables:

@Entity
@Table(name = "address1")
@SecondaryTables({
    @SecondaryTable(name="address2")
})

How an I then tell spring to create a Repository that uses the values from table address2?

interface AddressRepository extends CrudRepository<Address, Long> {
    //this one uses address1
}

I then want to be able to query only the secondary table by the CrudRepository. But how can I explicit tell spring to query the address2 table using the AddressRepository above?

(think of address2-table as a kind of archive table. Only if the address is not found in the primary address1-table, then address2 should be queried).

2条回答
狗以群分
2楼-- · 2019-09-12 13:49

You can represent two tables which are store different but related data in one entity by using SecondaryTable like user and user_address tables. What You are trying is storing same data in two different tables whhich are identically same. Therefore, SecondaryTable doesn't fit your needs. You should use inheritance annotation with strategy table per class. Here is an example;

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class AddressBase {
    ...
    ...
    ...
}

@Entity
@Table(name='address1')
public class Address1 extends AddressBase {}

@Entity
@Table(name='address2')
public class Address2 extends AddressBase {}

Then, you can write repository for each entity and do whatever you want.

查看更多
Root(大扎)
3楼-- · 2019-09-12 13:50

I think you are misunderstanding what @SecondaryTable is for. It is a way to split a single entity among different database tables.

From the docs (http://docs.oracle.com/javaee/7/api/javax/persistence/SecondaryTable.html)

Specifies a secondary table for the annotated entity class. Specifying one or more secondary tables indicates that the data for the entity class is stored across multiple tables. If no SecondaryTable annotation is specified, it is assumed that all persistent fields or properties of the entity are mapped to the primary table. If no primary key join columns are specified, the join columns are assumed to reference the primary key columns of the primary table, and have the same names and types as the referenced primary key columns of the primary table.

Your annotations, in their current state, say that there exists an Address entity, with data in the address1 and address2 table, which can be combined by joining on the primary key of the address1 table.

I think for what you want to do, and have it work without overriding your CrudRepository, is to just use different tables. You will need to query both tables anyway if I am understanding you correctly.

查看更多
登录 后发表回答