如何将 @SecondaryTable 与 CrudRepository 一起使用?

How to use @SecondaryTable with CrudRepository?

我正在使用 SecondaryTable 将 bean 模式映射到多个 table:

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

然后我如何告诉 spring 创建一个 Repository 使用来自 table address2 的值?

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

然后我希望能够通过 CrudRepository 仅查询 辅助 table。但是我怎样才能明确告诉 spring 使用上面的 AddressRepository 查询 address2 table?

(把address2-table看成是一种存档table。只有在主address1-table中找不到地址,才应该查询address2) .

我认为您误解了 @SecondaryTable 的用途。这是一种在不同数据库 table 之间拆分单个实体的方法。

来自文档 (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.

您的注释在当前状态下表示存在一个 Address 实体,数据在 address1address2 table 中,可以合并通过加入 address1 table.

的主键

我认为对于你想做的事情,并且让它在不覆盖你的 CrudRepository 的情况下工作,就是使用不同的 table。如果我理解正确的话,无论如何你都需要查询两个 tables。

您可以使用 SecondaryTable 表示两个 table,它们在一个实体中存储不同但相关的数据,例如用户和 user_address table。您正在尝试的是将相同的数据存储在两个完全相同的不同 table 中。因此,SecondaryTable 不符合您的需求。您应该将继承注释与策略 table per class 一起使用。这是一个例子;

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

然后,您可以为每个实体编写存储库,并为所欲为。