org.hibernate.exception.ConstraintViolationException:无法执行语句

时间:2015-12-22 05:41:36

标签: java hibernate

当我尝试添加应用和应用设置时,我收到以下错误。 以下是详细的错误消息:

  

org.hibernate.exception.ConstraintViolationException:不能   执行声明   org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:72)     在   org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)     在   org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)     在   org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)     在   org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)     在   org.hibernate.id.IdentityGenerator $ GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)     在   org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)     在   org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)     在   org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)     在   org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)     在org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:492)     在   org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:197)     在   org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:181)     在   org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:216)     在   org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:334)     在   org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:289)     在   org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:195)     在   org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)     在   org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)     在   org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)     在   org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)     在   org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)     在   org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)     在org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)     在org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)at   org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)at   com.ips.tvadmindao.services.TVAppService.addTVappsWithSettings(TVAppService.java:237)     在TVAppserviseTest.testsSaveApps(TVAppserviseTest.java:46)at   sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)     在   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     在java.lang.reflect.Method.invoke(Method.java:606)at   org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall(FrameworkMethod.java:50)     在   org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)     在   org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)     在   org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)     在   org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)     在   org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)     在org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)at   org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)     在   org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)     在org.junit.runners.ParentRunner $ 3.run(ParentRunner.java:290)at at   org.junit.runners.ParentRunner $ 1.schedule(ParentRunner.java:71)at at   org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)at at   org.junit.runners.ParentRunner.access $ 000(ParentRunner.java:58)at at   org.junit.runners.ParentRunner $ 2.evaluate(ParentRunner.java:268)at at   org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)     在   org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)     在org.junit.runners.ParentRunner.run(ParentRunner.java:363)at   org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)     在   org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)   引起:   com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:   专栏' company_id'不能为空   sun.reflect.NativeConstructorAccessorImpl.newInstance0(本机方法)     在   sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)     在   sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)     at java.lang.reflect.Constructor.newInstance(Constructor.java:526)     在com.mysql.jdbc.Util.handleNewInstance(Util.java:400)at   com.mysql.jdbc.Util.getInstance(Util.java:383)at   com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)at at   com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847)at at   com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783)at at   com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447)at at   com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594)at at   com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)at   com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901)     在   com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2113)     在   com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2049)     在   com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2034)     在   com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:147)     在   org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)     ......还有50个

     

2015-12-21 21:23:15 DEBUG SqlExceptionHelper:139 - 无法执行   声明[不适用]       com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:   专栏' company_id'不能为空         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)         at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)         at java.lang.reflect.Constructor.newInstance(Constructor.java:526)         在com.mysql.jdbc.Util.handleNewInstance(Util.java:400)         在com.mysql.jdbc.Util.getInstance(Util.java:383)         在com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)         在com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847)         在com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783)         在com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447)         在com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594)         在com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)         在com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901)         在com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2113)         在com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2049)         在com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2034)         在com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:147)         at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)         at org.hibernate.id.IdentityGenerator $ GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)         在org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)         在org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)         在org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)         在org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)         在org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:492)         在org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:197)         在org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:181)         在org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:216)         在org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:334)         at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:289)         在org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:195)         at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)         at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)         at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)         在org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)         在org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)         在org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)         在org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)         在org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)         在org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)         在com.ips.tvadmindao.services.TVAppService.addTVappsWithSettings(TVAppService.java:237)         在TVAppserviseTest.testsSaveApps(TVAppserviseTest.java:46)         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)         at java.lang.reflect.Method.invoke(Method.java:606)         在org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall(FrameworkMethod.java:50)         在org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)         在org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)         在org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)         在org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)         在org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)         在org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)         在org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)         在org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)         在org.junit.runners.ParentRunner $ 3.run(ParentRunner.java:290)         在org.junit.runners.ParentRunner $ 1.schedule(ParentRunner.java:71)         在org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)         在org.junit.runners.ParentRunner.access $ 000(ParentRunner.java:58)         在org.junit.runners.ParentRunner $ 2.evaluate(ParentRunner.java:268)         在org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)         在org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)         在org.junit.runners.ParentRunner.run(ParentRunner.java:363)         在org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)         在org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)         在org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)         在org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)         在org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)         在org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)       2015-12-21 21:23:15 WARN SqlExceptionHelper:144 - SQL错误:1048,SQLState:23000       2015-12-21 21:23:15错误SqlExceptionHelper:146 - Column' company_id'不能为空

这是junit测试

@Test
    public void testsSaveApps() {
        List<AppSetting> settings = new ArrayList<AppSetting>();
        //int settingid = types.getMaxSettingId()+1;
        settings.add(createSettingsOne());
        settings.add(createSettingsTwo());
        assertEquals(true,types.addTVappsWithSettings( 1,13, "App1", settings, "Danka" ) );

    }

    private static AppSetting createSettingsOne(){

        AppSetting setting = new AppSetting();
        setting.setCreated_by("Kasun");
        LocalDateTime time = new LocalDateTime();
        setting.setCreated_time(time);
        setting.setDisplayOrder(1);
        setting.setEditable(true);
        setting.setSettings_key("url");
        setting.setSettings_value("www.google.com");
        setting.setUpdated_time(time);
        setting.setUpdated_by("Kasun");
        //setting.setSettings_id(settingid);
        return setting;
    }
    private static AppSetting createSettingsTwo(){

        AppSetting setting = new AppSetting();
        setting.setCreated_by("Kasun");
        LocalDateTime time = new LocalDateTime();
        setting.setCreated_time(time);
        setting.setDisplayOrder(2);
        setting.setEditable(true);
        setting.setSettings_key("url2");
        setting.setSettings_value("www.CBC.com");
        setting.setUpdated_time(time);
        setting.setUpdated_by("Kasun");
        //setting.setSettings_id(settingid);

        return setting;
    }

