我正在尝试为购买构建简单的REST,我需要2种方法。第一种方法应显示按日期排序的所有购买。第二个删除指定日期的所有购买,我做了一个添加和获取所有购买的方法。现在我被卡住了。
@Entity
@Table (name="purchase")
public class Purchase {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@CreationTimestamp
@Temporal(TemporalType.DATE)
@Column(name="createat")
private Date created;
@Column(name="price")
private BigDecimal price;
@Column(name="currency")
private String currency;
@Repository
public interface PurchaseRepository extends JpaRepository<Purchase, Long>
{
}
@Service
public class PurchaseService {
@Autowired
private PurchaseRepository purchaseRepository;
public void addPurchase(Purchase purchase) {
purchaseRepository.save(purchase);
}
public List<Purchase> getAllPurchase() {
List<Purchase> purchase = new ArrayList<>();
purchaseRepository.findAll().forEach(purchase::add);
return purchase;
}
}
@RestController
public class PurchaseController {
@Autowired
private PurchaseService purchaseService;
@PostMapping("/purchase")
public void addPurchase(@RequestBody Purchase purchase) {
purchaseService.addPurchase(purchase);
}
@RequestMapping("/purchase")
public List<Purchase> getAllTopics() {
return purchaseService.getAllPurchase();
}
}
我需要什么: 1.按日期排序我的列表的方法 2.删除指定日期所有购买的方法
答案 0 :(得分:0)
在这些情况下,您可以使用Spring Data JPA功能。
将以下方法添加到PurchaseRepository:
List<Purchase> findAllByOrderByCreatedAsc();
long deleteByCreated(Date created);
毕竟,Spring将基于方法名称生成适当的查询。
答案 1 :(得分:0)
我明白了
long deleteByCreated(Date date);
@Transactional
public long deleteAllByDate(Date date){
return purchaseRepository.deleteByCreated(date);
}
@RequestMapping(method=RequestMethod.DELETE, value="/purchasess/{date}")
public long findAllByCreatedBetween(@DateTimeFormat(pattern="yyyy-MM-dd")
@PathVariable Date date){
return purchaseService.deleteAllByDate(date);
}