简体   繁体   中英

java.sql.BatchUpdateException: Cannot add or update a child row: a foreign key constraint fails ERROR

I've been at this problem for 2 weeks now, and I've come across several solutions on Stackoverflow, and other forums, but I am still unable to find a right answer.

I have 3 Tables in my Database: Users , UserGroups , and Groups .

The Users have a one-to-many relationship with UserGroups , and UserGroups many-to-one with Users .

The relationship with Groups and UserGroups is the same as Users .

I am using JSF + HIBERNATE + PrimeFaces to construct my application. So I have 3 Data tables in my view - 1 displays the list of users in my database, the other displays the list of groups, and lastly the UserGroup data table displays the list of users and groups.

so this error

java.sql.BatchUpdateException: Cannot add or update a child row: a foreign key constraint fails

APPEARS WHEN I select a user and a group, and I click the "Insert" button. The user and the group does not get inserted into the database table.

I do not think its a mapping error because I tried running a test class by manually inserting values into the database, and it works fine. Can anyone help me out with this?

USER model:

    @OneToMany(mappedBy="user", targetEntity=UsuariosGrupos.class,fetch= FetchType.EAGER,cascade= CascadeType.ALL)
    private List<UsuariosGrupos> usuariosgruposList;

    public Usuarios() {
    }


    @XmlTransient
    public List<UsuariosGrupos> getUsuariosgruposList() {
        return usuariosgruposList;
    }

    public void setUsuariosgruposList(List<UsuariosGrupos> usuariosgruposList) {
        this.usuariosgruposList = usuariosgruposList;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (idUsuario != null ? idUsuario.hashCode() : 0);
        return hash;
    }



    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Usuarios)) {
            return false;
        }
        Usuarios other = (Usuarios) object;
        if ((this.idUsuario == null && other.idUsuario != null) || (this.idUsuario != null && !this.idUsuario.equals(other.idUsuario))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "br.model.Usuarios[ idUsuario=" + idUsuario + " ]";
    }

}

UserGroups Model:

@Entity
@Table(name = "usuarios_grupos")
public class UsuariosGrupos {

    private Integer id_usuario;
    private Integer id_grupo;

    private Usuarios user;

    @ManyToOne
    @JoinColumn(name="id_usuario", insertable=false, updatable=false)
       public Usuarios getUser() {
        return user;
    }

    public void setUser(Usuarios user) {
        this.user = user;
    }

    @Id
    @GeneratedValue
    public Integer getId_grupo() {
        return id_grupo;
    }

    public void setId_grupo(Integer id_grupo) {
        this.id_grupo = id_grupo;
    }

    public Integer getId_usuario() {
        return id_usuario;
    }

    public void setId_usuario(Integer id_usuario) {
        this.id_usuario = id_usuario;
    }
}

Groups model:

    @Entity
    @Table(name="grupos")

    public class Grupos {
        private long id_grupo;
        private String descricao;

        private List<UsuariosGrupos> usergroup;

        @OneToMany(mappedBy = "group", targetEntity = UsuariosGrupos.class, fetch = FetchType.EAGER,
        cascade = CascadeType.ALL)
        public List<UsuariosGrupos> getUsergroup() {
            return usergroup;
        }

        public void setUsergroup(List<UsuariosGrupos> usergroup) {
            this.usergroup = usergroup;
        }

        @Id
        @GeneratedValue
        public String getDescricao() {
            return descricao;
        }

        public void setDescricao(String descricao) {
            this.descricao = descricao;
        }

        public long getId_grupo() {
            return id_grupo;
        }

        public void setId_grupo(long id_grupo) {
            this.id_grupo = id_grupo;
        }    
    }
    `

    Index.xhtml (view) :

          <h:commandButton value="Incluir" actionListener="#{usuariosGruposBean.finishAddUsuariosGrupos}">
                            <f:param name="#{usergroups}" value="#{usergroups}"/>
                        </h:commandButton>

My UserGroups Bean:

   @ManagedBean
@SessionScoped
public class UsuariosGruposBean {

    private Usuarios user;
    private UsuariosGrupos userGroups = new UsuariosGrupos();
    private UsuariosGruposDAO userDAO = new UsuariosGruposDAO();
    private UsuariosGruposDAO grpDAO = new UsuariosGruposDAO();
    private UsuariosGruposDAO userGrpDAO = new UsuariosGruposDAO();
    private List<Usuarios> listOfUsuarios;

    private List<UsuariosGrupos> listOfUserGroups;

    public List<Usuarios> getListOfUsuarios() {
        List<Usuarios> usuariosList = userDAO.retrieveUsuarios();
        listOfUsuarios = usuariosList;
        return listOfUsuarios;
    }



    public List<UsuariosGrupos> getListofUserGroups() {
        List<UsuariosGrupos> userGrpList = userGrpDAO.retrieveUsuariosGrupos();
        listOfUserGroups = userGrpList;
        return listOfUserGroups;
    }




    public Usuarios getUser() {
        return user;
    }

    public void setUser(Usuarios user) {
        this.user = user;
    }

    public UsuariosGrupos getUserGroups() {
        return userGroups;
    }

    public void setUserGroups(UsuariosGrupos userGroups) {
        this.userGroups = userGroups;
    }


    public void finishAddUsuariosGrupos() {
        userGroups.setId_usuario(62);
        userGroups.setId_grupo(2);
        userGrpDAO.saveUsuariosGrupos(userGroups);
        listOfUserGroups = null;
    }



}




    This is the error stack that I face when I attempt to add a user and a group to usergroups:

Out 21, 2011 10:15:26 AM org.hibernate.impl.SessionFactoryObjectFactory addInstance INFO: Not binding factory to JNDI, no JNDI name configured Out 21, 2011 10:15:33 AM org.hibernate.util.JDBCExceptionReporter logExceptions WARNING: SQL Error: 1452, SQLState: 23000 Out 21, 2011 10:15:33 AM org.hibernate.util.JDBCExceptionReporter logExceptions SEVERE: Cannot add or update a child row: a foreign key constraint fails ( social . usuarios_grupos , CONSTRAINT fk_usuarios FOREIGN KEY ( id_usuario ) REFERENCES usuarios ( id_usuario ) ON DELETE NO ACTION ON UPDATE NO ACTION) Out 21, 2011 10:15:33 AM org.hibernate.event.def.AbstractFlushingEventListener performExecutions SEVERE: Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.j dbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141) at java.lang.Thread.run(Thread.java:722) Caused by: java.sql.BatchUpdateException: Cannot add or update a child row: a foreign key constraint fails ( social . usuarios_grupos , CONSTRAINT fk_usuarios FOREIGN KEY ( id_usuario ) REFERENCES usuarios ( id_usuario ) ON DELETE NO ACTION ON UPDATE NO ACTION)

See the underlying generated query by show_sql=true ,

The problem is you are trying to insert/update a reference which isn't exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM