我在创建spring maven rest webservice项目时出错。我是新的Spring Boot,谁能帮我这个。错误是:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value : com.example.spring.backend.model.Employee.firstName; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value : com.example.spring.backend.model.Employee.firstName] with root cause
字符串
我使用MySQL Workbench创建了一个数据库,并在其中定义了一个表来存储员工的详细信息。下面是我的代码:
EmployeeController.java
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
private EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
super();
this.employeeService = employeeService;
}
// build create employee REST API
@PostMapping()
public ResponseEntity<Employee> saveEmployee(@RequestBody Employee employee){
return new ResponseEntity<Employee>(employeeService.saveEmployee(employee), HttpStatus.CREATED);
}
}
型
Employee.java
@Data
@Entity
@Table(name="employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
}
型
EmployeeRepository.java
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}
型
EmployeeService.java
public interface EmployeeService {
Employee saveEmployee(Employee employee);
}
型
EmployeeServiceImpl.java
@Service
public class EmployeeServiceImpl implements EmployeeService{
private EmployeeRepository employeeRepository;
public EmployeeServiceImpl(EmployeeRepository employeeRepository) {
super();
this.employeeRepository = employeeRepository;
}
@Override
public Employee saveEmployee(Employee employee) {
return employeeRepository.save(employee);
}
}
型
应用.属性
spring.datasource.url=jdbc:mysql://localhost:3306/employee_management_system?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
# Hibernate properties
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
# create, create-drop
spring.jpa.hibernate.ddl-auto=update
型
使用 Postman 发送邮件请求时,我收到了内部服务器错误500。
**Input**
{
"firstName": "abc",
"lastName": "abc",
"email": "abc@gmail.com"
}
**Result:**
{
"timestamp": "2022-10-26T09:48:51.322+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/api/employees"
}
型
我从youtube视频中引用,但在视频中,代码的工作,但不是在我的情况下。
请告诉我代码中有什么错误。提前感谢
1条答案
按热度按时间cvxl0en21#
有时注解或数据Map有问题,一旦尝试使用此代码
字符串
}
-UserEntity --(执行getter setter)
型
型
-DAO--
型
-------application.properties----------
型