级联保存时,Hibernate约束失败

时间:2015-06-07 19:22:35

标签: java spring hibernate jpa

我有相关实体的级联保存问题。我的UserEntity与RegistrationTokenEntity“一对多”相关。当我尝试保存这个级联的实体时,我得到了异常。这是代码:

UserEntity:

@Entity
@Table(name = "user", schema = "", catalog = "myDatabase")
public class UserEntity {
    private int userId;
    private String login;
    // Some other fields

    private Set<RegistrationTokenEntity> registrationTokenEntities = new HashSet<RegistrationTokenEntity>(0);

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "userId", cascade = CascadeType.ALL)
    public Set<RegistrationTokenEntity> getRegistrationTokenEntities() {
        return registrationTokenEntities;
    }

    public void setRegistrationTokenEntities(Set<RegistrationTokenEntity> registrationTokenEntities) {
        this.registrationTokenEntities = registrationTokenEntities;
    }

    @Id
    @Column(name = "user_id")
    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    // Some other setters and getters
}

RegistrationTokenEntity:

@Entity
@Table(name = "registration_token", schema = "", catalog = "myDatabase")
public class RegistrationTokenEntity {
    private int registrationTokenId;
    private UserEntity userId;
    // Some other fields

    @Id
    @Column(name = "registration_token_id")
    public int getRegistrationTokenId() {
        return registrationTokenId;
    }

    public void setRegistrationTokenId(int registrationTokenId) {
        this.registrationTokenId = registrationTokenId;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = false)
    public UserEntity getUserId() {
        return userId;
    }

    public void setUserId(UserEntity userId) {
        this.userId = userId;
    }

    // Some others setters and getters
}

以下是我的保存方式:

private void addNewUser(SignupForm homepageForm, PasswordEncoder passwordEncoder) {
    UserEntity userEntity = new UserEntity(homepageForm);

    RegistrationTokenEntity registrationTokenEntity = new RegistrationTokenEntity();
    registrationTokenEntity.setConfirmed((byte)0);
    UUID token = UUID.randomUUID();
    registrationTokenEntity.setToken(token.toString());
    registrationTokenEntity.setUserId(userEntity);
    userEntity.getRegistrationTokenEntities().add(registrationTokenEntity);

    userRepository.saveAndFlush(userEntity);
}

这是我的用户和registerToken表的数据库SQL:

CREATE TABLE IF NOT EXISTS `myDatabase`.`user` (
  `user_id` INT NOT NULL AUTO_INCREMENT,
  `login` VARCHAR(30) NOT NULL,
  // Some other fields
  PRIMARY KEY (`user_id`),
  UNIQUE INDEX `login_UNIQUE` (`login` ASC),
  UNIQUE INDEX `username_UNIQUE` (`username` ASC),
  UNIQUE INDEX `email_UNIQUE` (`email` ASC))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `myDatabase`.`registration_token` (
  `registration_token_id` INT NOT NULL AUTO_INCREMENT,
  `user_id` INT NOT NULL,
  // Some other fields
  PRIMARY KEY (`registration_token_id`, `user_id`),
  INDEX `fk_registration_token_user1_idx` (`user_id` ASC),
  CONSTRAINT `fk_registration_token_user1`
    FOREIGN KEY (`user_id`)
    REFERENCES `myDatabase`.`user` (`user_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

在输出时我得到:

07-Jun-2015 21:07:25.257 WARN [http-apr-8080-exec-38] org.hibernate.engine.jdbc.spi.SqlExceptionHelper.logExceptions SQL Error: 1452, SQLState: 23000
07-Jun-2015 21:07:25.257 ERROR [http-apr-8080-exec-38] org.hibernate.engine.jdbc.spi.SqlExceptionHelper.logExceptions Cannot add or update a child row: a foreign key constraint fails (`myDatabase`.`registration_token`, CONSTRAINT `fk_registration_token_user1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
07-Jun-2015 21:07:25.260 INFO [http-apr-8080-exec-38] org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl.release HHH000010: On release of batch it still contained JDBC statements
07-Jun-2015 21:07:25.262 WARN [http-apr-8080-exec-38] org.hibernate.engine.jdbc.spi.SqlExceptionHelper$StandardWarningHandler.logWarning SQL Warning Code: 1452, SQLState: 23000
07-Jun-2015 21:07:25.262 WARN [http-apr-8080-exec-38] org.hibernate.engine.jdbc.spi.SqlExceptionHelper$StandardWarningHandler.logWarning Cannot add or update a child row: a foreign key constraint fails (`myDatabase`.`registration_token`, CONSTRAINT `fk_registration_token_user1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION)

这是根异常堆栈:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
org.hibernate.exception.ConstraintViolationException: could not execute statement
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`myDatabase`.`registration_token`, CONSTRAINT `fk_registration_token_user1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION)

你知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

我知道了!

我必须将生成的价值策略添加到我的@Id中:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
public int getUserId() {
    return userId;
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "registration_token_id")
public int getRegistrationTokenId() {
    return registrationTokenId;
}