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.
Related
I have a table GROCERY which has following structure:
CREATE TABLE grocery
(
gro_id NUMBER,
gro_name VARCHAR(32),
gro_dep_name VARCHAR(32),
gro_price NUMBER(16, 2),
gro_max_discount NUMBER(16, 2),
CONSTRAINT gro_pk PRIMARY KEY (gro_id, gro_dep_name)
)
My problem is that, when I am trying to fetch the data from the table (saved in my oracle data base) , I am getting the following error :
org.hibernate.id.IdentifierGenerationException: null id generated
for:class com.domain.Grocery
I have generated following entity classes according to the structure of the table :
Grocery.java
package com.domain;
import java.math.BigDecimal;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;
/**
* Grocery generated by hbm2java
*/
#SuppressWarnings("serial")
#Entity
#Table(name = "GROCERY", schema = "TPRDBA")
public class Grocery implements java.io.Serializable {
#EmbeddedId
private GroceryId id;
private String groName;
private BigDecimal groPrice;
private BigDecimal groMaxDiscount;
public Grocery() {
}
public Grocery(GroceryId id) {
this.id = id;
}
public Grocery(GroceryId id, String groName, BigDecimal groPrice, BigDecimal groMaxDiscount) {
this.id = id;
this.groName = groName;
this.groPrice = groPrice;
this.groMaxDiscount = groMaxDiscount;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "groId", column = #Column(name = "GRO_ID", nullable = false, precision = 22, scale = 0)),
#AttributeOverride(name = "groDepName", column = #Column(name = "GRO_DEP_NAME", nullable = false, length = 32)) })
public GroceryId getId() {
return this.id;
}
public void setId(GroceryId id) {
this.id = id;
}
#Column(name = "GRO_NAME", length = 32)
public String getGroName() {
return this.groName;
}
public void setGroName(String groName) {
this.groName = groName;
}
#Column(name = "GRO_PRICE", precision = 16)
public BigDecimal getGroPrice() {
return this.groPrice;
}
public void setGroPrice(BigDecimal groPrice) {
this.groPrice = groPrice;
}
#Column(name = "GRO_MAX_DISCOUNT", precision = 16)
public BigDecimal getGroMaxDiscount() {
return this.groMaxDiscount;
}
public void setGroMaxDiscount(BigDecimal groMaxDiscount) {
this.groMaxDiscount = groMaxDiscount;
}
}
GroceryId.java
package com.domain;
// Generated Nov 12, 2018 11:42:16 AM by Hibernate Tools 4.3.1.Final
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
* GroceryId generated by hbm2java
*/
#SuppressWarnings("serial")
#Embeddable
public class GroceryId implements java.io.Serializable {
private BigDecimal groId;
private String groDepName;
public GroceryId() {
}
public GroceryId(BigDecimal groId, String groDepName) {
this.groId = groId;
this.groDepName = groDepName;
}
#Column(name = "GRO_ID", nullable = false, precision = 22, scale = 0)
public BigDecimal getGroId() {
return this.groId;
}
public void setGroId(BigDecimal groId) {
this.groId = groId;
}
#Column(name = "GRO_DEP_NAME", nullable = false, length = 32)
public String getGroDepName() {
return this.groDepName;
}
public void setGroDepName(String groDepName) {
this.groDepName = groDepName;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof GroceryId))
return false;
GroceryId castOther = (GroceryId) other;
return ((this.getGroId() == castOther.getGroId()) || (this.getGroId() != null && castOther.getGroId() != null
&& this.getGroId().equals(castOther.getGroId())))
&& ((this.getGroDepName() == castOther.getGroDepName())
|| (this.getGroDepName() != null && castOther.getGroDepName() != null
&& this.getGroDepName().equals(castOther.getGroDepName())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getGroId() == null ? 0 : this.getGroId().hashCode());
result = 37 * result + (getGroDepName() == null ? 0 : this.getGroDepName().hashCode());
return result;
}
}
I have followed this example.
Please help me out, I am not able to figure out what is wrong in it.
Following is my service to take the data from database, which has GroceryRepository which extends CrudRepository :
#Service
public class GroceryService {
#Autowired
GroceryRepository groceryRepository;
public List<Grocery> getAllGrocery()
{
List<Grocery> groceries = new ArrayList<>();
groceryRepository.findAll().forEach(groceries::add);
return groceries;
}
public void addGrocery(Grocery grocery)
{
groceryRepository.save(grocery);
}
}
Missed #EmbeddedId annotation in Grocery.java. Update your code as below.
#EmbeddedId
private GroceryId id;
Just use #EmbeddedId.There must be only one EmbeddedId annotation and no Id annotation when the EmbeddedId annotation is used.
#EmbeddedId
private GroceryId id;
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
I have a table with a simple int id column with Identity auto increment in SQL Server.
USE [Hot]
GO
/****** Object: Table [dbo].[InstagramRequest] Script Date: 24.10.2015 18:49:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[InstagramRequest](
[ID] [int] IDENTITY(1,1) NOT NULL,
[instUserId] [int] NULL,
[request] [nvarchar](max) NULL,
[intime] [datetime] NULL,
CONSTRAINT [PK_InstagramRequest] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 10) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[InstagramRequest] ADD CONSTRAINT [DF_InstagramRequest_intime] DEFAULT (getdate()) FOR [intime]
GO
Entity class is ;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author z
*/
#Entity
#Table(name = "InstagramRequest")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "InstagramRequest.findAll", query = "SELECT i FROM InstagramRequest i"),
#NamedQuery(name = "InstagramRequest.findById", query = "SELECT i FROM InstagramRequest i WHERE i.id = :id"),
#NamedQuery(name = "InstagramRequest.findByInstUserID", query = "SELECT i FROM InstagramRequest i WHERE i.instUserID = :instUserID"),
#NamedQuery(name = "InstagramRequest.findByIntime", query = "SELECT i FROM InstagramRequest i WHERE i.intime = :intime")})
public class InstagramRequest implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "ID")
private Integer id;
#Column(name = "instUserID")
private Integer instUserID;
#Lob
#Column(name = "request")
private String request;
#Column(name = "intime")
#Temporal(TemporalType.TIMESTAMP)
private Date intime;
public InstagramRequest() {
}
public InstagramRequest(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getInstUserID() {
return instUserID;
}
public void setInstUserID(Integer instUserID) {
this.instUserID = instUserID;
}
public String getRequest() {
return request;
}
public void setRequest(String request) {
this.request = request;
}
public Date getIntime() {
return intime;
}
public void setIntime(Date intime) {
this.intime = intime;
}
#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 InstagramRequest)) {
return false;
}
InstagramRequest other = (InstagramRequest) 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.instagramparse.entity.InstagramRequest[ id=" + id + " ]";
}
}
The error message is as below .;
Internal Exception: java.sql.SQLException: Cannot insert the value NULL into column 'ID', table 'master.dbo.InstagramRequest'; column does not allow nulls. INSERT fails.
Error Code: 515
Call: INSERT INTO InstagramRequest (instUserID, intime, request) VALUES (?, ?, ?)
bind => [3 parameters bound]
Query: InsertObjectQuery(com.instagramparse.entity.InstagramRequest[ id=null ])
Which GenerationType should I use in this case ?
Your GenerationType is correct. You need to remove #Basic(optional = false) - it does not make sense to enforce that this field is set by JPA if it is to be autogenerated by the DB.
In fact, what seems to happen is that your JPA provider tries to insert NULL value instead of not setting anything for the id column. As the column is autogenerated, no value can be inserted into that column in an INSERT. Making the field optional will work as expected - JPA will not try to insert any value for I'd into the db, but will read the generated value after insert, making the value to always be non-null after persist.
i have 4 tables in which purchaseOrder has relation ship with sullpier ,item,and ordertype.
reference key of all table to purchaseOrder is supplierIdfk,itemIdfk,orderTypeIdfk.
so my question how can i get record of purchaseOrder record who has suplliername="XXX" , suplliername is one of the column of supplier table.
i am using hibernate annotation and for backhand i am using mysql.
i have mapped all the entity with annotation.
Thanks For your Time.
My table looks like this
CREATE TABLE `purchaseorder` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`discount` double NOT NULL,
`finalAmount` double NOT NULL,
`remark` varchar(255) DEFAULT NULL,
`shipDate` datetime DEFAULT NULL,
`unitPrice` double NOT NULL,
`itemIdfk` int(11) DEFAULT NULL,
`orderIdfk` int(11) DEFAULT NULL,
`supplierIdfk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `indexPurchaseOrderShipDate` (`shipDate`),
KEY `FKDFD4BAAD36B52348` (`itemIdfk`),
KEY `FKDFD4BAADFD3C54D4` (`orderIdfk`),
KEY `FKDFD4BAAD79028B3A` (`supplierIdfk`),
CONSTRAINT `FKDFD4BAAD36B52348` FOREIGN KEY (`itemIdfk`) REFERENCES `item` (`id`),
CONSTRAINT `FKDFD4BAAD79028B3A` FOREIGN KEY (`supplierIdfk`) REFERENCES `supplier` (`id`),
CONSTRAINT `FKDFD4BAADFD3C54D4` FOREIGN KEY (`orderIdfk`) REFERENCES `ordertype` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
my Entity code for purchaseOrder is like this.
package org.chillies.database;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.Index;
#Entity
public class PurchaseOrder {
private int id;
private Date shipDate;
private double unitPrice;
private double discount;
private double finalAmount;
private String remark;
private OrderType orderType;
private Supplier supplier;
private Item item;
private static final String KeyOrderId = "orderIdfk";
private static final String KeySupplierId = "supplierIdfk";
private static final String KeyItemId = "itemIdfk";
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Index(name = "indexPurchaseOrderShipDate")
public Date getShipDate() {
return shipDate;
}
public void setShipDate(Date shipDate) {
this.shipDate = shipDate;
}
public double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public double getDiscount() {
return discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public double getFinalAmount() {
return finalAmount;
}
public void setFinalAmount(double finalAmount) {
this.finalAmount = finalAmount;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
#ManyToOne
#JoinColumn(name = KeyOrderId)
public OrderType getOrderType() {
return orderType;
}
public void setOrderType(OrderType orderType) {
this.orderType = orderType;
}
#ManyToOne
#JoinColumn(name = KeySupplierId)
public Supplier getSupplier() {
return supplier;
}
public void setSupplier(Supplier supplier) {
this.supplier = supplier;
}
#ManyToOne
#JoinColumn(name = KeyItemId)
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}
actually i am using query code like this but it gives me error ...
public PurchaseOrder getPurchaseOrder(String supplierName) {
Session session = null;
PurchaseOrder purchaseOrder = new PurchaseOrder();
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query query=session.createQuery("FROM PurchaseOrder WHERE PurchaseOrder.supplierIdfk=Supplier.id AND Supplier.name=?");
purchaseOrder = (PurchaseOrder)query.uniqueResult();
query.setString("Supplier.name",supplierName);
session.getTransaction().commit();
} catch (HibernateException e) {
if (session != null) {
session.getTransaction().rollback();
e.printStackTrace();
}
} finally {
if (session != null) {
session.close();
}
}
return purchaseOrder;
}
and my error code is like this
org.hibernate.QueryException: Unable to resolve path [PurchaseOrder.supplierIdfk], unexpected token [PurchaseOrder] [FROM org.chillies.database.PurchaseOrder WHERE PurchaseOrder.supplierIdfk=Supplier.id AND Supplier.name=?]
at org.hibernate.hql.ast.tree.IdentNode.resolveAsNakedComponentPropertyRefLHS(IdentNode.java:219)
at org.hibernate.hql.ast.tree.IdentNode.resolve(IdentNode.java:108)
at org.hibernate.hql.ast.tree.DotNode.resolveFirstChild(DotNode.java:175)
at org.hibernate.hql.ast.HqlSqlWalker.lookupProperty(HqlSqlWalker.java:550)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.addrExpr(HqlSqlBaseWalker.java:4543)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1289)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4243)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:3722)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:1864)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:1789)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:818)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:604)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:288)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:231)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:254)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:94)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1651)
at org.chillies.dataaccesslayer.DataAccessLayer.getPurchaseOrder(DataAccessLayer.java:748)
at TestDataAccess.purchaseOrderDalTest(TestDataAccess.java:368)
at TestDataAccess.main(TestDataAccess.java:404)
Exception in thread "main" java.lang.NullPointerException
at TestDataAccess.purchaseOrderDalTest(TestDataAccess.java:370)
at TestDataAccess.main(TestDataAccess.java:404)
Assuming you have done all the mappings correctly, the query would be like this,
List<PurchaseOrder> purchaseOrders;
Session session = HibernateUtil.getSession();
Query query = session.createQuery("from PurchaseOrder po where po.supplierName = ?1");
query.setString(1, pass_your_supplier_name);
purchaseOrders = query.list();
Try
Query query=session.createQuery("select new fu.bar.PurchaseOrderDto(po.id, po.x, po.y, po.z) FROM PurchaseOrder po, Supplier sup WHERE po.supplier.id=sup.id AND sup.name=?");
or
Query query=session.createQuery("FROM PurchaseOrder po WHERE po.supplier.id=sup.id AND sup.name=?");
As I said in my comment:
If u are using HQL, you have to use the java-objects variables, not the database-fields.
I don't know if the second one is working, because the Supplier is not mentioned after "from". If it doesn't work, create 2 constructors in your entity: empty and one with the fields you need OR create a DTO with the fields you need. Then use the first query.
EDIT:
Second problem will be the "query.setString". It does not do what you want. Use setParameter instead:
[...]
Query query=session.createQuery("select new fu.bar.PurchaseOrderDto(po.id, po.x, po.y, po.z) FROM PurchaseOrder po, Supplier sup WHERE po.supplier.id=sup.id AND sup.name= :supName ");
query.setParameter("supName",supplierName);
purchaseOrder = (PurchaseOrder)query.uniqueResult();
session.getTransaction().commit();
[...]
Thanks for all the reply and your precious time.
I have found my answer.
i have build my query like this.
createQuery("FROM PurchaseOrder po LEFT JOIN FETCH po.supplier sup WHERE sup.name=:supName").setString("supName",suplierName);
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.