写一个基于springboot实现客房入住情况进行登记、查询及续房操作代码片段
时间: 2024-05-05 07:15:57 浏览: 76
以下是基于springboot实现客房入住情况登记、查询及续房操作的代码片段:
1. 实体类
```
@Entity
public class Room {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String roomNumber;
private String status; // 客房状态:空闲、已预订、已入住
private Date checkInDate; // 入住时间
private Date checkOutDate; // 离店时间
// 省略getter/setter方法
}
```
2. 数据库操作接口
```
@Repository
public interface RoomRepository extends JpaRepository<Room, Long> {
List<Room> findByStatus(String status); // 查询指定状态的客房
Room findByRoomNumber(String roomNumber); // 根据客房号查询客房
}
```
3. 服务层
```
@Service
public class RoomService {
@Autowired
private RoomRepository roomRepository;
// 登记客房入住
public Room checkIn(String roomNumber) {
Room room = roomRepository.findByRoomNumber(roomNumber);
if (room == null || !"空闲".equals(room.getStatus())) {
// 客房不存在或已被预订或已入住
return null;
}
room.setStatus("已入住");
room.setCheckInDate(new Date());
room.setCheckOutDate(null);
return roomRepository.save(room);
}
// 查询空闲客房
public List<Room> findFreeRooms() {
return roomRepository.findByStatus("空闲");
}
// 查询已入住客房
public List<Room> findCheckedInRooms() {
return roomRepository.findByStatus("已入住");
}
// 续房
public Room renew(String roomNumber, int days) {
Room room = roomRepository.findByRoomNumber(roomNumber);
if (room == null || !"已入住".equals(room.getStatus())) {
// 客房不存在或不是已入住状态
return null;
}
room.setCheckOutDate(DateUtils.addDays(room.getCheckOutDate(), days));
return roomRepository.save(room);
}
}
```
4. 控制层
```
@RestController
@RequestMapping("/room")
public class RoomController {
@Autowired
private RoomService roomService;
// 登记客房入住
@PostMapping("/checkin")
public ResponseEntity checkIn(@RequestParam String roomNumber) {
Room room = roomService.checkIn(roomNumber);
if (room == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("客房不可用");
}
return ResponseEntity.ok(room);
}
// 查询空闲客房
@GetMapping("/free")
public ResponseEntity findFreeRooms() {
List<Room> rooms = roomService.findFreeRooms();
return ResponseEntity.ok(rooms);
}
// 查询已入住客房
@GetMapping("/checkedin")
public ResponseEntity findCheckedInRooms() {
List<Room> rooms = roomService.findCheckedInRooms();
return ResponseEntity.ok(rooms);
}
// 续房
@PostMapping("/renew")
public ResponseEntity renew(@RequestParam String roomNumber, @RequestParam int days) {
Room room = roomService.renew(roomNumber, days);
if (room == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("客房不可用");
}
return ResponseEntity.ok(room);
}
}
```
阅读全文