标签: spring-data

如何使用Spring Data Rest和PagingAndSortingRepository处理异常?

假设我有一个类似的存储库:

public interface MyRepository extends PagingAndSortingRepository<MyEntity, String> {

    @Query("....")
    Page<MyEntity> findByCustomField(@Param("customField") String customField, Pageable pageable);
}
Run Code Online (Sandbox Code Playgroud)

这非常有效.但是,如果客户端发送已形成的请求(例如,搜索不存在的字段),则Spring将异常作为JSON返回.揭示@Query等等

// This is OK
http://example.com/data-rest/search/findByCustomField?customField=ABC

// This is also OK because "secondField" is a valid column and is mapped via the Query
http://example.com/data-rest/search/findByCustomField?customField=ABC&sort=secondField

// This throws an exception and sends the exception to the client
http://example.com/data-rest/search/findByCustomField?customField=ABC&sort=blahblah
Run Code Online (Sandbox Code Playgroud)

抛出并发送给客户端的异常示例:

{
    message:null,
    cause: {
        message: 'org.hibernate.QueryException: could not resolve property: blahblah...'
    }
}
Run Code Online (Sandbox Code Playgroud)

我该如何处理这些例外情况?通常,我使用的@ExceptionHandler是我的MVC控制器,但我没有使用Data Rest API和客户端之间的层.我是不是该?

谢谢.

java exception-handling spring-data spring-data-jpa spring-data-rest

12
推荐指数
1
解决办法
2917
查看次数

如何将Spring Boot @RepositoryRestResource映射到特定URL?

我似乎无法在以下任何位置映射我的存储库:

@RepositoryRestResource(collectionResourceRel = "item", path = "item")
public interface ItemRepository extends PagingAndSortingRepository<Item, Long> {
Run Code Online (Sandbox Code Playgroud)

我以为我可以用:

 path = "/some/other/path/item"
Run Code Online (Sandbox Code Playgroud)

但映射无法解决.我明白了:

HTTP ERROR 404

Problem accessing /some/other/path/item. Reason:

Not Found
Run Code Online (Sandbox Code Playgroud)

在spring-data中,javadoc path定义为:"用于导出此资源的路径段."

我究竟做错了什么?

java configuration spring spring-data spring-boot

12
推荐指数
4
解决办法
9471
查看次数

资源注释:没有定义[javax.sql.DataSource]类型的限定bean:期望的单个匹配bean但找到2

我使用基于Spring Java的配置来配置Spring Data的多个数据库.在配置文件中,我正在创建两个data sourcefor MySQLMSSQL-Server.当尝试使用@Resource注释向实体管理器注入依赖项时,我遇到以下异常:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] is defined: expected single matching bean but found 2: mysql_datasource,secure_datasource
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1016)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:904)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:815)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:743)
Run Code Online (Sandbox Code Playgroud)

以下是我的代码:

@Bean(name="secure_datasource")
public DataSource dataSource(){
    try{
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setJdbcUrl(environment.getProperty("sc.db.url"));
        dataSource.setDriverClass(environment.getProperty("sc.db.driver.class"));
        dataSource.setUser(environment.getProperty("sc.db.username"));
        dataSource.setPassword(environment.getProperty("sc.db.password"));
        dataSource.setIdleConnectionTestPeriod(60);
        dataSource.setMaxPoolSize(10);
        dataSource.setMaxStatements(7);
        dataSource.setMinPoolSize(1);
        return dataSource; 
    }catch(Exception ex){
        throw new RuntimeException(ex);
    }
}

.................

