I have following two tables
CREATE TABLE event_type_master (
Event_Type_Code varchar(128) NOT NULL,
PRIMARY KEY (Event_Type_Code)
)
CREATE TABLE event_master (
Event_Code varchar(128) NOT NULL,
Event_Type_Code varchar(128) NOT NULL,
PRIMARY KEY (Event_Code,Event_Type_Code),
CONSTRAINT FK1 FOREIGN KEY (Event_Type_Code) REFERENCES event_type_master (Event_Type_Code)
)
Now I have create model classes for the above relation as follow
EventMaster Class:-
#Entity
#Table(name="event_master")
public class EventMaster implements java.io.Serializable {
private EventMasterId id;
private EventTypeMaster eventTypeMaster;
private String eventName;
public EventMaster() {
}
public EventMaster(EventMasterId id, EventTypeMaster eventTypeMaster) {
this.id = id;
this.eventTypeMaster = eventTypeMaster;
}
public EventMaster(EventMasterId id, EventTypeMaster eventTypeMaster) {
this.id = id;
this.eventTypeMaster = eventTypeMaster;
this.eventName = eventName;
}
#EmbeddedId
#AttributeOverrides( {
#AttributeOverride(name="eventCode", column=#Column(name="Event_Code", nullable=false, length=128) ),
#AttributeOverride(name="eventTypeCode", column=#Column(name="Event_Type_Code", nullable=false, length=128) ) } )
public EventMasterId getId() {
return this.id;
}
public void setId(EventMasterId id) {
this.id = id;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="Event_Type_Code",referencedColumnName = "Event_Type_Code", nullable=false, insertable=false, updatable=false)
public EventTypeMaster getEventTypeMaster()
{
return this.eventTypeMaster;
}
public void setEventTypeMaster(EventTypeMaster eventTypeMaster) {
this.eventTypeMaster = eventTypeMaster;
}
}
EventMasterId Class for Compound Primary Key setting:-
#Embeddable
public class EventMasterId implements java.io.Serializable {
private String eventCode;
private String eventTypeCode;
public EventMasterId() {
}
public EventMasterId(String eventCode, String eventTypeCode)
{
this.eventCode = eventCode;
this.eventTypeCode = eventTypeCode;
}
#Column(name="Event_Code", nullable=false, length=128)
public String getEventCode() {
return this.eventCode;
}
public void setEventCode(String eventCode) {
this.eventCode = eventCode;
}
#Column(name="Event_Type_Code", nullable=false, length=128)
public String getEventTypeCode() {
return this.eventTypeCode;
}
public void setEventTypeCode(String eventTypeCode) {
this.eventTypeCode = eventTypeCode;
}
public boolean equals(Object other) {
........
}
public int hashCode() {
..........
}
}
EventTypeMaster Class
#Entity
#Table(name="event_type_master")
public class EventTypeMaster implements java.io.Serializable {
private String eventTypeCode;
private String eventTypeName;
private Set<EventMaster> eventMasters = new HashSet<EventMaster>(0);
public EventTypeMaster() {
}
public EventTypeMaster(String eventTypeCode) {
this.eventTypeCode = eventTypeCode;
}
public EventTypeMaster(String eventTypeCode, String eventTypeName, Set eventMasters) {
this.eventTypeCode = eventTypeCode;
this.eventTypeName = eventTypeName;
this.eventMasters = eventMasters;
}
#Id
#Column(name="Event_Type_Code", unique=true, nullable=false, length=128)
public String getEventTypeCode() {
return this.eventTypeCode;
}
public void setEventTypeCode(String eventTypeCode) {
this.eventTypeCode = eventTypeCode;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="eventTypeMaster")
#JoinColumn(name="Event_Type_Code", referencedColumnName = "Event_Type_Code")
public Set<EventMaster> getEventMasters() {
return this.eventMasters;
}
public void setEventMasters(Set<EventMaster> eventMasters) {
this.eventMasters = eventMasters;
}
}
After setting All I created a HebernateUtil Class using Netbeans to connect to HibernateSession Factory and tried to Test adding a record to event_master table as follow
Session session = null;
session = NewHibernateUtil.getSessionFactory().getCurrentSession();
try {
org.hibernate.Transaction tx = session.beginTransaction();
EventMasterId key1=new EventMasterId();
EventTypeMaster eTypeMaster1=new EventTypeMaster();
eTypeMaster1=(EventTypeMaster)session.load(EventTypeMaster.class, "e1");
key1.setEventCode(eTypeMaster1.getEventTypeCode());
key1.setEventCode("Test_Event_Code");
EventMaster em=new EventMaster();
em.setId(key1);
em.setEventTypeMaster(eTypeMaster1);
em.setEventDesc("Event Description");
session.save(em);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
But I am getting following Error
Hibernate: insert into event_master (Create_DTTM, Created_By, Event_Desc, Event_Name, Event_Short_Name, Last_Mod_By, Last_Mod_DTTM, Event_Code, Event_Type_Code) values (?, ?, ?, ?, ?, ?, ?, ?, ?)
1473 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1048, SQLState: 23000
1473 [main] ERROR org.hibernate.util.JDBCExceptionReporter - Column 'Event_Type_Code' cannot be null
1474 [main] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1028)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:366)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at test.NewMain.main(NewMain.java:46)
Caused by: java.sql.BatchUpdateException: Column 'Event_Type_Code' cannot be null
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1666)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1082)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
Please help me to solve this.
I think you have a typo.
key1.setEventCode(eTypeMaster1.getEventTypeCode());
key1.setEventCode("Test_Event_Code");
Should the first line be key1.setEventTypeCode.
Related
Tables script:
DROP TABLE IF EXISTS STOCK; CREATE TABLE STOCK ( STOCK_ID INT(10) NOT NULL, STOCK_CODE VARCHAR(10) NOT NULL, STOCK_NAME VARCHAR(20) NOT NULL, PRIMARY KEY (STOCK_ID,STOCK_CODE), KEY STOCK_CODE_IDX (STOCK_CODE) );
DROP TABLE IF EXISTS STOCK_DAILY_RECORD;
CREATE TABLE STOCK_DAILY_RECORD ( RECORD_ID INT(10) NOT NULL, STOCK_CODE VARCHAR(10) NOT NULL, PRICE_OPEN FLOAT(6,2) DEFAULT NULL, PRICE_CLOSE FLOAT(6,2) DEFAULT NULL, PRICE_CHANGE FLOAT(6,2) DEFAULT NULL, VOLUME BIGINT(20) DEFAULT NULL, STOCK_ID INT(10) NOT NULL, PRIMARY KEY (RECORD_ID,STOCK_CODE), KEY FK_STOCK_ID (STOCK_ID,STOCK_CODE), CONSTRAINT FK_STOCK_ID FOREIGN KEY (STOCK_ID,STOCK_CODE) REFERENCES STOCK (STOCK_ID,STOCK_CODE) ) ;
This is main class where I can populate the entity classes to save values in stock and stockdailyrecord tables:
package org.hibernate.HibernateEntity;
import org.hibernate.Session;
import com.model.Stock;
import com.model.StockDailyRecord;
import com.model.StockDailyRecordId;
import com.model.StockId;
/**
* Hello world!
*
*/
public class App
{
public static void main(String[] args) {
System.out.println("Hibernate one to one (Annotation)");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Stock stock = new Stock();
StockId id = new StockId(2, "7052");
stock.setId(id);
stock.setStockName("PADINI");
StockDailyRecord stockDetail = new StockDailyRecord();
StockDailyRecordId id1 = new StockDailyRecordId(101, "7052");
stockDetail.setId(id1);
stockDetail.setPriceChange(200.0f);
stockDetail.setPriceClose(210.0f);
stockDetail.setPriceOpen(120.0f);
stockDetail.setVolume(12l);
stock.getStockDailyRecords().add(stockDetail);
stockDetail.setStock(stock);
session.save(stock);
//session.save(stockDetail);
session.getTransaction().commit();
System.out.println("Done");
}
}
Entity class which is configured with composite key with hibernate embedded and id:
package com.model;
// Generated Jan 12, 2018 8:17:38 AM by Hibernate Tools 5.2.6.Final
import java.util.HashSet;
import java.util.Set;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
/**
* Stock generated by hbm2java
*/
#Entity
#Table(name = "stock", catalog = "testdb")
public class Stock implements java.io.Serializable {
private StockId id;
private String stockName;
private Set<StockDailyRecord> stockDailyRecords = new HashSet<StockDailyRecord>(0);
public Stock() {
}
public Stock(StockId id, String stockName) {
this.id = id;
this.stockName = stockName;
}
public Stock(StockId id, String stockName, Set<StockDailyRecord> stockDailyRecords) {
this.id = id;
this.stockName = stockName;
this.stockDailyRecords = stockDailyRecords;
}
#EmbeddedId
#AttributeOverrides({ #AttributeOverride(name = "stockId", column = #Column(name = "STOCK_ID", nullable = false)),
#AttributeOverride(name = "stockCode", column = #Column(name = "STOCK_CODE", nullable = false, length = 10)) })
public StockId getId() {
return this.id;
}
public void setId(StockId id) {
this.id = id;
}
#Column(name = "STOCK_NAME", nullable = false, length = 20)
public String getStockName() {
return this.stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "stock")
#Cascade(CascadeType.ALL)
public Set<StockDailyRecord> getStockDailyRecords() {
return this.stockDailyRecords;
}
public void setStockDailyRecords(Set<StockDailyRecord> stockDailyRecords) {
this.stockDailyRecords = stockDailyRecords;
}
}
Entity class which is configured with composite key with hibernate embedded and id:
package com.model;
// Generated Jan 12, 2018 8:17:38 AM by Hibernate Tools 5.2.6.Final
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* StockDailyRecord generated by hbm2java
*/
#Entity
#Table(name = "stock_daily_record", catalog = "testdb")
public class StockDailyRecord implements java.io.Serializable {
private StockDailyRecordId id;
private Stock stock;
private Float priceOpen;
private Float priceClose;
private Float priceChange;
private Long volume;
public StockDailyRecord() {
}
public StockDailyRecord(StockDailyRecordId id, Stock stock) {
this.id = id;
this.stock = stock;
}
public StockDailyRecord(StockDailyRecordId id, Stock stock, Float priceOpen, Float priceClose, Float priceChange,
Long volume) {
this.id = id;
this.stock = stock;
this.priceOpen = priceOpen;
this.priceClose = priceClose;
this.priceChange = priceChange;
this.volume = volume;
}
#EmbeddedId
#AttributeOverrides({ #AttributeOverride(name = "recordId", column = #Column(name = "RECORD_ID", nullable = false)),
#AttributeOverride(name = "stockCode", column = #Column(name = "STOCK_CODE", nullable = false, length = 10)) })
public StockDailyRecordId getId() {
return this.id;
}
public void setId(StockDailyRecordId id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumns({
#JoinColumn(name = "STOCK_ID", referencedColumnName = "STOCK_ID", nullable = false, insertable = false, updatable = false),
#JoinColumn(name = "STOCK_CODE", referencedColumnName = "STOCK_CODE", nullable = false, insertable = false, updatable = false) })
public Stock getStock() {
return this.stock;
}
public void setStock(Stock stock) {
this.stock = stock;
}
#Column(name = "PRICE_OPEN", precision = 6)
public Float getPriceOpen() {
return this.priceOpen;
}
public void setPriceOpen(Float priceOpen) {
this.priceOpen = priceOpen;
}
#Column(name = "PRICE_CLOSE", precision = 6)
public Float getPriceClose() {
return this.priceClose;
}
public void setPriceClose(Float priceClose) {
this.priceClose = priceClose;
}
#Column(name = "PRICE_CHANGE", precision = 6)
public Float getPriceChange() {
return this.priceChange;
}
public void setPriceChange(Float priceChange) {
this.priceChange = priceChange;
}
#Column(name = "VOLUME")
public Long getVolume() {
return this.volume;
}
public void setVolume(Long volume) {
this.volume = volume;
}
}
Entity class which is configured with composite key with hibernate embedded and id:
package com.model;
// Generated Jan 12, 2018 8:17:38 AM by Hibernate Tools 5.2.6.Final
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
* StockDailyRecordId generated by hbm2java
*/
#Embeddable
public class StockDailyRecordId implements java.io.Serializable {
private int recordId;
private String stockCode;
public StockDailyRecordId() {
}
public StockDailyRecordId(int recordId, String stockCode) {
this.recordId = recordId;
this.stockCode = stockCode;
}
#Column(name = "RECORD_ID", nullable = false)
public int getRecordId() {
return this.recordId;
}
public void setRecordId(int recordId) {
this.recordId = recordId;
}
#Column(name = "STOCK_CODE", nullable = false, length = 10)
public String getStockCode() {
return this.stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof StockDailyRecordId))
return false;
StockDailyRecordId castOther = (StockDailyRecordId) other;
return (this.getRecordId() == castOther.getRecordId())
&& ((this.getStockCode() == castOther.getStockCode()) || (this.getStockCode() != null
&& castOther.getStockCode() != null && this.getStockCode().equals(castOther.getStockCode())));
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getRecordId();
result = 37 * result + (getStockCode() == null ? 0 : this.getStockCode().hashCode());
return result;
}
}
Entity class which is configured with composite key with hibernate embedded and id:
package com.model;
// Generated Jan 12, 2018 8:17:38 AM by Hibernate Tools 5.2.6.Final
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
* StockId generated by hbm2java
*/
#Embeddable
public class StockId implements java.io.Serializable {
private int stockId;
private String stockCode;
public StockId() {
}
public StockId(int stockId, String stockCode) {
this.stockId = stockId;
this.stockCode = stockCode;
}
#Column(name = "STOCK_ID", nullable = false)
public int getStockId() {
return this.stockId;
}
public void setStockId(int stockId) {
this.stockId = stockId;
}
#Column(name = "STOCK_CODE", nullable = false, length = 10)
public String getStockCode() {
return this.stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof StockId))
return false;
StockId castOther = (StockId) other;
return (this.getStockId() == castOther.getStockId())
&& ((this.getStockCode() == castOther.getStockCode()) || (this.getStockCode() != null
&& castOther.getStockCode() != null && this.getStockCode().equals(castOther.getStockCode())));
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getStockId();
result = 37 * result + (getStockCode() == null ? 0 : this.getStockCode().hashCode());
return result;
}
}
Class used to create a session factory using hibernate configuration:
package org.hibernate.HibernateEntity;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
Stockdailyrecord not getting populated with stock id , please advice.
08:20:05.202 [main] DEBUG org.hibernate.pretty.Printer - listing entities:
08:20:05.203 [main] DEBUG org.hibernate.pretty.Printer - com.model.StockDailyRecord{priceChange=200.0, volume=12, priceClose=210.0, priceOpen=120.0, id=component[recordId,stockCode]{recordId=101, stockCode=7052}, stock=com.model.Stock#component[stockCode,stockId]{stockId=2, stockCode=7052}}
08:20:05.203 [main] DEBUG org.hibernate.pretty.Printer - com.model.Stock{stockName=PADINI, stockDailyRecords=[com.model.StockDailyRecord#component[recordId,stockCode]{recordId=101, stockCode=7052}], id=component[stockCode,stockId]{stockId=2, stockCode=7052}}
08:20:05.205 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
08:20:05.206 [main] DEBUG org.hibernate.SQL - insert into testdb.stock (STOCK_NAME, STOCK_CODE, STOCK_ID) values (?, ?, ?)
08:20:05.207 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - Executing batch size: 1
08:20:05.271 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
08:20:05.271 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
08:20:05.271 [main] DEBUG org.hibernate.SQL - insert into testdb.stock_daily_record (PRICE_CHANGE, PRICE_CLOSE, PRICE_OPEN, VOLUME, RECORD_ID, STOCK_CODE) values (?, ?, ?, ?, ?, ?)
08:20:05.277 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - Executing batch size: 1
08:20:05.300 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
08:20:05.315 [main] DEBUG o.h.util.JDBCExceptionReporter - Could not execute JDBC batch update [insert into testdb.stock_daily_record (PRICE_CHANGE, PRICE_CLOSE, PRICE_OPEN, VOLUME, RECORD_ID, STOCK_CODE) values (?, ?, ?, ?, ?, ?)]
java.sql.BatchUpdateException: Field 'STOCK_ID' doesn't have a default value
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2024) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1449) ~[mysql-connector-java-5.1.15.jar:na]
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70) ~[hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268) ~[hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268) [hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184) [hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) [hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51) [hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216) [hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383) [hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133) [hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.HibernateEntity.App.main(App.java:40) [classes/:na]
Caused by: java.sql.SQLException: Field 'STOCK_ID' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1976) ~[mysql-connector-java-5.1.15.jar:na]
... 11 common frames omitted
08:20:05.316 [main] WARN o.h.util.JDBCExceptionReporter - SQL Error: 1364, SQLState: HY000
08:20:05.316 [main] ERROR o.h.util.JDBCExceptionReporter - Field 'STOCK_ID' doesn't have a default value
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at org.hibernate.HibernateEntity.App.main(App.java:40)
Caused by: java.sql.BatchUpdateException: Field 'STOCK_ID' doesn't have a default value
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2024)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1449)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 8 more
Caused by: java.sql.SQLException: Field 'STOCK_ID' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1976)
... 11 more
Thsi error raised beacuse you not filled field STOCK_ID but its can't be null in database. Add clause AUTO_INCREMENT to defenition of field STOCK_ID in table STOCK:
STOCK_ID INT(10) NOT NULL AUTO_INCREMENT
and to RECORD_ID in table STOCK_DAILY_RECORD:
RECORD_ID INT(10) NOT NULL AUTO_INCREMENT
But remember that STOCK_CODE not null too and you must fill it before insert.
Can you post the code where you create the instance of the entity and save it? The error is self explanatory. You have to set the value of STOCK_ID. Did you want it to be an identity column (auto_increment in mysql)?. If that's the case, change the data model to declare STOCK_ID as identity and add #GeneratedValue(strategy=GenerationType.IDENTITY) for stockId.
getting id = null when I try to insert data in table here is my create table syntax
CREATE TABLE query_builder (
id int(11) NOT NULL AUTO_INCREMENT,
query_title varchar(150) NOT NULL,
sql_query text NOT NULL,
condition varchar(50) NOT NULL,
output_fields varchar(45) NOT NULL,
physician int(11) NOT NULL,
creation_time timestamp NULL DEFAULT CURRENT_TIMESTAMP,
modification_time timestamp NULL DEFAULT NULL,
discription text NOT NULL,
PRIMARY KEY (id),
KEY query_builder_physician_FK_idx (physician),
CONSTRAINT query_builder_physician_FK FOREIGN KEY (physician) REFERENCES physician (Physician_Id) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and entity for this is
import java.io.Serializable;
import javax.xml.bind.annotation.XmlTransient;
public class QueryBuilder implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, unique = true)
private Integer id;
#Basic(optional = false)
#Column(name = "query_title")
private String queryTitle;
#Basic(optional = false)
#Lob
#Column(name = "sql_query")
private String sqlQuery;
#Basic(optional = false)
#Column(name = "condition")
private String condition;
#Basic(optional = false)
#Column(name = "output_fields")
private String outputFields;
#Column(name = "creation_time")
#Temporal(TemporalType.TIMESTAMP)
private Date creationTime;
#Column(name = "modification_time")
#Temporal(TemporalType.TIMESTAMP)
private Date modificationTime;
#Basic(optional = false)
#Lob
#Column(name = "discription")
private String discription;
#JoinColumn(name = "physician", referencedColumnName = "Physician_Id")
#ManyToOne(optional = false)
private Physician physician;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name= "querybuilderId")
private Collection<QueryBuilderCondition> queryBuilderConditionCollection;
public QueryBuilder() {
}
public QueryBuilder(Integer id) {
this.id = id;
}
public QueryBuilder(Integer id, String queryTitle, String sqlQuery, String condition, String outputFields, String discription) {
this.id = id;
this.queryTitle = queryTitle;
this.sqlQuery = sqlQuery;
this.condition = condition;
this.outputFields = outputFields;
this.discription = discription;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getQueryTitle() {
return queryTitle;
}
public void setQueryTitle(String queryTitle) {
this.queryTitle = queryTitle;
}
public String getSqlQuery() {
return sqlQuery;
}
public void setSqlQuery(String sqlQuery) {
this.sqlQuery = sqlQuery;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getOutputFields() {
return outputFields;
}
public void setOutputFields(String outputFields) {
this.outputFields = outputFields;
}
public Date getCreationTime() {
return creationTime;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
public Date getModificationTime() {
return modificationTime;
}
public void setModificationTime(Date modificationTime) {
this.modificationTime = modificationTime;
}
public String getDiscription() {
return discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
public Physician getPhysician() {
return physician;
}
public void setPhysician(Physician physician) {
this.physician = physician;
}
#XmlTransient
public Collection<QueryBuilderCondition> getQueryBuilderConditionCollection() {
return queryBuilderConditionCollection;
}
public void setQueryBuilderConditionCollection(Collection<QueryBuilderCondition> queryBuilderConditionCollection) {
this.queryBuilderConditionCollection = queryBuilderConditionCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 QueryBuilder)) {
return false;
}
QueryBuilder other = (QueryBuilder) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.medikm.entity.QueryBuilder[ id=" + id + " ]";
}
}
to store data in table i uset below code
builder.setCondition(condition);
builder.setCreationTime(new Date());
builder.setDiscription(discription);
builder.setOutputFields(fields);
builder.setPhysician(new PhysicianJpaController().findPhysician(physicianId));
builder.setQueryTitle(title);
builder.setSqlQuery(query);
em.persist(builder);
em.getTransaction().commit();
em.close();
but above code give me an error
this is the error that i got when i try to persist
[EL Warning]: 2016-06-29 14:22:03.749--UnitOfWork(900737)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.DatabaseExceptionInternal Exception: om.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'condition, output_fields, discription, creation_time, modification_time, physici' at line 1Error Code: 1064
Call: INSERT INTO query_builder (query_title, sql_query, condition,output_fields, discription, creation_time, modification_time, physician) VALUES (?, ?, ?, ?, ?, ?, ?, ?) bind => [adfdfafad, SELECT c.Case_Id, c.Age FROM case1 c, patient p, episode e, personal_medical_history pmh, reproductive_history rh WHERE( c.Disease_type = 2 AND c.Primary_Diagnosis_Dt <> '2016/06/22' OR c.Clinical_Stage = 'I'
) AND c.Patient_Id = p.Patient_Id AND e.Case_Id = c.Case_Id
AND pmh.Patient_Id = p.Patient_Id AND rh.Patient_Id = p.Patient_Id
GROUP BY c.Case_Id , "OR", ["ca.Age","ca.aortic_node_positive"], adffda, 2016-06-29 14:22:03.724, null, 200]Query: InsertObjectQuery(com.medikm.entity.QueryBuilder[ id=null ])javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.2.v20100323-r6872):org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'condition, output_fields, discription, creation_time, modification_time, physici' at line 1
Error Code: 1064Call: INSERT INTO query_builder (query_title, sql_query, condition, output_fields, discription, creation_time, modification_time, physician) VALUES (?, ?, ?, ?, ?, ?, ?, ?) bind => [adfdfafad, SELECT c.Case_Id, c.Age FROM case1 c, patient p, episode e, personal_medical_history pmh, reproductive_history rhWHERE( c.Disease_type = 2 AND c.Primary_Diagnosis_Dt <> '2016/06/22' OR c.Clinical_Stage = 'I' ) AND c.Patient_Id = p.Patient_Id
AND e.Case_Id = c.Case_Id AND pmh.Patient_Id = p.Patient_Id
AND rh.Patient_Id = p.Patient_Id GROUP BY c.Case_Id , "OR", ["ca.Age","ca.aortic_node_positive"], adffda, 2016-06-29 14:22:03.724, null, 200]Query: InsertObjectQuery(com.medikm.entity.QueryBuilder[ id=null ])at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:102)at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:63)
please let me know if anything wrong done by me please help... Thank you
Identity sequencing uses special IDENTITY columns in the database to allow the database to automatically assign an id to the object when its row is inserted. Identity columns are supported in many databases, such as MySQL, DB2, SQL Server, Sybase and Postgres. Oracle does not support IDENTITY columns but they can be simulated through using sequence objects and triggers.
If you are using Oracle, that might be the reason.
You can change this code
#GeneratedValue(strategy = GenerationType.IDENTITY)
To this
#GeneratedValue(strategy = GenerationType.SEQUENCE)
PhysicianJpaController() might not find a physician with "physicianId",so you might be trying to do this:
builder.setPhysician(null);
while you have also this:
physician int(11) NOT NULL
hey guys thank you so much for your help issue that I found is in my entity as I check I found that condition is reserved keyword in mysql and because of this I got this error
When I try save instance, I get this strange error:
WARN [15:06:27,917] JDBCExceptionReporter - SQL Error: 20000, SQLState: 42X04
ERROR[15:06:27,917] JDBCExceptionReporter - Column 'ad0b8d24-f596-47cb-9d79-06a3c9c1de26' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then 'ad0b8d24-f596-47cb-9d79-06a3c9c1de26' is not a column in the target table.
Row is not inserted into database.
It looks like it is trying to use scenario_id (uuid) as column name. But why?
I am using this Data Access Object:
public interface ScenarioDao extends GenericDao<Scenario, String> {
public List<Scenario> getScenariosWhereOwner(Person owner);
public List<Scenario> getScenariosWhereOwner(Person person, int LIMIT);
...
}
public interface GenericDao <T, PK extends Serializable>{
public PK create(T newInstance) {
PK primaryKey = (PK) getHibernateTemplate().save(newInstance);
return primaryKey;
}
}
POJO:
#Entity
#Table(name = "SCENARIO")
#XmlRootElement
public class Scenario implements Serializable, Comparable<Scenario> {
private static final long serialVersionUID = -6608175331606366993L;
private String scenarioId;
private Person person;
private ResearchGroup researchGroup;
private String title;
private int scenarioLength;
private boolean privateScenario;
private String description;
private String scenarioName;
private String mimetype;
private Set<History> histories = new HashSet<History>(0);
private Set<Experiment> experiments = new HashSet<Experiment>(0);
private boolean userMemberOfGroup;
private Blob scenarioFile;
private String group;
private Boolean availableFile;
private InputStream fileContentStream;
#Transient
public boolean isUserMemberOfGroup() {
return userMemberOfGroup;
}
public void setUserMemberOfGroup(boolean userMemberOfGroup) {
this.userMemberOfGroup = userMemberOfGroup;
}
#Transient
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
#Transient
public Boolean getAvailableFile() {
return availableFile;
}
public void setAvailableFile(Boolean availableFile) {
this.availableFile = availableFile;
}
public Scenario() {
}
public Scenario(Person person, ResearchGroup researchGroup) {
this.person = person;
this.researchGroup = researchGroup;
}
public Scenario(Person person, ResearchGroup researchGroup, String title,
int scenarioLength, boolean privateScenario, String description,
String scenarioName, String mimetype, Set<History> histories,
Set<Experiment> experiments) {
this.person = person;
this.researchGroup = researchGroup;
this.title = title;
this.scenarioLength = scenarioLength;
this.privateScenario = privateScenario;
this.description = description;
this.scenarioName = scenarioName;
this.mimetype = mimetype;
this.histories = histories;
this.experiments = experiments;
}
#Id
#GeneratedValue(generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid2")
#Column(name = "SCENARIO_ID", nullable = false, length = 36, scale = 0)
public String getScenarioId() {
return this.scenarioId;
}
public void setScenarioId(String scenarioId) {
this.scenarioId = scenarioId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "OWNER_ID", nullable = false)
public Person getPerson() {
return this.person;
}
public void setPerson(Person person) {
this.person = person;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "RESEARCH_GROUP_ID", nullable = false)
public ResearchGroup getResearchGroup() {
return this.researchGroup;
}
public void setResearchGroup(ResearchGroup researchGroup) {
this.researchGroup = researchGroup;
}
#Column(name = "TITLE", unique = true)
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name = "SCENARIO_LENGTH", precision = 22, scale = 0)
public int getScenarioLength() {
return this.scenarioLength;
}
public void setScenarioLength(int scenarioLength) {
this.scenarioLength = scenarioLength;
}
#Column(name = "PRIVATE", precision = 1, scale = 0)
public boolean isPrivateScenario() {
return this.privateScenario;
}
public void setPrivateScenario(boolean privateScenario) {
this.privateScenario = privateScenario;
}
#Lob
#Type(type = "org.hibernate.type.TextType")
#Column(name = "DESCRIPTION")
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "SCENARIO_NAME")
public String getScenarioName() {
return this.scenarioName;
}
public void setScenarioName(String scenarioName) {
this.scenarioName = scenarioName;
}
#Column(name = "MIMETYPE")
public String getMimetype() {
return this.mimetype;
}
public void setMimetype(String mimetype) {
this.mimetype = mimetype;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "scenario")
public Set<History> getHistories() {
return this.histories;
}
public void setHistories(Set<History> histories) {
this.histories = histories;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "scenario")
public Set<Experiment> getExperiments() {
return this.experiments;
}
public void setExperiments(Set<Experiment> experiments) {
this.experiments = experiments;
}
#XmlJavaTypeAdapter(BlobSerializer.class)
#Basic(fetch = FetchType.LAZY)
#Lob
#Column(name = "SCENARIO_FILE", nullable = true)
public Blob getScenarioFile() {
return this.scenarioFile;
}
public void setScenarioFile(Blob scenarioFile) {
this.scenarioFile = scenarioFile;
}
#Override
public int compareTo(Scenario scen) {
return this.title.compareTo(scen.getTitle());
}
public void setFileContentStream(InputStream inputStream) {
this.fileContentStream = inputStream;
}
#Transient
public InputStream getFileContentStream() {
return fileContentStream;
}
}
I try to create it using this code:
scenario = new Scenario();
scenario.setPrivateScenario(some boolean);
scenario.setScenarioLength(some int);
scenario.setDescription(some string);
scenario.setTitle(some string);
scenario.setResearchGroup(some ResearchGroup);
scenario.setPerson(some Person);
All these parameters are set correctly. I am also using GenericDao with other objects without errors. Here is insert statement generated by hibernate:
DEBUG[16:07:25,132] SQL - insert into SCENARIO (DESCRIPTION, MIMETYPE, OWNER_ID, PRIVATE, RESEARCH_GROUP_ID, SCENARIO_FILE, SCENARIO_LENGTH, SCENARIO_NAME, TITLE, SCENARIO_ID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
TRACE[16:07:25,153] BasicBinder - binding parameter [1] as [LONGVARCHAR] - newscenariodescription
TRACE[16:07:25,153] BasicBinder - binding parameter [2] as [VARCHAR] - <null>
TRACE[16:07:25,153] BasicBinder - binding parameter [3] as [VARCHAR] - 9e87924e-3a14-4f82-ad57-c191ead873b5
TRACE[16:07:25,153] BasicBinder - binding parameter [4] as [BIT] - false
TRACE[16:07:25,154] BasicBinder - binding parameter [5] as [VARCHAR] - b399f04f-92a7-427c-9af5-f90055cb1ddc
TRACE[16:07:25,154] BasicBinder - binding parameter [6] as [BLOB] - <null>
TRACE[16:07:25,154] BasicBinder - binding parameter [7] as [INTEGER] - 5
TRACE[16:07:25,154] BasicBinder - binding parameter [8] as [VARCHAR] - <null>
TRACE[16:07:25,154] BasicBinder - binding parameter [9] as [VARCHAR] - newscenario
TRACE[16:07:25,154] BasicBinder - binding parameter [10] as [VARCHAR] - 2d71bcd2-756e-4ffd-82b0-9649d7f05e0b
WARN [16:07:25,180] JDBCExceptionReporter - SQL Error: 20000, SQLState: 38000
ERROR[16:07:25,180] JDBCExceptionReporter - The exception 'java.sql.SQLException: Column '2d71bcd2-756e-4ffd-82b0-9649d7f05e0b' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then '2d71bcd2-756e-4ffd-82b0-9649d7f05e0b' is not a column in the target table.' was thrown while evaluating an expression.
When I try execute:
String query = "insert into SCENARIO (DESCRIPTION, MIMETYPE, OWNER_ID, PRIVATE, RESEARCH_GROUP_ID, FILE_CONTENT, SCENARIO_LENGTH, SCENARIO_NAME, TITLE, SCENARIO_ID) values ('newscenariodescription', NULL, '9e87924e-3a14-4f82-ad57-c191ead873b5', 0, 'b399f04f-92a7-427c-9af5-f90055cb1ddc', NULL, 5, NULL, 'text', '2d71bcd2-756e-4ffd-82b0-9649d7f205e0b')";
session.createSQLQuery(query).executeUpdate();
I get same error.
When I try execute query directly I get very strange error:
SQL Error [20000] [38000]: The exception 'java.lang.NoClassDefFoundError: org/jumpmind/symmetric/db/derby/DerbyFunctions' was thrown while evaluating an expression.
SQL Error [XJ001]: Java exception: 'org/jumpmind/symmetric/db/derby/DerbyFunctions: java.lang.NoClassDefFoundError'.
The exception 'java.lang.NoClassDefFoundError: org/jumpmind/symmetric/db/derby/DerbyFunctions' was thrown while evaluating an expression.
The exception 'java.lang.NoClassDefFoundError: org/jumpmind/symmetric/db/derby/DerbyFunctions' was thrown while evaluating an expression.
Java exception: 'org/jumpmind/symmetric/db/derby/DerbyFunctions: java.lang.NoClassDefFoundError'.
org/jumpmind/symmetric/db/derby/DerbyFunctions
I forget to set capture_big_lobs in trigger table. Changing value to 1 solved problem. However if the column is NULL, then SymmetricDS will throw Null Pointer Exception. I am using 3.5.10, so maybe it's solved in newer versions.
I'm starting to use JPA with the OpenJPA API, and i'm having a problem with the find().
Here are the tables:
CREATE TABLE compania (
ID int(11) NOT NULL,
NOMBRE varchar(45) DEFAULT NULL,
PRIMARY KEY (ID)
)
CREATE TABLE modelo (
ID int(11) NOT NULL,
ID_COMPANIA int(11) DEFAULT NULL,
NOMBRE_MODELO varchar(45) DEFAULT NULL,
PRIMARY KEY (ID),
KEY MODELO_COMPANIA_FK_idx (ID_COMPANIA),
CONSTRAINT MODELO_COMPANIA_FK FOREIGN KEY (ID_COMPANIA) REFERENCES compania (ID)
)
and here are my Entities:
#Entity
public class Compania extends EntityJPA{
private static final long serialVersionUID = 1L;
#Id
private int id;
#Column
private String nombre;
#OneToMany(mappedBy="compania",cascade={CascadeType.ALL})
#JoinColumn(name="ID_COMPANIA", nullable=false)
private List<Modelo> listaModelos;
public Compania() {
}
public int getId() {
return id;
}
public void setId(int idCompania) {
this.id = idCompania;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombreCompania) {
this.nombre = nombreCompania;
}
public List<Modelo> getListaModelos() {
return listaModelos;
}
public void setListaModelos(List<Modelo> listaModelos) {
this.listaModelos = listaModelos;
}
}
#Entity
public class Modelo extends EntityJPA{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="NOMBRE_MODELO")
private String nombreModelo;
#ManyToOne
#JoinColumn(name="ID_COMPANIA", referencedColumnName="ID")
private Compania compania;
public Modelo() {
}
public Compania getCompania() {
return compania;
}
public void setCompania(Compania compania) {
this.compania = compania;
}
public int getId() {
return id;
}
public void setId(int idModelo) {
this.id = idModelo;
}
public String getNombre() {
return nombreModelo;
}
public void setNombre(String nombreModelo) {
this.nombreModelo = nombreModelo;
}
}
At the moment I make the
Compania cia = getEntityManager().find(Compania.class, idCompania);
the cia object does not have the value of the #Id attribute, it has the value of nombre but not of id. I mean:
cia.getId() = 0
and it must be 1 or 2 , etc. Not 0.
Thank you very much for your help.
I do not have the code to persist because It was already persisted.
the code for the find is
public static Compania findCompania(int idCompania){
try {
Compania cia = getEntityManager().find(Compania.class, idCompania);
return cia;
} finally {
closeEntityManager();
}
}
And if I activate the log, this is the select it shows:
482 testMySql TRACE [http-bio-8080-exec-5] openjpa.jdbc.SQL - <t 1228180882, conn 1699837157> executing prepstmnt 2127861376 SELECT t0.nombre FROM Compania t0 WHERE t0.id = ? [params=(int) 1]
497 testMySql TRACE [http-bio-8080-exec-5] openjpa.jdbc.SQL - <t 1228180882, conn 1699837157> [15 ms] spent
As you can see, there is no t0.id in the select.
Thanks for your help.
Primary Key (ID) not retrieved (?) from database using OpenJPA
Duplicate.... the net of the post is that you need to use a different enhancement method.
If you don't specifically set the value for the #Id attribute you have to declare it with #GeneratedValueso that it's automatically incremented.
Hi I am trying to do one to many insert but I am having problems.
I have two tables:
CREATE TABLE users_app (
user_id int UNSIGNED NOT NULL AUTO_INCREMENT,
user_number varchar(45) NOT NULL default '0',
user_password varchar(45) NOT NULL default '0',
os int(1) unsigned NOT NULL,
token varchar(500) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
CREATE TABLE user_app_devices(
id int AUTO_INCREMENT PRIMARY KEY,
user_id int UNSIGNED NOT NULL,
device_name varchar(45) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users_app (user_id)
)ENGINE=InnoDB CHARSET=utf8;
My classes:
#Entity
#Table(name="user_app_devices")
public class UserAppDevice implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
#Column(name="device_name")
private String deviceName;
//bi-directional many-to-one association to UsersApp
#ManyToOne
#JoinColumn(name="user_id")
private UsersApp usersApp;
public UserAppDevice() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getDeviceName() {
return this.deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public UsersApp getUsersApp() {
return this.usersApp;
}
public void setUsersApp(UsersApp usersApp) {
this.usersApp = usersApp;
}
}
#Entity
#Table(name="users_app")
public class UsersApp implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="user_id")
private int userId;
private int os;
private String token;
#Column(name="user_number")
private String userNumber;
#Column(name="user_password")
private String userPassword;
//bi-directional many-to-one association to UserAppDevice
#OneToMany(mappedBy="usersApp")
private List<UserAppDevice> userAppDevices;
public UsersApp() {
}
public int getUserId() {
return this.userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getOs() {
return this.os;
}
public void setOs(int os) {
this.os = os;
}
public String getToken() {
return this.token;
}
public void setToken(String token) {
this.token = token;
}
public String getUserNumber() {
return this.userNumber;
}
public void setUserNumber(String userNumber) {
this.userNumber = userNumber;
}
public String getUserPassword() {
return this.userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public List<UserAppDevice> getUserAppDevices() {
return this.userAppDevices;
}
public void setUserAppDevices(List<UserAppDevice> userAppDevices) {
this.userAppDevices = userAppDevices;
}
public UsersApp(int os, String token, String userNumber, String userPassword) {
this.os = os;
this.token = token;
this.userNumber = userNumber;
this.userPassword = userPassword;
}
I want to add new user with device
I try this code:
Session session = (Session) em.getDelegate();
session.beginTransaction();
UsersApp user = new UsersApp(os, token, userNumber, userPassword);
session.save(user);
UserAppDevice ud = new UserAppDevice();
ud.setUsersApp(user);
ud.setDeviceName(device);
session.save(ud);
session.getTransaction().commit();
but I am facing exception:
13:16:48,516 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http--0.0.0.0-8080-3) SQL Error: 1452, SQLState: 23000
13:16:48,517 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http--0.0.0.0-8080-3) Cannot add or update a child row: a foreign key constraint fails (`application`.`user_a
pp_devices`, CONSTRAINT `user_app_devices_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users_app` (`user_id`))
13:16:48,520 ERROR [org.jboss.as.ejb3.tx.CMTTxInterceptor] (http--0.0.0.0-8080-3) javax.ejb.EJBTransactionRolledbackException: Cannot add or update a child row: a foreign key const
raint fails (`application`.`user_app_devices`, CONSTRAINT `user_app_devices_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users_app` (`user_id`))
13:16:48,524 ERROR [org.jboss.ejb3.invocation] (http--0.0.0.0-8080-3) JBAS014134: EJB Invocation failed on component DeviceRegisterDAOImpl for method public abstract void com.break
id.ejb.model.DeviceRegisterDAO.add(int,java.lang.String,java.lang.String,java.lang.String,java.lang.String): javax.ejb.EJBTransactionRolledbackException: Cannot add or update a chi
ld row: a foreign key constraint fails (`application`.`user_app_devices`, CONSTRAINT `user_app_devices_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users_app` (`user_id`))
at org.jboss.as.ejb3.tx.CMTTxInterceptor.handleInCallerTx(CMTTxInterceptor.java:139) [jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:204) [jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:306) [jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:190) [jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
at org.jboss.as.ejb3.remote.EJBRemoteTransactionPropagatingInterceptor.processInvocation(EJBRemoteTransactionPropagatingInterceptor.java:80) [jboss-as-ejb3-7.1.1.Final.jar:
7.1.1.Final]
What am I missing ?
You haven't told Hibernate that the ID of UserApp was generated automatically by the database:
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name="user_id")
private int userId;
(and do the same for the other entity)
Since your are using bidirectional, change your client code as below.
Session session = (Session) em.getDelegate();
session.beginTransaction();
UserAppDevice ud = new UserAppDevice();
ud.setDeviceName(device);
UsersApp user = new UsersApp(os, token, userNumber, userPassword);
user.setUserAppDevices(new ArrayList<UserAppDevice>())
user.getUserAppDevices().add(ud);
session.save(user);
session.getTransaction().commit();
As mentioned by JB Nizet, you're missing the autogenerated strategy.
An alternative would be to use UUID as your id column and create the values yourself with
#Id
private UUID id = UUID.randomUUID();
Also, don't forget to set equals/hashCode to use the id field as discussed to death in The JPA hashCode() / equals() dilemma
Incidentally, why are you using Session (hibernate specific) instead of sticking to JPA's API?