relational-database - 错误 OneTOMany/ManyToOne 映射 : null at time of saving parent - child table

标签 relational-database

我有两个实体:
我明白这个问题。 FK(名称:LOGGEMPLOYEEMODEL_ID)位于“loggingmodel”表中。
在为父表“employeedetails”保存新记录时,子表也应该更新。但我收到错误消息:“org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException:列“LOGGINGEMPLOYEEMODEL_ID”不允许为空;SQL 语句:
插入 LoggingModel (infotext, loggingEmployeeModel_id, title, id) 值 (?, ?, ?, ?) [23502-199]"
我明白了,对于子表的 FK,employeedetails 的新 ID 是未知的。 (如果它从 Postman 注入(inject)中取出“employeeModelLogging”部分,那么我不会收到约束错误,所以它应该是 loggingModel 部分)
我如何在 JPA - Hibernate 中解决这个问题?
父端:一对多:


@Entity
@AllArgsConstructor    
@Getter
@Setter
@NoArgsConstructor     
@Table(name="employeedetails", schema="public")
public class EmployeeModel implements Serializable {        
 
    private static final long serialVersionUID = -3009157732242241606L;
     
    @Id
    @Column(name="id")
    @SequenceGenerator(initialValue=1, name="employeedetails_seq", sequenceName="employeedetails_sequence", allocationSize=1)
        @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="employeedetails_seq")
    private Long id;
        ...
     
    @OneToMany(mappedBy = "loggingEmployeeModel",fetch=FetchType.LAZY , cascade = CascadeType.ALL)
        private List<LoggingModel> employeeModelLogging;
     
       ...
  
}

子端:多对一:
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class LoggingModel {
 
    @Id
    @Column(name = "id")
    @SequenceGenerator(initialValue = 1, name = "log_seq", sequenceName = "log_sequence", allocationSize=1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "log_seq")
    private Long id;
    @Column() 
    private String title;
    @Column()
    private String infotext;
     
    @ManyToOne (cascade = CascadeType.ALL)
    @JoinColumn(name = "loggingEmployeeModel_id", referencedColumnName = "id", nullable = false) 
    private EmployeeModel loggingEmployeeModel;
     
}
创建员工服务实现:

       @Override
   public ResponseEntity<Object> createEmployee(EmployeeModel employeeModelToCreate) {
        
       if (employeeRepository.findByEmployeeName(employeeModelToCreate.getEmployeeName()).isEmpty()) {
        
           employeeModelToCreate.setCreatedDateTime(LocalDateTime.now());
           employeeModelToCreate.setModifiedDateTime(LocalDateTime.now());
 
           Long unitId = employeeModelToCreate.getUnit().getId();
           Unit unit = em.find(Unit.class, unitId);
           employeeModelToCreate.setUnit(em.getReference(Unit.class, unitId)); // Alternative 2
                
           EmployeeModel savedEmployeeModel = employeeRepository.save(employeeModelToCreate);
            
           if (employeeRepository.findById(savedEmployeeModel .getId()).isPresent())
                return ResponseEntity.ok("User Created Successfully");
            else
                return ResponseEntity.unprocessableEntity().body("Failed Creating User as Specified");
       } else {
           return ResponseEntity.unprocessableEntity().body("msg: Employee with this employee name: " + employeeModelToCreate.getEmployeeName() + ", already exist in DB!");
       }   
   }  

这就是我用 Postman 注入(inject)的内容:
{
    "employeeName": "Nico",
    "employeeCode": "ECN0004",
    "designation": "ZZZZZ",
    "address": {
        "doorNumber": "37",
        "street": "Laakse Laan",
        "city": "Zutphen"
    },
    "department": {
        "deptName": "Nieuwegein"
    },
    "employeeModelLogging":[
        {
            "title": "Dit is de titel - nieuw opmerking",
            "infotext": "Dit is de infotext "
        },
        {
            "title": "Dit is de titel van de 2e opmerking ",
            "infotext": "Dit is de infotext van de 2e opmerking"
        }
    ],
    "unit":  {
        "id": 3
    },
    "roles": [
        {
            "id": 1,
            "name":"Admin",
            "description": "Administrator"
        },
        {
            "id": 2,
            "name":"Guest",
            "description": "Gast"
        }
    ]
}

有人可以提出想法/提示我做错了什么吗?

最佳答案

我认为模型类是从 JSON 直接映射到您的实体的,对吗?如果是这样,您将遇到仅在一侧设置的双向关系。 unmarshalling从 JSON 创建新 LoggingModel实例,并将它们放入一个列表中。然后在创建的 EmployeeModel 上设置该列表实例。 EmployeeModel实例现在可以引用它的所有 LoggingModel实例。仍然缺少的是 LoggingModel 中的引用EmployeeModel 的实例实例。 JSON unmarshalling没有设置它,因为它根本不知道它应该。
一个快速的解决方案是自己修复这些引用。快速 for-each 语句就足够了:

employeeModel.getEmployeeModelLogging().forEach(lm -> lm.setLoggingEmployeeModel(employeeModel);

关于relational-database - 错误 OneTOMany/ManyToOne 映射 : null at time of saving parent - child table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69217655/

相关文章:

mysql : Best way to deal with data like average rating of restaurants etc?

mysql - 一张或单独的 MariaDB 表中的价格

php - 如何访问 yii2 关系映射表字段

sql-server-express - SQL Server Compact Edition 和 SQL Server Express Edition 有什么区别?

mysql - 如何处理MySQL读写分离中的最终一致性问题

mysql - 如何存储嵌套位置?

mysql - 需要帮助构建奇怪的 Sequelize 查询

database - 在excel中创建数据库

SQL 查询 ORDER BY 两个条件无法正常工作 - 我做错了什么?

mysql - 选择 MYSQL 而不是 Mongodb