我在MySQL数据库中为表“Bookings”创建了一个Bookings类(Model类),该类中的所有数据成员都是根据数据库表设置的。
所有GET请求都有效,只有POST请求返回错误。
存储库接口:
package com.example.demo.bookings;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BookingsRepository extends CrudRepository<Bookings, Integer>{
Iterable<Bookings> findAllByBookingName(String name);
}
BookingsController类别:
package com.example.demo.bookings;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BookingsController {
@Autowired
BookingsService bs;
@RequestMapping("/bookings")
public List<Bookings> getBookings(){
return bs.getAllBookings();
}
@RequestMapping("/{name}/bookings")
public List<Bookings> getBookings(@PathVariable String name){
return bs.getBookingsByName(name);
}
@PostMapping("/bookings")
public void addBookings(Bookings bookings) {
bs.addBookings(bookings);
}
}
预订POJO课程:
package com.example.demo.bookings;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Bookings {
@Id
int bookingId;
String bookingName;
int bookingPid;
int passengers;
int cost;
public Bookings() {
}
public Bookings(int bookingId, String bookingName, int bookingPid, int passengers, int cost) {
super();
this.bookingId = bookingId;
this.bookingName = bookingName;
this.bookingPid = bookingPid;
this.passengers = passengers;
this.cost = cost;
}
public int getBookingId() {
return bookingId;
}
public void setBookingId(int bookingId) {
this.bookingId = bookingId;
}
public String getBookingName() {
return bookingName;
}
public void setBookingName(String bookingName) {
this.bookingName = bookingName;
}
public int getBookingPid() {
return bookingPid;
}
public void setBookingPid(int bookingPid) {
this.bookingPid = bookingPid;
}
public int getPassengers() {
return passengers;
}
public void setPassengers(int passengers) {
this.passengers = passengers;
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
}
编辑二:
按照建议,我将名称中有'_'的列的模型类数据成员更改为camelcase。这帮助解决了我所面临的许多问题,但POST方法仍然返回错误。
尝试POST请求时出现的错误:
java.sql.SQLIntegrityConstraintViolationException: Column 'booking_name' cannot be null
2条答案
按热度按时间mnemlml81#
在您的
TopicService
中,您正在尝试自动连接TopicsRepository
,但是您没有任何类型为TopicsRepository
的bean。添加以下注解:
von4xj4u2#
数据库中用下划线分隔的字段通常Map到类中的camelCase字段。
Bookings
类中的字段名应为bookingName
,存储库方法签名应为:对于
Bookings
类中的所有其他字段也是如此。