Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.hibernate.exception.ConstraintViolationException: could not execute statement

Tags:

java

hibernate

I am getting the below error, when I try to add a app and app settings. Here is the detailed error message:

org.hibernate.exception.ConstraintViolationException: could not
execute statement   at
org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:72)
    at
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
    at
org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at
org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
    at
org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:492)
    at
org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:197)
    at
org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:181)
    at
org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:216)
    at
org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:334)
    at
org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:289)
    at
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)
    at
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at
org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
    at 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)
    at 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)     at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at
org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)    at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)  at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)     at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)   at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)     at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)    at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at
org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'company_id' cannot be null  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)
    at 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
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847)  at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783)  at
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447)   at
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594)    at
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)     at
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901)
    at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2113)
    at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2049)
    at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2034)
    at
com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:147)
    at
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    ... 50 more






2015-12-21 21:23:15 DEBUG SqlExceptionHelper:139 - could not execute
statement [n/a]
    com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'company_id' cannot be null
        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)
        at 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 com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783)
        at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447)
        at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594)
        at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)
        at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901)
        at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2113)
        at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2049)
        at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2034)
        at 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)
        at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
        at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
        at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:492)
        at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:197)
        at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:181)
        at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:216)
        at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:334)
        at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:289)
        at 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)
        at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
        at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
        at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
        at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
        at 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)
        at 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)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
        at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
    2015-12-21 21:23:15 WARN  SqlExceptionHelper:144 - SQL Error: 1048, SQLState: 23000
    2015-12-21 21:23:15 ERROR SqlExceptionHelper:146 - Column 'company_id' cannot be null

Here is the junit test

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

This is the app and settings saving method

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

These are DAO classes.

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

This is the 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;

Why do I get the above error? If you guys need any more information, please let me know.

Update

@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;
like image 429
newday Avatar asked Dec 22 '15 05:12

newday


1 Answers

In your case you have made OneToMany as owning side for company_id. i.e, Company class is owning side.

In this scenario inserting a App record results in two queries one insert and one update. First is the insert statement that performs an insert into App table without company_id (as this is not owning side) and then it fires an update query to update the company_id. So for the first insert statement to succeed it requires company_id to be a null field in database. Else it will throw ConstraintViolationException.

If you make ManyToOne as owning side, then it results in a single insert statement in App table. So company_id field can be null in this case.

So with this, I see two options:

  1. Either make company_id as null field in database.
  2. Make ManyToOne as owning side.

The below output helps in understanding the above statements. I have Forest class which has OneToMany relation with Tree class.

WITH MANY-TO-ONE SIDE OWNING

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

WITH ONE-TO-MANY SIDE OWNING

Hibernate: insert into Tree (id, "COUNT", name, version) values (default, ?, ?, ?)
Hibernate: values identity_val_local()
Hibernate: update Tree set FOREST=?, index=? where id=?
like image 65
Madhusudana Reddy Sunnapu Avatar answered Oct 23 '22 11:10

Madhusudana Reddy Sunnapu