这是应用和设置保存方法

public boolean addTVappsWithSettings(int appTypeId,int companyid, String appName, List<AppSetting> settings, String createdBy) {
    //set properties of the app to persist
    App app = new App();

    //app.setSettings_id(settingid);
//  app.setSettings_id(settingid);
    app.setApp_id(appTypeId);
    app.setCompany_id(companyid);
    app.setApp_name(appName);
    app.setCreated_by(createdBy);
    LocalDateTime created_time = new LocalDateTime();
    app.setCreated_time(created_time);
    app.setUpdated_by(createdBy);
    app.setUpdated_time(created_time);
    app.setEnable(true);
    app.setapps(settings);
    session.save(app);
    if (!HibernateUtil.INSTANCE.commitTransaction())
        return false;
    return true;
}

这些是DAO课程。

@Entity
@Table(name="company")
public class Company {
    @Id  //primary key
    @GeneratedValue(strategy = GenerationType.IDENTITY)//strategy for generating auto generated number
    @Column(name= "company_id", nullable = false)
    private int company_id; 

    @OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
    @Fetch(value = FetchMode.SUBSELECT)
    @JoinColumn(name = "company_id", nullable = false)
    private List<App> threatviewapps = new ArrayList<App>();

    @NotEmpty
    @Column(name= "short_name", nullable = false)
    private String short_name;

    @NotEmpty
    @Column(name= "company_description", nullable = false)
    private String company_description;

    @NotEmpty
    @Column(name= "company_name", nullable = false)
    private String company_name;

    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name= "created_time", nullable = false)
    private LocalDateTime created_time;

    @Column(name= "created_by", nullable = false)
    private String created_by;

    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name= "update_time", nullable = false)
    private LocalDateTime update_time;

    @Column(name= "updated_by", nullable = false)
    private String updated_by; 

    @Column(name= "enable", nullable = false)
    private boolean enable;

这是App DAO

@Entity
@Table(name = "apps")
public class App {

    @Id // primary key
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Column(name = "settings_id", insertable = false, updatable = false)
    private int settings_id;


    @Column(name = "app_id", nullable = false)
    private int app_id;

/*  @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "settings_id", nullable = false)
    private List<AppSetting> tvsettings = new ArrayList<AppSetting>();*/

    @ElementCollection
    @CollectionTable(name="threatview_app_settings",joinColumns = @JoinColumn(name = "settings_id"))
    private List<AppSetting> tvsettings = new ArrayList<AppSetting>();


    @Column(name = "company_id", insertable = false, updatable = false)
    private int company_id;

    @Column(name = "app_name", nullable = false)
    private String app_name;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name = "created_time", nullable = false)
    private LocalDateTime created_time;

    @Column(name = "created_by", nullable = false)
    private String created_by;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name = "updated_time", nullable = false)
    private LocalDateTime updated_time;

    @Column(name = "updated_by", nullable = false)
    private String updated_by;

    @Column(name = "enable", nullable = false)
    private boolean enable;

为什么我会收到上述错误?如果您需要更多信息,请告诉我们。

更新

@Entity
@IdClass(SettingIDKey.class)
@Table(name = "app_settings")
public class AppSetting {


    @Id
    private int settings_id;

    @Id
    private String settings_key;


    @Column(name = "settings_value", nullable = false)
    private String settings_value;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name = "created_time", nullable = false)
    private LocalDateTime created_time;

    @Column(name = "created_by", nullable = false)
    private String created_by;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name = "updated_time", nullable = false)
    private LocalDateTime updated_time;

    @Column(name = "updated_by", nullable = false)
    private String updated_by;

    @Column(name = "editable", nullable = false)
    private boolean editable;

    @Column(name = "enable", nullable = false)
    private boolean enable;

    @Column(name = "display_order", nullable = false)
    private int displayOrder;

4 个答案:

答案 0 :(得分:4)

在您的情况下,您已将OneToMany作为company_id的拥有方。即公司类拥有一方。

在此方案中,插入App记录会导致两个查询,一个插入和一个更新。首先是insert语句,它在没有company_id的情况下执行插入到App表中(因为这不是拥有方),然后它会触发更新查询来更新company_id。因此,要使第一个insert语句成功,它需要company_id为数据库中的空字段。否则会抛出ConstraintViolationException。

如果您将ManyToOne作为拥有方,那么它会在App表中生成一个insert语句。因此,在这种情况下,company_id字段可以为null。

因此,我看到两个选项:

  1. 将company_id设为数据库中的空字段。
  2. 让ManyToOne成为拥有者。
  3. 以下输出有助于理解上述陈述。我有Forest类,它与Tree类具有OneToMany关系。

    与许多人一对一的

    Hibernate: values identity_val_local()
    Hibernate: insert into Tree (id, "COUNT", FOREST, name, version) values (default, ?, ?, ?, ?)
    

    与一对多的一面

    Hibernate: insert into Tree (id, "COUNT", name, version) values (default, ?, ?, ?)
    Hibernate: values identity_val_local()
    Hibernate: update Tree set FOREST=?, index=? where id=?
    

答案 1 :(得分:0)

问题似乎出现在App.java

@Column(name = "company_id", insertable = false, updatable = false)
private int company_id;

通过设置insertable = false,您告诉Hibernate不要将其包含在INSERT语句中。有了这个和updatable = false,如果没有明确的查询,你就永远无法设置它。

答案 2 :(得分:0)

在您的表单中

查看company_id antite的名称,它与数据库中的名称相同。如果是,则必须在表单级别提供公司ID。

答案 3 :(得分:-1)

我有同样的错误。我试图保存具有空值的实体。(数据库对A列具有Not Null约束,并且实体中的列具有空值)。