我有两个实体:客房和服务。我也想在ServiceController类中使用Logic类中的方法。其他课程无关紧要。
room.getBeds()始终返回0,默认为int值。
房间实体:
@Entity
public class Room {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int room_id;
private int beds;
private int number;
public Room() {
}
public Room(int beds, int number) {
this.beds = beds;
this.number = number;
}
public int getRoom_id() {
return room_id;
}
public void setRoom_id(int room_id) {
this.room_id = room_id;
}
public int getBeds() {
return beds;
}
public void setBeds(int beds) {
this.beds = beds;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
服务实体:
@Entity
public class Service {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int service_id;
@JsonFormat(pattern = "dd/MM/yyyy", timezone = "Europe/Berlin")
private Date arrival_at;
@JsonFormat(pattern = "dd/MM/yyyy", timezone = "Europe/Berlin")
private Date departure_at;
private int meals;
private int guest_id;
private double price;
public int getService_id() {
return service_id;
}
public void setService_id(int service_id) {
this.service_id = service_id;
}
public Date getArrival_at() {
return arrival_at;
}
public void setArrival_at(Date arrival_at) {
this.arrival_at = arrival_at;
}
public Date getDeparture_at() {
return departure_at;
}
public void setDeparture_at(Date departure_at) {
this.departure_at = departure_at;
}
public int getMeals() {
return meals;
}
public void setMeals(int meals) {
this.meals = meals;
}
public int getGuest_id() {
return guest_id;
}
public void setGuest_id(int guest_id) {
this.guest_id = guest_id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
服务控制器:
@RestController
public class ServiceController {
@Autowired
ServiceRepository serviceRepository;
private Logic logic = new Logic();
private Room room = new Room();
//CREATE
@PostMapping("/services")
public int createService(@RequestBody Service service) {
service.setPrice(logic.calculatePrice(service.getArrival_at(), service.getDeparture_at(), room.getBeds(), service.getMeals()));
return serviceRepository.save(service);
}
}
如何从room.getBeds()getter获取正确的值?
答案 0 :(得分:1)
Lerius,您只是在创建“房间实体”的新对象,而没有将数据库中的任何值填充到该对象 这就是为什么要占用room.getBeds();的原因。为0(即int的默认值) 尝试将DB值填充到您的对象之后,您将可以获取getBeds()的值;