当前位置: 首页 > 知识库问答 >
问题:

org.hibernate.exception.ConstraintViolationException(在hibernate中带有onetomany注释)

云建木
2023-03-14

我是一个新的探索Spring启动和冬眠,并面临一个问题,我认为这并不是新的。然而,在所有的建议都到位的情况下,我仍然找不到一个方法来解决我目前面临的问题。

你们谁能指出我错在哪里吗?

以下是场景-

我有一个Category类,并且Category类的每个实例可以有许多子Category的实例。

我已经使用@OneTomany注释设置了关系。然而,当试图将记录保存到数据库时,我面临的是org.hibernate.exception.ConstraintViolationException(带有异常)报告的外键值不能为空。

类别.类

import java.util.Date;
import java.util.Set;


import javax.persistence.JoinColumn;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.springframework.context.annotation.Scope;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

@Entity
@Table(name="Category")
@Scope("session")
@EntityListeners(AuditingEntityListener.class)
public class Category {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Category_Id")
    private Long Id;

    private String CategoryName;

    private String CategoryValue;

    @Column(name = "IsActive", columnDefinition = "BOOLEAN")
    private Boolean IsActive;

//  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "category")
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "category")
//  @JoinTable(name = "Category_SubCategory", joinColumns = { @JoinColumn(name = "Category_Id") }, inverseJoinColumns = { @JoinColumn(name = "Sub_Category_Id") })
    private Set<SubCategory> SubCategories;

    @CreatedBy
    @Column(nullable = false, updatable = false)
    private String CreatedBy;

    @CreatedDate
    @Column(nullable = false, updatable = false)
    private Date CreatedDate;

    @LastModifiedBy
    @Column(nullable = false)
    private String ModifiedBy;

    @LastModifiedDate
    @Column(nullable = false)
    private Date ModifiedDate;

    public Long getId() {
        return Id;
    }

    public void setId(Long id) {
        Id = id;
    }

    public String getCategoryName() {
        return CategoryName;
    }

    public void setCategoryName(String categoryName) {
        CategoryName = categoryName;
    }

    public String getCategoryValue() {
        return CategoryValue;
    }

    public void setCategoryValue(String categoryValue) {
        CategoryValue = categoryValue;
    }

    public Boolean getIsActive() {
        return IsActive;
    }

    public void setIsActive(Boolean isActive) {
        IsActive = isActive;
    }

    public Set<SubCategory> getSubCategories() {
        return SubCategories;
    }

    public void setSubCategories(Set<SubCategory> subCategories) {
        SubCategories = subCategories;
    }

    public String getCreatedBy() {
        return CreatedBy;
    }

    public void setCreatedBy(String createdBy) {
        CreatedBy = createdBy;
    }

    public Date getCreatedDate() {
        return CreatedDate;
    }

    public void setCreatedDate(Date createdDate) {
        CreatedDate = createdDate;
    }

    public String getModifiedBy() {
        return ModifiedBy;
    }

    public void setModifiedBy(String modifiedBy) {
        ModifiedBy = modifiedBy;
    }

    public Date getModifiedDate() {
        return ModifiedDate;
    }

    public void setModifiedDate(Date modifiedDate) {
        ModifiedDate = modifiedDate;
    }

}

Subcategory.Class

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.springframework.context.annotation.Scope;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

@Entity
@Table(name="SubCategory")
@Scope("session")
@EntityListeners(AuditingEntityListener.class)
public class SubCategory {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Sub_Category_Id")
    private Long Id;

    private String SubCategoryName;

    private String SubCategoryValue;

    @Column(name = "IsActive", columnDefinition = "BOOLEAN")
    private Boolean IsActive;

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "Category_Id", nullable = false)
    private Category category;

    @CreatedBy
    @Column(nullable = false, updatable = false)
    private String CreatedBy;

    @CreatedDate
    @Column(nullable = false, updatable = false)
    private Date CreatedDate;

    @LastModifiedBy
    @Column(nullable = false)
    private String ModifiedBy;

    @LastModifiedDate
    @Column(nullable = false)
    private Date ModifiedDate;

    public Long getId() {
        return Id;
    }

    public void setId(Long id) {
        Id = id;
    }

    public String getSubCategoryName() {
        return SubCategoryName;
    }

    public void setSubCategoryName(String subCategoryName) {
        SubCategoryName = subCategoryName;
    }

    public String getSubCategoryValue() {
        return SubCategoryValue;
    }

    public void setSubCategoryValue(String subCategoryValue) {
        SubCategoryValue = subCategoryValue;
    }

    public Boolean getIsActive() {
        return IsActive;
    }

    public void setIsActive(Boolean isActive) {
        IsActive = isActive;
    }

    public String getCreatedBy() {
        return CreatedBy;
    }

    public void setCreatedBy(String createdBy) {
        CreatedBy = createdBy;
    }

    public Date getCreatedDate() {
        return CreatedDate;
    }

    public void setCreatedDate(Date createdDate) {
        CreatedDate = createdDate;
    }

    public String getModifiedBy() {
        return ModifiedBy;
    }

    public void setModifiedBy(String modifiedBy) {
        ModifiedBy = modifiedBy;
    }

    public Date getModifiedDate() {
        return ModifiedDate;
    }

    public void setModifiedDate(Date modifiedDate) {
        ModifiedDate = modifiedDate;
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }



}

