如何选择Spring @Query注释以适应数据库(例如HSQLDB,Postgres)?

时间:2017-09-22 15:50:34

标签: spring-data-jpa

说我有这个带注释的Java代码:

'%...

这适用于Postgres。但是,在运行单元测试时,我想使用内存数据库,如HSQLDB。不幸的是,SQL date(...)命令对HSQLDB不起作用,所以我真的需要根据数据库更改查询的内容,如下所示,我编写了一个虚构的“db =”标记:

@Transactional
public interface EventRepository extends JpaRepository<Event, Long> {

@Query("from Event where path like ?1% and date(start_time)=CURRENT_DATE")
Stream<Event> findAllChildrenToday(String path);

我该如何做到这一点?

我对Spring不太熟悉,所以请在答案中详细说明。感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用Spring profiles制作以下技巧:

@NoRepositoryBean
public interface EventRepo extends JpaRepository<Event, Long> {
    Stream<Event> findAllChildrenToday(String path);
}

@Profile("postgres")
public interface PostgresRepo extends EventRepo {
    @Override 
    @Query(/* a postgres specific query */)
    Stream<Event> findAllChildrenToday(String path);
}

@Profile("hsqldb")
public interface HsqldbRepo extends EventRepo {
    @Override
    @Query(/* a hsqldb specific query */)
    Stream<Event> findAllChildrenToday(String path);
}

然后在您的服务(或控制器)中:

@Service
public class EventService {

    @Autowired
    private EventRepo eventRepo;

    //...
}

在您设置的application.properties文件中&#39; postgres&#39;配置文件(默认情况下将在生产中使用此配置文件):

spring.profiles.active=postgres

在你的IDE中设置&#39; hsqldb&#39; profile:-Dspring.profiles.active=hsqldb(作为JVM选项)。

由于这个原因,回购注入将取决于使用的Spring配置文件。