每当我调用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;
}
}
这是我的控制器:
@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.为什么?
答案 0 :(得分:1)
由于您没有为@GeneratedValue
指定策略,我猜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
)。