java - 由于@OneToMany,JPA 更新记录失败

标签 java spring postgresql spring-boot jpa

我对 @OneToMany 映射有一个很小的疑问。

我有一个模范学生和另一个模范出勤者。

一名学生可以多次出勤。但学生模型应该只能检索出勤信息。

但是当我尝试更改一些学生信息时,我收到以下错误,因为它正在尝试更新出勤记录。

这是我的映射

@Entity
@Table(name="student_detail")
@Getter @Setter
public class StudentDetailsModel {

    @Id
    @Column(name="reg_no",updatable = false, nullable = false)
    private String regNo;

    @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL })
    @JoinColumn(name = "reg_no")
    private List<AttendanceModel> attendances;
}

我得到了异常(exception)。

    update
        student_detail 
    set
        address=?,
        alt_contact_number=?,
        blood_group=?,
        contact_number=?,
        dob=?,
        father_name=?,
        first_name=?,
        gender=?,
        last_name=?,
        middle_name=?,
        mother_name=?,
        photo_url=?,
        school_id=? 
    where
        reg_no=?
Hibernate: 
    update
        attendance 
    set
        reg_no=null 
    where
        reg_no=?
2019-01-13 12:12:52.922  WARN 10708 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 23502
2019-01-13 12:12:52.923 ERROR 10708 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: null value in column "reg_no" violates not-null constraint
  Detail: Failing row contains (null, 1, 2019-01-05, t, 2).
2019-01-13 12:12:52.926  INFO 10708 --- [nio-8081-exec-1] o.h.e.j.b.internal.AbstractBatchImpl     : HHH000010: On release of batch it still contained JDBC statements
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [reg_no]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

我的出勤模型如下

@Entity
@Table(name="attendance")
@Getter @Setter
public class AttendanceModel {

    //@EmbeddedId
    //private AttendanceId attendanceId;

    @Id
    @Column(name="attendance_id")
    private long id;


    @Column(name="reg_no")
    private String regNo;

    @Column(name="subject_id")
    private long subjectId;

    @Column(name="class_date")
    private Date classDate;


    @Column(name="present")
    private boolean present;
}

最佳答案

你能给我看一下学生模型吗?如果我看看你的代码帖子:你使用单向关系。

我认为必须:

@OneToMany(fetch = FetchType.LAZY , cascade = CascedeType.ALL)
@JoinColumn(name="attendance_id")
private List<AttendanceModel> attendances = new ArrayList<>();

关于java - 由于@OneToMany,JPA 更新记录失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54166756/

相关文章:

Java 应用程序在打开套接字时立即抛出 ClosedByInterruptException,原因是什么?

java - Jdbc 的 Spring Beans 不工作

java - Spring Data JPA findOne() 改为 Optional 怎么用?

postgresql - 将PostgreSQL中所有表的所有记录中的所有空字符串设置为NULL

mysql判断一个字段的存储大小

sql - 在 Postgres 聚合中过滤

java - 包括请求对象的操作、包括指令和哈希码?

java - 右加入jpa

java - spring cassandra 数据版本 2.1.4 分页

java - 使 ServletContextListener 具有 Spring 意识