我有一个使用JPA作为ORM的Spring应用程序,我认为这是正确的,并且Swagger为端点创建了一个不错的UI。
当尝试使用已保存在数据库中的数据发出POST或PUT请求时,我收到错误消息:
Servlet.service() for servlet [dispatcher] in context with path [/api/orgchart] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement] with root cause
java.sql.SQLSyntaxErrorException: Table 'orgchart_api.employee_department' doesn't exist
很明显,该错误是由于JPA试图更新employee_department
表上的数据而该表不存在这一事实造成的。我遇到的问题是找出为什么,JPA正在尝试访问该表。
数据流:
{
"id": 104,
"isActive": true,
"manager": null,
"firstName": "string",
"middleInitial": null,
"lastName": "string",
"department": {
"id": 104,
"isActive": true,
"parentDepartment": {
"id": 101,
"isActive": true,
"parentDepartment": null,
"manager": null,
"name": "Marketing"
},
"manager": null,
"name": "Americas"
},
"jobTitle": {
"id": 1001,
"isActive": true,
"name": "Jr. Developer"
},
"email": "e",
"skypeName": "e",
"isManager": false
}
package com.orgchart.web.controller;
import com.orgchart.model.Employee;
import com.orgchart.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/emps")
public class EmployeeController {
@Autowired
EmployeeService employeeService;
@RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT})
public Employee createOrUpdateEmployee(@RequestBody Employee employee) {
return employeeService.storeOrUpdate(employee);
}
}
package com.nexient.orgchart.service;
import com.nexient.orgchart.data.entity.DepartmentEntity;
import com.nexient.orgchart.data.entity.EmployeeEntity;
import com.nexient.orgchart.data.repository.EmployeeRepository;
import com.nexient.orgchart.mapper.EmployeeMapper;
import com.nexient.orgchart.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@Autowired
EmployeeMapper employeeMapper;
public Employee storeOrUpdate(Employee employee) {
EmployeeEntity employeeEntity = employeeMapper.modelToEntity(employee);
EmployeeEntity savedEmployeeEntity = employeeRepository.save(employeeEntity);
Employee employeeModel = employeeMapper.entityToModel(savedEmployeeEntity);
return employeeModel;
}
package com.nexient.orgchart.mapper;
import com.nexient.orgchart.data.entity.DepartmentEntity;
import com.nexient.orgchart.data.entity.EmployeeEntity;
import com.nexient.orgchart.data.entity.JobTitleEntity;
import com.nexient.orgchart.model.Department;
import com.nexient.orgchart.model.Employee;
import com.nexient.orgchart.model.JobTitle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
@Component
public class EmployeeMapper implements EntityModelMapper<EmployeeEntity, Employee> {
@Autowired
private DepartmentMapper departmentMapper;
@Autowired
private JobTitleMapper jobTitleMapper;
@Override
public EmployeeEntity modelToEntity(Employee employee) {
Assert.notNull(employee, "Employee model cannot be null.");
EmployeeEntity employeeEntity = new EmployeeEntity();
DepartmentEntity departmentEntity = departmentMapper.modelToEntity(employee.getDepartment());
JobTitleEntity jobTitleEntity = jobTitleMapper.modelToEntity(employee.getJobTitle());
Employee employeeManager = employee.getManager();
if (employeeManager != null) {
EmployeeEntity employeeManagerEntity = modelToEntity(employeeManager);
employeeEntity.setManager(employeeManagerEntity);
}
employeeEntity.setId(employee.getId());
employeeEntity.setEmail(employee.getEmail());
employeeEntity.setFirstName(employee.getFirstName());
employeeEntity.setMiddleInitial(employee.getMiddleInitial());
employeeEntity.setLastName(employee.getLastName());
employeeEntity.setDepartment(departmentEntity);
employeeEntity.setJobTitle(jobTitleEntity);
employeeEntity.setIsManager(employee.getIsManager());
employeeEntity.setSkypeName(employee.getSkypeName());
employeeEntity.setIsActive(employee.getIsActive());
return employeeEntity;
}
从这里开始,它仅遍历<Model>.modelToEntity()
和jobTitle
的其他department
,并最终从 EmployeeService 文件中调用employeeRepository.save(employeeEntity)
错误的来源。
重申一下,为什么在我的任何实体中都没有将employee_department
表指定为表名时,为什么我的POST请求试图访问它?
package com.nexient.orgchart.data.entity;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Set;
@Entity
@Table(name = "employee")
public class EmployeeEntity extends BaseEntity {
@Column(name = "first_name")
@NotEmpty
@Size(min = 1)
private String firstName;
@Column(name = "middle_initial")
private Character middleInitial;
@Column(name = "last_name")
@NotEmpty
@Size(min = 1)
private String lastName;
@Column(name = "email")
@NotEmpty
@Size(min = 1)
private String email;
@Column(name = "skype_name")
@NotEmpty
@Size(min = 1)
private String skypeName;
@ManyToOne
@JoinColumn(name = "job_title_id")
private JobTitleEntity jobTitle;
@ManyToOne
@JoinColumn(name = "manager_id")
private EmployeeEntity manager;
@ManyToOne
@JoinColumn(name = "department_id")
private DepartmentEntity department;
@OneToMany(mappedBy = "manager")
private Set<EmployeeEntity> ManagedEmployees;
@OneToMany
private Set<DepartmentEntity> ManagedDepartments;
@Column(name = "is_manager")
@NotNull
private boolean isManager;
... Getters and Setters ...
package com.nexient.orgchart.data.entity;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.util.Set;
@Entity
@Table(name = "job_title")
public class JobTitleEntity extends BaseEntity {
@Column(name = "name", unique = true)
@NotEmpty
private String name;
@OneToMany
private Set<EmployeeEntity> titleEmployees;
... Getters and Setters ...
package com.nexient.orgchart.data.entity;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "department")
public class DepartmentEntity extends BaseEntity {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "manager_id")
private EmployeeEntity manager;
@Column(name = "name", nullable = false, length = 50, unique = true)
@NotNull
@NotEmpty
@Size(min = 1, max = 45)
private String name;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "parent_department_id", referencedColumnName = "ID")
private DepartmentEntity parentDepartment;
@OneToMany(mappedBy = "parentDepartment")
private Set<DepartmentEntity> departments = new HashSet<>(0);
@OneToMany(mappedBy = "department")
private Set<EmployeeEntity> employees = new HashSet<>(0);
... Getters and Setters ...
答案 0 :(得分:1)
发生这种情况是因为您有一个N
名员工与1
个部门关系:
@ManyToOne
@JoinColumn(name = "department_id")
private DepartmentEntity department;
您的JPA实现选择使用专用表而不是可空列来支持此关系。显然,它已从所涉及实体的表名称中自动导出了employee_department
名称。
使用配置为生成DDL语句和记录所有SQL语句的JPA实现运行您的应用程序可能会证明是相当具有启发性的。确切的配置将取决于您选择的JPA提供程序,但是由于您使用的是Spring,因此您可能需要spring.jpa.generate-ddl=true
和spring.jpa.show-sql=true
。参见the documentation