我擁有User和Address物體具有one-to-many單向關系。當我嘗試插入詳細資訊User時Address,它會因例外“參考完整性約束違規”而失敗,因為我檢查了Address沒有插入userId它有 0 我沒有得到什么問題。
我的用戶物體:
@Entity
@Table(name = "users")
public class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private long id;
@OneToMany(orphanRemoval = true,cascade = CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name = "USER_ID", referencedColumnName = "ID")
private List<Address> address;
// other table columns
}
我的地址物體:
@Entity
@Table(name = "address")
public class Address{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private long id;
@Column(name = "USER_ID")
private long userId;
//other table columns
}
我的控制器:
@PostMapping("/")
public ResponseEntity<UserDTO> saveUser(@RequestBody UserRequestDTO userRequestDTO){
try {
if (userRequestDTO != null) {
return new ResponseEntity<>(userService.saveUser(userRequestDTO), HttpStatus.CREATED);
}
} catch (Exception ex) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return null;
}
我的服務層:
@Override
public UserDTO saveUser(UserRequestDTO userDto) {
User obj = modelMapper.map(userDto, User.class);
System.out.println(obj.toString());
obj = userRepository.save(obj);
return modelMapper.map(obj, UserDTO.class);
}
這是我的 UserRequestDTO 我擁有所有財產
public class UserRequestDTO {
private long id;
private long clientId;
private String clientName;
private String email;
private String firstName;
private String lastName;
private String employeeNo;
private String designation;
private String status;
private String phoneNumber;
private String employeeType;
private String reportingTo;
private String department;
private String division;
private String password;
private String gender;
private String bloodGroup;
private String maritalStatus;
private String spouseName;
private String noOfChildren;
private Date dateOfBirth;
private Date hiredDate;
private LocalDate createdDate;
private String createdBy;
private LocalDate updatedDate;
private String updatedBy;
private List<Address> address;
}
檢查了許多在線教程,但無法從控制臺獲取根本原因錯誤訊息:
User(id=0, clientId=1, email=user@gmail.com, firstName=user 10, lastName=K, password=password@123, employeeNo=EH5213, phoneNumber=9999999990, status=A, designation=Developer, employeeType=FullTime, reportingTo=Roshan, department=Information Technology, division=division, locationId=null, gender=null, bloodGroup=null, maritalStatus=null, spouseName=null, noOfChildren=null, dateOfBirth=null, hiredDate=null, createdDate=2022-03-25, createdBy=admin, updatedDate=2022-03-25, updatedBy=admin, organization=null, address=[Address(id=0, clientId=1, userId=0, address1=add1Sample, address2=add2Sample, state=sample, addressType=P, country=sample, city=sample, zipCode=000002, primaryPhone=1111111111, secondaryPhone=2222222222, active=true, createdDate=2022-03-25, createdBy=admin, updatedDate=2022-03-25, updatedBy=admin), Address(id=0, clientId=1, userId=0, address1=sample2, address2=add2sample2 , state=sample2, addressType=T, country=sample2, city=sample2, zipCode=000008, primaryPhone=4444444444, secondaryPhone=666666666, active=true, createdDate=2022-03-25, createdBy=admin, updatedDate=2022-03-25, updatedBy=admin)], employeeGroups=null)
Hibernate: insert into users (id, blood_group, client_id, created_by, created_date, date_of_birth, department, designation, division, email, employee_no, employee_type, first_name, gender, hired_date, last_name, location_id, marital_status, no_of_children, organization_id, password, phone_number, reporting_to, spouse_name, status, updated_by, updated_date) values (default, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into address (id, active, address_line_1, address_line_2, address_type, city, client_id, country, created_by, created_date, primary_phone, secondary_phone, state, updated_by, updated_date, user_id, zip_code) values (default, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
[2m2022-03-30 12:41:25.689[0;39m [33m WARN[0;39m [35m13308[0;39m [2m---[0;39m [2m[nio-8085-exec-2][0;39m [36mo.h.engine.jdbc.spi.SqlExceptionHelper [0;39m [2m:[0;39m SQL Error: 23506, SQLState: 23506
[2m2022-03-30 12:41:25.702[0;39m [31mERROR[0;39m [35m13308[0;39m [2m---[0;39m [2m[nio-8085-exec-2][0;39m [36mo.h.engine.jdbc.spi.SqlExceptionHelper [0;39m [2m:[0;39m Referential integrity constraint violation: "FK6I66IJB8TWGCQTETL8EEEED6V: PUBLIC.ADDRESS FOREIGN KEY(USER_ID) REFERENCES PUBLIC.USERS(ID) (0)"; SQL statement:
insert into address (id, active, address_line_1, address_line_2, address_type, city, client_id, country, created_by, created_date, primary_phone, secondary_phone, state, updated_by, updated_date, user_id, zip_code) values (default, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [23506-200]
uj5u.com熱心網友回復:
您必須先插入,User然后在插入之后插入意味著您必須在插入之前Address獲得參考。但是您不需要為插入添加代碼,因為它會自動從. 這里不需要。UserAddressUnidirectional MappingAddressUserDTO
洗掉此列,Address.java因為手動插入外鍵是不好的做法:
@Column(name = "USER_ID", insertable = false, updatable = false)
private long userId;
下面是修改后的代碼:
控制器
@RequestMapping(value = "/")
@ResponseBody
public ResponseEntity<User> addUser(@RequestBody User user)
{
userRepository.save(user);
return new ResponseEntity<>(user, HttpStatus.CREATED);
}
你不想在這里做 DTO ......
uj5u.com熱心網友回復:
這可以通過在物體級別進行一些小的更改來解決:
Change-1: 在您的用戶物體中添加 nullable=false,如下所示:
@Entity
@Table(name = "users")`
public class User{`
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private long id;
@OneToMany(orphanRemoval = true,cascade = CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name = "USER_ID", referencedColumnName = "ID", nullable = false)
private List<Address> address;
// other table columns
}
更改 2:在您的地址物體中添加 insertable = false 和 updatable = false,如下所示
@Entity
@Table(name = "address")
public class Address{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private long id;
@Column(name = "USER_ID", insertable = false, updatable = false)
private long userId;
//other table columns
}
使用 nullable=false :它將非空約束應用于特定的資料庫列
要了解 insertable = false、updatable = false 的用法,請參考:請參考 JPA @Column 注釋解釋 insertable=false 和 updatable=false
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/454323.html
