我公开了一个端点,客户端在该端点上调用请求以启动Spring Batch作业。
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private MyProcessor processor;
@PostMapping(value = "/runJob", consumes = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity<MyResponse> runJob(@Valid @RequestBody MyRequest request) {
//persist the request using Spring JPA
String requestTrackingId = UUID.randomUUID().toString()
MyResponse response = processor.process(request, requestTrackingId); //run spring batch job and create response
return new ResponseEntity<>(response, CREATED);
}
}
请求包括名称和其他一些参数:
public class MyRequest {
private String name;
private String runDate;
private boolean rerun;
}
我需要使用Spring JPA将http作业运行请求持久保存在表中。该表应保留请求数据以及唯一ID,以便可以对其进行跟踪,还应该捕获作业状态,以便客户端可以使用跟踪ID对其进行查询。
我需要有关JPA实施的帮助,包括创建实体并在请求到达端点时将请求持久保存到表中。实现将是什么样的?表格上的ID应该是跟踪ID。
如果您想要更复杂的答案,请提供其他信息。
一种可能的实现方式:
模型
@Entity
@Table
public class RequestData{
@Id
@Column(name = "id", nullable = false, unique = true, updatable = false, length = 32)
private String id; // = IdGenerator.generateId(); #use it if you want to get the id from the object, and not set it.
@Basic
private String name;
@Basic
private String runDate;
@Basic
private Boolean rerun;
//[getters/setters] here
}
存储库界面
public interface RequestDataRepository extends JpaRepository<RequestData, String>{}
现在您可以将邮局注入到您的控制器中并保存请求:
@Autowired
private RequestDataRepository repository;
@PostMapping(value = "/runJob", consumes = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity<MyResponse> runJob(@Valid @RequestBody MyRequest request) {
String uniqueId=IdGenerator.generateId()
RequestData requestData=new RequestData();
requestData.setId(uniqueId);
requestData.setName(request.getName())
.... //other fields setters (except id)
repository.save(requestData)
//alternativelly get the id from the object, then you do not need to create id here, but in the RequestData object
//String uniqueId=requestData.getId();
[...]
}
UUID生成器
public final class IdGenerator {
private static org.springframework.util.IdGenerator idGenerator = new AlternativeJdkIdGenerator();
private IdGenerator() {
throw new UnsupportedOperationException("IdGenerator is an utility class");
}
public static String generateId() {
return idGenerator.generateId().toString().replaceAll("-", "");
}
}