本文介绍了如何将@SecondaryTable 与 CrudRepository 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

然后我如何告诉 spring 创建一个 Repository 使用表 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
}

然后我希望能够通过 CrudRepository 仅查询辅助表.但是我如何明确告诉 spring 使用上面的 AddressRepository 查询 address2 表?

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?

(把address2-table看作是一种归档表.只有在主address1-table中没有找到地址,才应该查询address2).

(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).

推荐答案

您可以使用像 user 和 user_address 表一样的 SecondaryTable 来表示在一个实体中存储不同但相关数据的两个表.您正在尝试将相同的数据存储在两个完全相同的不同表中.因此, SecondaryTable 不符合您的需求.您应该将继承注释与每个类的策略表一起使用.这是一个例子;

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.

这篇关于如何将@SecondaryTable 与 CrudRepository 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 06:16