@Bean(name="mysql_datasource")
public DataSource dataSource(){
    try{
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setJdbcUrl(environment.getProperty("db.url"));
        dataSource.setDriverClass(environment.getProperty("db.driver.class"));
        dataSource.setUser(environment.getProperty("db.username"));
        dataSource.setPassword(environment.getProperty("db.password")); …
Run Code Online (Sandbox Code Playgroud)

dependency-injection exception spring-data

12
推荐指数
3
解决办法
2万
查看次数

Spring 4中的@PathVariable验证

如何在spring中验证我的路径变量.我想验证id字段,因为它只有单个字段我不想移动到Pojo

@RestController
public class MyController {
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity method_name(@PathVariable String id) {
        /// Some code
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试在路径变量中添加验证,但它仍然无效

    @RestController
    @Validated
public class MyController {
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity method_name(
            @Valid 
            @Nonnull  
            @Size(max = 2, min = 1, message = "name should have between 1 and 10 characters") 
            @PathVariable String id) {
    /// Some code
    }
}
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-security spring-data spring-boot

12
推荐指数
1
解决办法
2万
查看次数

如何解决Timeout FeignClient

使用在SQL Server中执行查询的服务时,我的应用程序遇到错误FeignClient.

错误:

线程"pool-10-thread-14"中的异常feign.RetryableException:读取超时执行GET http://127.0.0.1:8876/processoData/search/buscaProcessoPorCliente?cliente=ELEKTRO+-+TRABALHISTA&estado=SP

我的消费者服务:

@FeignClient(url="http://127.0.0.1:8876")
public interface ProcessoConsumer {

@RequestMapping(method = RequestMethod.GET, value = "/processoData/search/buscaProcessoPorCliente?cliente={cliente}&estado={estado}")
public PagedResources<ProcessoDTO> buscaProcessoClienteEstado(@PathVariable("cliente") String cliente, @PathVariable("estado") String estado);

}
Run Code Online (Sandbox Code Playgroud)

我的YML:

server:
  port: 8874

endpoints:
  restart:
    enabled: true
  shutdown:
    enabled: true
  health:
    sensitive: false

eureka:
  client:
  serviceUrl:
    defaultZone: ${vcap.services.eureka-service.credentials.uri:http://xxx.xx.xxx.xx:8764}/eureka/
  instance: 
    preferIpAddress: true

ribbon:
  eureka:
    enabled: true

spring:
  application:
    name: MyApplication
  data:
    mongodb:
      host: xxx.xx.xxx.xx
      port: 27017
      uri: mongodb://xxx.xx.xxx.xx/recortesExtrator
      repositories.enabled: true
    solr:
      host: http://xxx.xx.xxx.xx:8983/solr
      repositories.enabled: true
Run Code Online (Sandbox Code Playgroud)

有谁知道如何解决这个问题?

谢谢.

java spring-data spring-boot netflix-feign

12
推荐指数
4
解决办法
3万
查看次数

在Spring Data MongoDB for ZonedDateTime中注册一个可审计的新Date Converter

我希望我的可审计(@CreatedDate@LastModifiedDate)MongoDB文档可以使用ZonedDateTime字段.

显然,Spring Data不支持这种类型(请看一下org.springframework.data.auditing.AnnotationAuditingMetadata).

框架版本:Spring Boot 2.0.0Spring Data MongoDB 2.0.0

Spring Data审核错误:

java.lang.IllegalArgumentException: Invalid date type for member <MEMBER NAME>!
Supported types are [org.joda.time.DateTime, org.joda.time.LocalDateTime, java.util.Date, java.lang.Long, long].
Run Code Online (Sandbox Code Playgroud)

Mongo配置:

@Configuration
@EnableMongoAuditing
public class MongoConfiguration {

}
Run Code Online (Sandbox Code Playgroud)

可审计实体:

public abstract class BaseDocument {

    @CreatedDate
    private ZonedDateTime createdDate;

    @LastModifiedDate
    private ZonedDateTime lastModifiedDate;

}
Run Code Online (Sandbox Code Playgroud)

我试过的事情

我也试过为ZonedDateTime它创建一个自定义转换器,但Spring Data没有考虑它.该类DateConvertingAuditableBeanWrapper有一个ConversionService在构造函数方法中配置的JodaTimeConverters,Jsr310ConvertersThreeTenBackPortConverters.

定制转换器:

@Component
public class …
Run Code Online (Sandbox Code Playgroud)

java spring-data spring-data-mongodb

12
推荐指数
1
解决办法
2717
查看次数

Spring Data Page没有正确地序列化排序为JSON

此问题出现在Spring-Data发行版2中.在最新版本1.13.9(及更早版本)中,它运行正常.

控制器代码:

@RestController
public class HelloController {

    @RequestMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }

    @RequestMapping(value = "sorttest", method = RequestMethod.GET)
    public Page<Integer> getDummy() {
        return new PageImpl<>(Collections.singletonList(1), new PageRequest(0, 5, new Sort("asdf")), 1);
    }

}
Run Code Online (Sandbox Code Playgroud)

Spring-Data 2风格相同:

Pageable pageable = PageRequest.of(0, 10, new Sort(Sort.Direction.ASC, "asd"));
PageImpl<Integer> page = new PageImpl<Integer>(Lists.newArrayList(1,2,3), pageable, 3);
return page;
Run Code Online (Sandbox Code Playgroud)

组态:

@SpringBootApplication
@EnableWebMvc
@EnableSpringDataWebSupport
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

还尝试了简单的Spring应用程序,没有带有Java配置的Spring Boot以及XML配置.结果是一样的:

{
    "content": …
Run Code Online (Sandbox Code Playgroud)

spring-data spring-data-commons spring-config

12
推荐指数
2
解决办法
3327
查看次数

使用外部属性文件配置的表名

我构建了一个访问数据库并从中提取数据的 Spring-Boot 应用程序。一切正常,但我想从外部 .properties 文件配置表名。

喜欢:

@Entity
@Table(name = "${fleet.table.name}")
public class Fleet {
...
}
Run Code Online (Sandbox Code Playgroud)

我试图找到一些东西,但我没有。

您可以使用@Value("...")注释访问外部属性。

所以我的问题是:有什么办法可以配置表名?或者我可以更改/拦截休眠发送的查询吗?

解决方案:

好的,hibernate 5 与PhysicalNamingStrategy. 所以我创建了自己的PhysicalNamingStrategy.

@Configuration 
public class TableNameConfig{

    @Value("${fleet.table.name}")
    private String fleetTableName;

    @Value("${visits.table.name}")
    private String visitsTableName;

    @Value("${route.table.name}")
    private String routeTableName;

    @Bean
    public PhysicalNamingStrategyStandardImpl physicalNamingStrategyStandard(){
        return new PhysicalNamingImpl();
    }

class PhysicalNamingImpl extends PhysicalNamingStrategyStandardImpl {

    @Override
    public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
        switch (name.getText()) {
            case "Fleet":
                return new Identifier(fleetTableName, name.isQuoted());
            case "Visits":
                return new …
Run Code Online (Sandbox Code Playgroud)

spring spring-data

12
推荐指数
1
解决办法
6160
查看次数

使用Spring CrudRepository时"不等于"条件

我应该如何构建我的findBy方法名称,以便我可以实现where子句 -

statusCode != 'Denied'
Run Code Online (Sandbox Code Playgroud)

这是一个选择吗?

findByStatusCodeNotIn(List<String> statusCode);
Run Code Online (Sandbox Code Playgroud)

如果我只想传递一个String而不是一个列表怎么办?

谢谢

spring-data spring-data-jpa

12
推荐指数
3
解决办法
1万
查看次数

跨两个数据源的事务管理(ChainedTransactionManager)-SpringBoot

为什么 SpringChainedTransactionManager被弃用了?Spring 是否提供任何替代库来支持多个事务管理器?

我的用例:- 我们正在构建一个连接到两个数据源(db1 和 db2)的 Spring Boot 应用程序,它对两个数据库(db1 和 db2)执行插入操作。我们的要求是这样的:插入 -> DB1 -> 成功插入 -> DB2 -> 错误回滚 DB1

目前,我们正在使用ChaninedTransactionManager并且它按预期工作,但我可以看到 lib 已被弃用。那么,只是想确保使用它是否安全,或者 Spring 是否提供了任何我们可以用来替代它的替代库?

spring spring-transactions spring-data spring-boot

12
推荐指数
2
解决办法
2万
查看次数