OrderCancelService 與 NotificationService 來存取使用者的通知訊息!create table notification(
id varchar(100) not null primary key,
user_id varchar(100) not null,
msg varchar(100) not null,
is_read tinyint(1) default 0 not null,
create_time timestamp not null,
constraint fk_userid_notification
foreign key (user_id)
references users (id)
on delete cascade
);
/notification 端點,藉著GET取得使用者的訊息集合。OrderCancelService 注入 NotificationDao,並在排程執行時,設定「取消訊息」並 .saveAll 進通知表。// OrderCancelService.java
@Transactional
public int expiredOrderScheduling(List<Order> orderList){
// ...省略
List<Notification> notificationList = new ArrayList<>();
for (Order order : orderList){
// ...省略
Notification noti = new Notification();
noti.setUser(order.getUser());
noti.setMsg(order.getId() + " has been canceled");
noti.setCreate_time(Instant.now());
noti.setIs_read(false);
notificationList.add(noti);
// ...省略
}
notificationDao.saveAll(notificationList);
// ...省略
index.html 接收並呈現!// NotificationService.java
public Response<List<NotificationResponse>> getNotifications(String account){
User user = userDao.findByAccount(account).orElseThrow(() -> ResourcesException.of(ErrorCode.USER_NOT_FOUND));
List<Notification> notiList = notificationDao.findAllByUser(user);
if (notiList.isEmpty()) return new Response<>("0", "No notification", Collections.emptyList());
List<NotificationResponse> notiResList = notiList
.stream()
.map(NotificationResponse::new)
.toList();
return new Response<>("0", "Successfully", notiResList);
}
本篇文章出自《每天學Java直到今年結束》Day226,大家可以到我的網站上查看~