我有一个方法应该对来自RestController的对象执行持久化操作,但在此之前它应该确保Object名称是唯一的,所以我试图使用.exists(Predicate谓词)方法在春天CrudRepository类。
但我不知道如何创建这个谓词对象,它通常直接从请求URL传递给JPA,我需要知道在代码中创建谓词的语法是什么。
这是我的restController
@RestController("MyObjectRestController")
@RequestMapping(value = "/v1.0/myObject", produces = "application/json")
public class MyObjectRestController extends BaseRestController<MyObject> {
@Autowired
private MyObjectService service;
public ResponseEntity<?> save(@RequestBody MyObject body)
throws NotFoundException {
return service.saveNew(body);
}
}
这是MyObjectService类,我想在调用save方法之前使用exists(Preidicate)。
@Service
public class MyObjectService extends BaseService<MyObject> {
@Autowired
private MyObjectRepository repository;
public Long saveNew(MyObject work){
if(repository.exists(predicateObject )) // here is my problem
System.out.println("This name exists, can't save your object");
return work.getId();
}
}
我的存储库继承自CrudRepository
@Repository
public interface MyObjectRepository extends BaseRepository<MyObject> {
public MyObject findByName(String name);
}
BaseRepository
@NoRepositoryBean
public interface BaseRepository<S extends BaseEntity> extends PagingAndSortingRepository<S, Long>, QueryDslPredicateExecutor<S>
{
}
答案 0 :(得分:0)
您可以创建这样的谓词:
Predicate isDigit = c - &gt; Character.isDigit(c);