【问题标题】:Spring JPA to query same table across different schemasSpring JPA 跨不同模式查询同一张表
【发布时间】:2021-02-11 08:43:26
【问题描述】:

我正在对 Oracle 数据库使用 Spring JPA,我希望能够跨 2 个不同的模式/数据库(例如 db1.car 和 db2.car)查询同一个表。

我的域对象会非常标准,如下所示。有没有办法通过控制器将 schema/db 限定符传递给域对象,如果说我有一个 db1.car 表和一个和 db2.car 表?

@Entity
@Table(name = "car")
public class Car {
    ...
}

或者,有没有办法将限定的表名传递给命名查询?似乎不是,因为这似乎不起作用(即,“:qualifiedcar”会导致 Spring 自动装配错误):

public interface CarRepository extends JpaRepository<Person, String> {
    @Query("select p from :qualifiedcar p where p.type in (:type)")
    List<Person> findByQualifiedPersonAndType(@Param("qualifiedcar") String qualifiedcar, @Param("type") String type);
}

为了澄清,也许 Oracle 不使用术语 schema。将它们称为不同的数据库可能更准确。

【问题讨论】:

    标签: spring oracle jpa


    【解决方案1】:

    要在实体中指定架构,您必须执行以下操作:

    @Entity
    @Table(name = "car", schema = "db1")
    public class CarS1 {
        ...
    }
    
    @Entity
    @Table(name = "car", schema = "db2")
    public class CarS2 {
        ...
    }
    

    关于第二个问题,我会尝试如下使用程序化命名查询:

    String dinamicQuery = "Select * from ";
    String resultMapping = "";
    
    if (schema.equals("db1")){
        dinamicQuery = dinamicQuery + "table1 ";
        resultMapping = "test1"
    }else{
        dinamicQuery = dinamicQuery + "table2 ";
        resultMapping = "test2"
    }
    
    Query q = em.createNativeQuery(dinamicQuery,resultMapping);
    em.getEntityManagerFactory().addNamedQuery("selectDinamic", q);
    
    return em.createNamedQuery("selectDinamic",Piloto.class).getResultList();
    

    resultMapping 在实体中定义,是获取查询中格式化的对象所必需的

    @SqlResultSetMappings({
        @SqlResultSetMapping(name="test1",
        classes = {
            @ConstructorResult(
                targetClass = Cars1.class,
                columns = {
                    @ColumnResult(name = "id", type = Long.class),
                    [...]
            })
        })
    })
    @Entity
    @Table(name = "car", schema = "db1")
    public class CarS1 {
        [...]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-04
      • 2021-01-06
      • 2017-11-06
      • 1970-01-01
      • 2021-11-15
      • 2016-09-25
      • 2017-06-11
      • 2011-01-14
      相关资源
      最近更新 更多