org.hibernate.exception.ConstraintViolationException与hibernate中的onetomany注释

时间:2018-04-04 08:18:46

标签: spring hibernate spring-data-jpa one-to-many

我是新手探索春季启动和休眠并面临某个问题,我认为这不是新问题。但是,根据所有建议,我仍然无法找到解决我目前面临的问题的方法。

你们中的任何人都可以指出我出错的地方吗?

以下是情景 -

我有一个Category类,类别类的每个实例都可以有很多子类实例。

我使用@OneToMany注释设置了关系。但是当我试图将记录保存到数据库时,我正面临着 org.hibernate.exception.ConstraintViolationException,异常报告说外键值不能为NULL。

请在下面找到课程声明

Category.class

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

2 个答案:

答案 0 :(得分:2)

原因是您在保存父对象之前尝试保存子对象。因此,将实现更改为第一个保存父对象,后跟子对象,如下所示。

myClass

答案 1 :(得分:0)

嗯,实际上你不应该手动执行此操作。对于这个确切的问题,您应该使用 CASCADING

来自here

  

级联中,完成一次操作(保存,更新和删除)后,它决定是否需要在与每个操作有关系的其他实体上调用其他操作(保存,更新和删除)其他

所以这基本上可以解决你的问题:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "category", cascade=CascadeType.PERSIST)
private Set<SubCategory> SubCategories;

如果您想要DELETE等的不同行为,您可以选择几种级联类型:

  

Java Persistence Architecture支持的级联类型如下:

     

CascadeType.PERSIST :表示save()或persist()操作级联到相关实体。    CascadeType.MERGE :表示合并拥有实体时合并相关实体。

     

CascadeType.REFRESH :对refresh()操作执行相同的操作。    CascadeType.REMOVE :删除拥有实体后,删除与此设置相关的所有相关实体。

     

CascadeType.DETACH :如果发生“手动分离”,则会分离所有相关实体。    CascadeType.ALL :是所有上述级联操作的简写。

请参阅here

编辑:(参考其他建议的答案): 调用.save不会自动提交事务,如果你真的想手动执行,请尝试.saveAndFlush,但我建议使用 Cascade 。 请参阅:Difference between save and saveAndFlush in Spring data jpa