每当我调用 save() 方法时,三个不同实体之间共享相同的 ID,我不知道为什么?
@Entity
public class Department {
@Id
@GeneratedValue
private Long departmentId;
private String name;
public Department(Long departmentId) {
this.departmentId = departmentId;
}
public Department() {
}
public Department(String name) {
this.name = name;
}
public Long getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Long departmentId) {
this.departmentId = departmentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity
public class Location {
@Id
@GeneratedValue
private Long locationId;
private String name;
public Location(Long locationId) {
this.locationId = locationId;
}
public Location() {
}
public Location(String name) {
this.name = name;
}
public Long getLocationId() {
return locationId;
}
public void setLocationId(Long locationId) {
this.locationId = locationId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
这是我的 Controller :
@RestController
public class SettingsController {
@Autowired
private LocationRepository locationRepository;
@Autowired
private DepartmentRepository departmentRepository;
@Autowired
private RoleRepository roleRepository;
@RequestMapping(value = "/api/locations", method = RequestMethod.POST)
public ResponseEntity addLocation(@RequestBody DataForm dataForm) {
if (dataForm == null) {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
locationRepository.save(new Location(dataForm.getName()));
return new ResponseEntity(HttpStatus.CREATED);
}
@RequestMapping(value = "/api/roles", method = RequestMethod.POST)
public ResponseEntity addRole(@RequestBody DataForm dataForm) {
if (dataForm == null) {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
roleRepository.save(new Role(dataForm.getName()));
return new ResponseEntity(HttpStatus.CREATED);
}
@RequestMapping(value = "/api/departments", method = RequestMethod.POST)
public ResponseEntity addDepartment(@RequestBody DataForm dataForm) {
if (dataForm == null) {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
departmentRepository.save(new Department(dataForm.getName()));
return new ResponseEntity(HttpStatus.CREATED);
}
}
只有当 id 是静态的时候才会发生这种情况,但事实并非如此。如果我创建两个新的 Location() 对象,当我创建一个新的 Department() 时,部门的 ID 将为 3。为什么?
最佳答案
由于您没有指定 @GeneeratedValue
的策略,我猜测 Hibernate 对您的所有实体使用相同的序列。
你可以设置类似的东西
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="department_seq_gen")
@SequenceGenerator(name="department_seq_gen", sequenceName="DEPARTMENT_SEQ")
在Department
实体上,以及在Location
实体上类似的东西(只需使用location_seq_gen
和LOCATION_SEQ
)。
关于java - 为什么当我在存储库中保存对象时相同的 id 会递增?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38900082/