spring-data-jpa Hibernate JPA @多对多Map无法添加或更新子行:外键约束失败

tv6aics1  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(131)

我尝试在用户和组之间建立多对多关系,因此当我保存组时,用户和组信息应保存在user_group表中,但在尝试保存组信息时出现此错误,在请求中我只是传递groupName。
错误

2022-11-07 14:45:47.565 ERROR 29066 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper   : Cannot add or update a child row: a foreign key constraint fails (`testdb`.`user_group`, CONSTRAINT `FK7k9ade3lqbo483u9vuryxmm34` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))

User.java

@Entity
@Table(name = "users", 
    uniqueConstraints = { 
      @UniqueConstraint(columnNames = "username"),
      @UniqueConstraint(columnNames = "email") 
    })
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @ManyToMany(fetch = FetchType.LAZY)
  @JoinTable(  name = "user_roles", 
        joinColumns = @JoinColumn(name = "user_id"), 
        inverseJoinColumns = @JoinColumn(name = "role_id"))
  private Set<Role> roles = new HashSet<>();

  @ManyToMany(fetch = FetchType.LAZY,
          cascade = {
                  CascadeType.PERSIST,
                  CascadeType.MERGE
          },
          mappedBy = "users")
  @JsonIgnore
  private Set<Group> groups = new HashSet<>();

  public Set<Group> getGroups() {
    return groups;
  }
}

Group.java

@Entity
@Table(name = "grp")
public class Group {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String groupName;

    @Column
    private String createdBy;

    public Group(String groupName, String createdBy ) {
        this.groupName = groupName;
        this.createdBy = createdBy;
    }

    public Group() {

    }
}

GroupController.java

@RestController
@RequestMapping("/api")
public class GroupController  {

    @Autowired
    GroupRepository groupRepository;

    @Autowired
    UserRepository userRepository;

    @PostMapping("/group")
    public ResponseEntity<Group> createTutorial(@RequestBody Group group, Principal principal) {
        try {
            Set<User> userSet = new HashSet<>();
            Optional<User> user = userRepository.findByUsername(principal.getName());
            userSet.add(user.get());
            Group group2 = new Group(group.getGroupName(), principal.getName());
            group2.setUsers(userSet);
            Group group1 = groupRepository.save(group2);
            return new ResponseEntity<>(group1, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

aydmsdu9

aydmsdu91#

这个问题是我的数据库模式,它是由一个早期的不正确的JPA模型创建的。在删除并重新创建数据库后,它得到了解决。

相关问题