草庐IT

java - Hibernate 无法添加或更新子行 : a foreign key constraint fails

coder 2023-10-19 原文

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

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";
    }

[编辑:添加] 解析类:

@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;
    }
}

最佳答案

差不多好了。您必须为 Resolution 类和下面的类似代码添加上面的 getId() 方法。可能您的 resolution 对象在保存方法调用后始终为 0 作为 id

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

关于java - Hibernate 无法添加或更新子行 : a foreign key constraint fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39456480/

有关java - Hibernate 无法添加或更新子行 : a foreign key constraint fails的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  4. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  5. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  6. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  7. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  8. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  9. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  10. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

随机推荐