Java Hibernate无法添加或更新子行:外键约束失败

Java Hibernate无法添加或更新子行:外键约束失败,java,mysql,spring,hibernate,Java,Mysql,Spring,Hibernate,当我试图将对象保存到数据库中时,出现错误: java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`smartphones`.`smartphone`, CONSTRAINT `fk_smartphone_resolution1` FOREIGN KEY (`resolution_id`) REFERENCES `re

当我试图将对象保存到数据库中时,出现错误:

java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`smartphones`.`smartphone`, CONSTRAINT `fk_smartphone_resolution1` FOREIGN KEY (`resolution_id`) REFERENCES `resolution` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)

第一件事是我在
Smartphone
类中有错误的引用名称列,但我检查了一下,它看起来不错。也许有人能找出这个问题的原因

数据库短截图

创建智能手机表的SQL脚本

CREATE TABLE IF NOT EXISTS `smartphones`.`smartphone` (
      `id` INT(11) NOT NULL AUTO_INCREMENT,
      `name` VARCHAR(45) NULL DEFAULT NULL,
      `resolution_id` INT(11) NOT NULL,
               ...other
      PRIMARY KEY (`id`, `resolution_id`),
      UNIQUE INDEX `id_UNIQUE` (`id` ASC),
      INDEX `fk_smartphone_resolution1_idx` (`resolution_id` ASC),
      CONSTRAINT `fk_smartphone_resolution1`
        FOREIGN KEY (`resolution_id`)
        REFERENCES `smartphones`.`resolution` (`id`)
        ON DELETE NO ACTION
        ON UPDATE NO ACTION)
Smartphone
类,但具有一个关系对象

package com.project.model;

import javax.persistence.*;

@Entity
public class Smartphone {
    private int id;
    private String name;
    private Resolution resolutionId;

    @Id
    @Column(name = "id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
    @JoinColumn(name = "resolution_id", referencedColumnName = "id", nullable = false)
    public Resolution getResolutionId() {
        return resolutionId;
    }

    public void setResolutionId(Resolution resolutionId) {
        this.resolutionId = resolutionId;
    }
}
[编辑:解析智能手机模型并保存到数据库]

@RequestMapping(value = { "apple" }, method = RequestMethod.GET)
    public String parseApple(ModelMap model) {

        try {
            String appleData = Utilities.getResourceAsString(this, "json/apple.json");

            JSONArray array = new JSONArray(appleData);

            Session session = sessionFactory.openSession();
            Transaction transaction = session.beginTransaction();

            for (int i = 0; i < array.length(); i++) {
                Smartphone smartphone = new Smartphone();

                String resolutionValue = array.getJSONObject(i).getString("resolution");
                String resolution_w = resolutionValue.split(" ")[0];
                String resolution_h = resolutionValue.split(" ")[2];
                Resolution resolution = new Resolution();
                resolution.setHeight(Integer.valueOf(resolution_h));
                resolution.setWidth(Integer.valueOf(resolution_w));
                resolution.setTypeId(typeService.findByCode(session, Resolution.serialId));
                session.save(resolution);

                smartphone.setResolutionId(resolution);
                //other

                session.save(smartphone);
                break;
            }
            transaction.commit();
            sessionFactory.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "index";
    }
@RequestMapping(value={“apple”},method=RequestMethod.GET)
公共字符串解析(ModelMap模型){
试一试{
字符串appleData=Utilities.getResourceAsString(这是“json/apple.json”);
JSONArray数组=新的JSONArray(appleData);
Session Session=sessionFactory.openSession();
事务=会话。beginTransaction();
对于(int i=0;i
[编辑:添加]分辨率类别:

@Entity
public class Resolution {
    public static final int serialId = 106;

    private int id;
    private Integer height;
    private Integer width;
    private Type typeId;
    private Collection<Smartphone> resolutionId;

    @Id
    @Column(name = "id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "height")
    public Integer getHeight() {
        return height;
    }

    public void setHeight(Integer height) {
        this.height = height;
    }

    @Basic
    @Column(name = "width")
    public Integer getWidth() {
        return width;
    }

    public void setWidth(Integer width) {
        this.width = width;
    }

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "type_id", referencedColumnName = "id", nullable = false)
    public Type getTypeId() {
        return typeId;
    }

    public void setTypeId(Type typeId) {
        this.typeId = typeId;
    }

    @LazyCollection(LazyCollectionOption.FALSE)
    @OneToMany(mappedBy = "resolutionId")
    public Collection<Smartphone> getResolutionId() {
        return resolutionId;
    }

    public void setResolutionId(Collection<Smartphone> resolutionId) {
        this.resolutionId = resolutionId;
    }
}
@实体
公共类决议{
公共静态final int serialId=106;
私有int-id;
私有整数高度;
私有整数宽度;
私有类型typeId;
私人收藏决议;
@身份证
@列(name=“id”)
公共int getId(){
返回id;
}
公共无效集合id(内部id){
this.id=id;
}
@基本的
@列(name=“height”)
公共整数getHeight(){
返回高度;
}
公共空间设置高度(整数高度){
高度=高度;
}
@基本的
@列(name=“width”)
公共整数getWidth(){
返回宽度;
}
公共void setWidth(整数宽度){
这个。宽度=宽度;
}
@manytone(fetch=FetchType.EAGER)
@JoinColumn(name=“type\u id”,referencedColumnName=“id”,nullable=false)
公共类型getTypeId(){
返回typeId;
}
公共无效setTypeId(类型typeId){
this.typeId=typeId;
}
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(mappedBy=“resolutionId”)
公共集合getResolutionId(){
返回解析ID;
}
公共无效setResolutionId(集合resolutionId){
this.resolutionId=resolutionId;
}
}

您试图
分辨率添加/更新
行,该行基于
智能手机中存储的值,在
id
字段中没有有效值

您必须首先将行插入到
分辨率表中。

几乎可以。您必须为
解析添加上面的
getId()
方法以及下面的类似代码。可能在save方法调用之后,您的
分辨率
对象始终为0,作为
id

@Column(name = "id", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)

保存“smartphone”时,它引用的“分辨率”应该是数据库中的持久实体。是的,我正在使用session.save()。我应该使用new transaction保存新对象吗?请查收。我添加了源代码。对我来说也是,但它不起作用。我添加了
解析
类源代码。是的,我正在使用
session.save()
。我应该使用new transaction保存新对象吗?