我有几个实体:
@Entity
@Table(name = "app_user", schema = "edu", catalog = "ed_db")
@Getter
@Setter
public class AppUser {
@Basic
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id", insertable = false, updatable = false)
private Integer id;
@Id
@Column(name = "username")
private String username;
@Basic
@Column(name = "password")
@JsonIgnore
private String password;
@Basic
@Column(name = "first_name")
private String firstName;
@Basic
@Column(name = "last_name")
private String lastName;
@Basic
@Column(name = "email")
private String email = "";
}
和教师实体,教师实体与appuser的关系为:
@Entity
@Getter
@Setter
public class Teacher {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
@Column(name = "id")
private Integer id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "app_user_id", nullable = false, referencedColumnName = "id")
private AppUser appUser;
@Basic
@Column(name = "client_id")
@NotNull(message = "client.is_required")
private Integer clientId;
}
当我尝试在代码中使用它时:
public Teacher save(TeacherDto teacherDto) {
AppUser appUser = teacherDto.getAppUserEntity();
AppUser dbAppUser = appUserService.save(appUser);
Teacher teacher = teacherDto.getTeacherEntity();
teacher.setAppUser(dbAppUser);
teacher.setClientId(appUser.getClientId());
return teacherRepository.save(teacher);
}
它不断抛出异常:
2022-08-19T01:20:56.052-04:00 WARN 69525 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23502
2022-08-19T01:20:56.053-04:00 ERROR 69525 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: null value in column "app_user_id" of relation "teacher" violates not-null constraint
Detail: Failing row contains (1, null, 2, 2022-08-19 01:20:56.028, 2022-08-19 01:20:56.028).
2022-08-19T01:20:56.064-04:00 ERROR 69525 --- [nio-8080-exec-2] c.c.p.exceptions.GlobalExceptionHandler : org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [app_user_id" of relation "teacher]
我不知道这里有什么问题。在控制台中,语句如下所示:
insert
into
edu.app_user
(address, client_id, created_at, email, enabled, first_name, last_name, password, phone, username)
values
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
insert
into
edu.teacher
(app_user_id, client_id, created_at, updated_at)
values
(?, ?, ?, ?)
1条答案
按热度按时间e0bqpujr1#
在您的实体
AppUser
中,@GeneratedValue
适用于字段id
,@Id
适用于字段username
。我猜您必须将@Id
移动到字段id
。