ServiceImpl-

@Override
    public void save(Category category) {

        Set<SubCategory> subCategoryRec = category.getSubCategories();
        if(subCategoryRec != null && subCategoryRec.size() > 0) {
            for(SubCategory rec: subCategoryRec) {
                try {
                    subcategoryRepository.save(rec);
                }catch (Exception ex) {
                    ex.printStackTrace();
                }

            }
        }

        try {
            categoryRepository.save(category);
        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
        at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
        at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
        at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
        at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2855)
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3426)
        at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
        at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:619)
        at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:273)
        at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:254)
        at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:299)
        at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:317)
        at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:272)
        at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:178)
        at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:109)
        at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67)
        at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189)
        at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132)
        at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
        at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:775)
        at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:748)
        at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:753)
        at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1146)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:347)
        at com.sun.proxy.$Proxy113.persist(Unknown Source)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
        at com.sun.proxy.$Proxy113.persist(Unknown Source)
        at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:508)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:513)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:498)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:475)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
        ... 104 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'category_id' cannot be null

共有1个答案

袁翰池
2023-03-14

原因是您试图在保存父对象之前保存子对象。因此,将实现更改为首先保存父对象,然后保存子对象,如下所示。

    categoryRepository.save(category);
    Set<SubCategory> subCategoryRec = category.getSubCategories();
    if(subCategoryRec != null && subCategoryRec.size() > 0) {
        for(SubCategory rec: subCategoryRec) {
            subcategoryRepository.save(rec);  
        }
    }
 类似资料:
  • 我有一个数据库,它的一些表之间有关系,例如,我必须表Person和Company,它们的Id之间有一个一对多的关系,这是在Hibernate生成的表名Person_Company中构建的。当我在java中使用@onetomany和@manytoone注释时,它在它们之间建立了关系,但不是根据Person_Company表,我只使用表的Id什么是正确的注释?

  • 我们必须在可选元素“mappedby”中指定什么。是特定模型的table_name还是classname? 哪个是正确的? 这个

  • 问题内容: 这是我在堆栈上的第一个问题,所以请谨慎:D 我正在尝试创建hibernate的OneToMany关系。当我尝试从数据库中获取一些数据时,出现了StackOverflowError。但是,当我删除OneToMany部分时,一切正常。这是我的REST服务的一部分,目前它可以在VMware vFabric Server和MySQL DB上运行。 获取示例: MySQL脚本: 类: 错误: 编

  • 我在Hibernate(4.3.0)中遇到了一个问题,其中as单向@OneToMany返回重复项。 我的数据库结构(MySQL与InnoDB),其中作为“条目”表与“entry_address”表有1: N关系。“条目”表是主表,“entry_address”是“条目”表的子表。 下面是“entry”实体的最小代码。 以下是“entry_address”实体的最小代码: 这是Hibernate完成

  • 问题内容: 是否可以在运行时创建hibernate的Entity类(带有注释)?它应与也在运行时中添加的表相关。重要的是,该实体应该对Hibernate可见。一般情况下是否可能,请您给我有关该问题的任何建议吗?我了解,反射是关键字,但需要更多的单词。问候。 问题答案: 在这种情况下,您可能希望在运行时以编程方式创建Hibernate Session Factory,并传入创建的新映射,请访问htt

  • 我正在使用hibernate注释,为此,在中,我需要添加注释类,比如这里p是包名,Customer是注释bean。 假设我有20个此类注释类,这意味着我必须为该类编写20个映射行。在Spring中,有一个属性,可以用来注册/加载指定包中的所有hibernate注释类。 既然我没有使用Spring,那么我们可以在Hibernate中拥有相同的功能吗?