Hibernate SQL Reference Exception - java

Today i was trying to add Customer to database using Hibernate Annotation but i dont know why i am facing a reference Problem with a table !
Please read the Exception below
ERROR: Referential integrity constraint violation:
"FKOFMCQE0O4K2TFOXB308SKTMQ3: PUBLIC.CUSTOMER FOREIGN
KEY(CUS_BILLINGADDRESSID) REFERENCES
PUBLIC.CUSTOMERBILLINGADDRESS(CUS_BILLINGADDRESSID) ('CBA00001')"; SQL
statement:
update Customer set cus_emailid=?, cus_mobileno=?, cus_name=?, cus_billingaddressid=?, cus_cartid=?, cus_loginid=?,
cus_shippingaddressid=? where cus_id=? [23506-193]
Apr 01, 2017 7:09:57 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Apr 01, 2017 7:09:57 PM org.hibernate.internal.ExceptionMapperStandardImpl
mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not
execute statement]
Apr 01, 2017 7:09:57 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/TechNXT] threw exception [Request processing failed; nested
exception is javax.persistence.PersistenceException:
org.hibernate.exception.ConstraintViolationException: could not
execute statement] with root cause
org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FKOFMCQE0O4K2TFOXB308SKTMQ3: PUBLIC.CUSTOMER FOREIGN
KEY(CUS_BILLINGADDRESSID) REFERENCES
PUBLIC.CUSTOMERBILLINGADDRESS(CUS_BILLINGADDRESSID) ('CBA00001')"; SQL
statement:
update Customer set cus_emailid=?, cus_mobileno=?, cus_name=?, cus_billingaddressid=?, cus_cartid=?, cus_loginid=?,
cus_shippingaddressid=? where cus_id=? [23506-192]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.constraint.ConstraintReferential.checkRowOwnTable(ConstraintReferential.java:372)
at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:314)
at org.h2.table.Table.fireConstraints(Table.java:967)
at org.h2.table.Table.fireAfterRow(Table.java:985)
at org.h2.command.dml.Update.update(Update.java:151)
at org.h2.command.CommandContainer.update(CommandContainer.java:98)
at org.h2.command.Command.executeUpdate(Command.java:258)
at org.h2.server.TcpServerThread.process(TcpServerThread.java:344)
at org.h2.server.TcpServerThread.run(TcpServerThread.java:158)
at java.lang.Thread.run(Unknown Source)
Here is my Two model Tables
NOTE : i have generated getters and Setters but not posting so making as small as possible
1. Customer table which has a references of the other table
#Entity
public class Customer {
#Id
private String cus_id;
private String cus_name;
private String cus_emailid;
private String cus_mobileno;
#OneToOne(cascade=CascadeType.REFRESH)
#JoinColumn(name="cus_loginid")
private CustomerDetails customerdetails;
#OneToOne(cascade=CascadeType.REFRESH)
#JoinColumn(name="cus_billingaddressid")
private CustomerBillingAddress customerbillingaddress;
#OneToOne(cascade=CascadeType.REFRESH)
#JoinColumn(name="cus_shippingaddressid")
private CustomerShippingAddress customershippingaddress;
#OneToOne(cascade=CascadeType.REFRESH)
#JoinColumn(name="cus_cartid")
private CustomerCart customercart;
My Customer Billing Address Model
#Entity
public class CustomerBillingAddress {
#Id
private String cus_billingaddressid;
private String cus_houseno;
private String cus_street;
private String cus_area;
private String cus_city;
private String cus_state;
private String cus_country;
private String cus_pincode;
#OneToOne(mappedBy="customerbillingaddress")
private Customer customer;
Similarly Other Models
And Finally My DAO method which add the Customer to db
here is the code !
#Transactional
public String addCustomer(Customer customer) {
System.out.println("CustomerDao -TechNXT\n");
Session ses = sf.openSession();
customer.setCus_id(generateCustomerid());
customer.setCustomerbillingaddress(new CustomerBillingAddress());
customer.setCustomershippingaddress(new CustomerShippingAddress());
customer.setCustomercart(new CustomerCart());
customer.getCustomerdetails().setCus_loginid(generateCustomerLoginid());
customer.getCustomerbillingaddress().setCus_billingaddressid(generateCustomerBillingid());
customer.getCustomershippingaddress().setCus_shippingaddressid(generateCustomershippingid());
customer.getCustomercart().setCus_cartid(generateCustomerCartid());
customer.getCustomerdetails().setCus_isenabled(true);
customer.getCustomerdetails().setCus_role("ROLE_USER");
Transaction tr = ses.beginTransaction();
ses.save(customer);
tr.commit();
ses.close();
return customer.getCustomerdetails().getCus_loginid();
}
Well i have being trying stuffs since 3hrs but failed to get a solution of it !!
Sorry for taking your precious time.
and Thanking you in advance for helping me !

can you mark the #Table annontation on your class
like
#Table(name ="Customer")

Related

Duplicate entry '2' for key error in Spring jpa

I am working on a spring boot app where I am using JPA for all data transactions and I came across this error while using OneToMany relationship.
Here are both my models:
user.java
#Entity
public class user {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private String role;
#ManyToOne(cascade=CascadeType.ALL)
private file f;
#JsonIgnore
#OneToMany(targetEntity=job.class,cascade=CascadeType.ALL)
private List<job> applied;
//getters ,setters and constuctors.
}
job.java
#Entity
public class job {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String role;
private String company;
private String salary;
private String description;
private String level;
private Date expiry;
private String skills;
private String location;
#JsonIgnore
#OneToMany(targetEntity=user.class,cascade=CascadeType.ALL)
private List<user> candidates;
//getters setters and constructor
}
here's the method that triggers the error:
public String applyToJob(Integer userId,Integer jobId)
{
job jobToApply= jobRepo.getOne(jobId);
user applier=userRepo.getById(userId);
List<job> jobs=applier.getApplied();
jobs.add(jobToApply);
applier.setApplied(jobs);
userRepo.save(applier);
List<user> candidates=jobToApply.getCandidates();
System.out.println(candidates);
candidates.add(userRepo.getOne(userId));
System.out.println(candidates);
jobToApply.setCandidates(candidates);
jobRepo.save(jobToApply);
return "Job Apply Success";
}
Now that I want to add data inside job's candidates field I get the below error:
2021-10-07 17:17:37.542 WARN 21696 --- [nio-8090-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1062, SQLState: 23000
2021-10-07 17:17:37.543 ERROR 21696 --- [nio-8090-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : Duplicate entry '2' for key 'job_candidates.UK_q0o76ghxl59c5ip3qwatsxo3f'
2021-10-07 17:17:37.543 INFO 21696 --- [nio-8090-exec-4] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2021-10-07 17:17:37.564 ERROR 21696 --- [nio-8090-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [job_candidates.UK_q0o76ghxl59c5ip3qwatsxo3f]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '2' for key 'job_candidates.UK_q0o76ghxl59c5ip3qwatsxo3f'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117) ~[mysql-connector-java-8.0.26.jar:8.0.26]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java
Seems like you are adding a candidate to the job entity, which is already previously mapped to that particular job.
Please thoroughly check your entries in the DB and try to find out if there is any candidate that is being added multiple times to the same job, preferably with id as 2.
Let me know if you face any further difficulties!

Could not extract ResultSet. Problem with Oracle Database

I have a Spring Boot connected with Oracle Database application. The same version of the application works fine with MySQL, but when I try to do some requests to Oracle Database it throws error:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
"status":500,"error":"Internal Server
Error","trace":"org.springframework.dao.InvalidDataAccessResourceUsageException:
could not extract ResultSet; SQL [n/a]; nested exception is
org.hibernate.exception.SQLGrammarException: could not extract
ResultSet\r\n\tat
org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:281)\r\n\tat
org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)\r\n\tat
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)\r\n\tat
org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)\r\n\tat
org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)\r\n\tat
org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:154)
at com.example.pawel.expense.controller.ExpenseController.createExpense(ExpenseController.java:67) ~[classes/:na]
ECT...
So here is my controller method for this function:
#PostMapping("/expense")
ResponseEntity<Expense> createExpense(#Valid #RequestBody Expense expense) throws URISyntaxException {
Expense result = expenseRepository.save(expense);
return ResponseEntity.created(new URI("/api/expense/" + result.getId())).body(result);
}
And my Expense model
#NoArgsConstructor
#Data
#Table(name="expense")
#Entity
public class Expense {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
private Instant date;
private double amount;
private String description;
#ManyToOne
private Category category;
#ManyToOne
private User user;
// Getters and setters
Here is my application.properties
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle12cDialect
spring.jpa.properties.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.show-sql=true
spring.datasource.url=jdbc:oracle:thin:#localhost:1521:XE
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.username=system
spring.datasource.password=root
spring.datasource.initialization-mode=always
spring.datasource.validationQuery=SELECT 1
logging.level.org.hibernate.SQL=DEBUG
spring.server.compression.enabled=true
spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect
spring.jpa.properties.hibernate.format_sql=true
You should add Hibernate Dialect to your application.properties like so
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
Or create a Bean for Oracle datasource. Follow this guide for further information
Configuring Spring Boot for Oracle

Hibernate and MySQL: #CreationTimestamp annotated Date property throws ConstraintViolationException when saving new Entity

I'm making a Spring MVC app with Hibernate and MySQL. I have a TIMESTAMP column in one of my MySQL tables defined like this tstamp timestamp default current_timestamp.
The entity for this table has a composite primary key which includes the tstamp column.
The Entity class part where I define the EmbeddedId:
#Entity
#Table(name="trustassessments")
public class TrustAssessment {
#EmbeddedId
#JsonView(Views.Public.class)
private TrustAssessmentId id;
....
The Embeddable class where I define the timestamp:
#Embeddable
public class TrustAssessmentId implements Serializable {
#Column(name="deviceId")
int deviceId;
#Column(name="tmsId")
int tmsId;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name="tstamp")
private Date tstamp;
....
I'm using Jackson, so I POST in json format and I have tried these two:
1.
{
"id": {
"deviceId": 21,
"tmsId": "20"
},
"trustLevel": 0.4,
"honesty": 0.6,
"cooperativeness": 0.4,
"communityInterest": 0.2
}
2.
{
"id": {
"deviceId": 21,
"tmsId": "20",
"tstamp": ""
},
"trustLevel": 0.4,
"honesty": 0.6,
"cooperativeness": 0.4,
"communityInterest": 0.2
}
The stack trace:
Nov 28, 2019 9:07:28 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1048, SQLState: 23000
Nov 28, 2019 9:07:28 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Column 'tstamp' cannot be null
Nov 28, 2019 9:07:28 PM org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
Nov 28, 2019 9:07:28 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/tms-rest-again] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Column 'tstamp' cannot be null
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)
I removed the #CreationTimestamp and wrote it like this:
#Column(name="tstamp", updatable=false)
#Temporal(TemporalType.TIMESTAMP)
private Date tstamp = new Date();
Props to this answer.
However, it would be nice if someone could explain how this works and why it didn't work with #CreationTimestamp.

Hibernate Foreign Key Error

So in my Oracle database I have two tables which have a foreign key constraint properly defined.
Here are the DDL for the two tables.
CREATE TABLE "BI***********"."PROJECT"
(
"PROJECT_ID" NUMBER(10,0) NOT NULL,
"PROJECT_CODE" VARCHAR2(20) NOT NULL,
"PRODUCT_ID" NUMBER(10,0) NOT NULL,
"DESCRIPTION" VARCHAR2(45) NOT NULL,
CONSTRAINT PROJECT_PK PRIMARY KEY ("PROJECT_ID"),
CONSTRAINT "PROJECT_FK1" FOREIGN KEY ("PRODUCT_ID")
REFERENCES "BI***********"."PRODUCT" ("PRODUCT_ID")
);
CREATE TABLE "BI***********"."PRODUCT"
(
"PRODUCT_ID" NUMBER(10,0) NOT NULL,
"PRODUCT_NAME" VARCHAR2(20) NOT NULL,
"DESCRIPTION" VARCHAR2(45) NOT NULL,
CONSTRAINT PRODUCT_PK PRIMARY KEY ("PRODUCT_ID")
);
And here is the corresponding Java code with the Hibernate Annotations:
#Entity
#Table (name="project")
#SequenceGenerator(name="seq_project",sequenceName="BI***********.SEQ_PROJECT", allocationSize=1, initialValue=1)
public class Project {
//Fields
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_project")
#Column(name="PROJECT_ID")
private int id;
#Column(name="PROJECT_CODE")
private String projectCode;
#Column(name="PRODUCT_ID")
private int productId;
#Column(name="DESCRIPTION")
private String description;
#Entity
#Table (name="product")
#SequenceGenerator(name="seq_product",sequenceName="BI***********.SEQ_PRODUCT", allocationSize=1, initialValue=1)
public class Product {
//Fields
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_product")
#Column(name="PRODUCT_ID")
private int id;
#Column(name="PRODUCT_NAME")
private String productName;
#Column(name="DESCRIPTION")
private String description;
However, when I try to add to the tables with hibernate I'm receiving the following error code:
Hibernate: insert into project (DESCRIPTION, PRODUCT_ID, PROJECT_CODE, PROJECT_ID) values (?, ?, ?, ?)
Jun 08, 2016 9:06:49 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 2291, SQLState: 23000
Jun 08, 2016 9:06:49 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-02291: integrity constraint (BIMB2013WMMEE.PROJECT_FK1) violated - parent key not found
Jun 08, 2016 9:06:49 AM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Jun 08, 2016 9:06:49 AM org.hibernate.internal.SessionImpl$5 mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [could not execute statement]
Jun 08, 2016 9:06:49 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:oracle:thin:#endeavour.us.manh.com:1523/pso11r2f]
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2921)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3421)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:560)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:434)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1295)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:468)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3135)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2352)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:147)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)
at com.luv2code.demo.CreateClientDemo.main(CreateClientDemo.java:37)
Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-02291: integrity constraint (BIMB2013WMMEE.PROJECT_FK1) violated - parent key not found
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
Look at your error
Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-02291: integrity constraint (BIMB2013WMMEE.PROJECT_FK1) violated - parent key not found
Your foreign key in "project" references a primary key in "product" that doesn't exists. You have to make the link between your tables
You have to change your annotations for something like that
#Entity
#Table (name="project")
#SequenceGenerator(name="seq_project",sequenceName="BI***********.SEQ_PROJECT", allocationSize=1, initialValue=1)
public class Project {
//Fields
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_project")
#Column(name="PROJECT_ID")
private int id;
#Column(name="PROJECT_CODE")
private String projectCode;
#OneToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
#JoinColumn(name="PRODUCT_ID",insertable=true,
updatable=true,nullable=false,unique=true)
private Product product;
#Column(name="DESCRIPTION")
private String description;
#Entity
#Table (name="product")
#SequenceGenerator(name="seq_product",sequenceName="BI***********.SEQ_PRODUCT", allocationSize=1, initialValue=1)
public class Product {
//Fields
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_product")
#Column(name="PRODUCT_ID")
private int id;
#Column(name="PRODUCT_NAME")
private String productName;
#Column(name="DESCRIPTION")
private String description
#OneToOne (mappedBy="PRODUCT_ID",fetch=FetchType.EAGER)
private Project project;
or you can use #PrimaryKeyJoinColumn annotation with
#PrimaryKeyJoinColumn
private Project project;
You'll find more informations about relationships here
My guess is that you need to give the Product class to your Project class, instead of the productId Integer you are using right now.
CONSTRAINT "PROJECT_FK1" FOREIGN KEY ("PRODUCT_ID")
REFERENCES "BI***********"."PRODUCT" ("PRODUCT_ID")
The foreign key states that there is a reference between the two tables, while in your code you only pass an integer, and not the full Product class as an object
Thus i would think that you need to replace:
#Column(name="PRODUCT_ID")
private int productId;
in your Project class with the following:
#Column(name="PRODUCT_ID")
#OneToOne
private Product product;
You have an error in the cfg.xml file. Change hbm2dll to hbm2ddl in
"hibernate.hbm2dll.auto">create
Then life will be beautiful again. I know this because I made the same mistake and spent some hours to figure it out.

EclipseLink and Hibernate integration

we currently work with an Eclipse-Link project (A) and a filled database (with a sequence table).
for my next project (B) I want/need to use Hibernate to access and write data from/to this database. working with an entity that exists in project B is perfectly fine, I can save and read it.
project A entities are needed for B, so I included them in the build path. although when I try to save an entity from project A I get several errors.
basic class Test in project A
#Entity
#Table(name = "test")
public class Test implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
public Test() {
}
public Test(String name) {
this.name = name;
}
// getter & setter
....
}
class Test is added to my sessionFactory
Configuration configuration = new Configuration();
configuration.configure().addAnnotatedClass(Test.class);
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
exceptions when I try to save a Test-object in project B
Hibernate: insert into test (name) values (?)
Nov 21, 2013 1:27:41 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1364, SQLState: HY000
Nov 21, 2013 1:27:41 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Field 'ID' doesn't have a default value
org.hibernate.exception.GenericJDBCException: could not execute statement
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:136)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2989)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3501)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:393)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:227)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:207)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:191)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:321)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:286)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:206)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:191)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:764)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:756)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:752)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
at com.sun.proxy.$Proxy12.save(Unknown Source)
at de.main.Dao.save(Dao.java:31)
at de.main.Main.main(Main.java:47)
Caused by: java.sql.SQLException: Field 'ID' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2794)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133)
... 29 more
GenerationType.AUTO lets the provider pick what it wants to use, and this is different in EclipseLink from Hibernate. EclipseLink will use a sequence table (http://wiki.eclipse.org/EclipseLink/Examples/JPA/PrimaryKey), while I believe in Hibernate it depends on the database - but in your case it seems to assume Identity is being used to assign it or the key would exist in the insert statement. Since your tables are not set up for sequencing or identity, you will need to specify the table generation that EclipseLink uses by default, something like:
#Id
#GeneratedValue(generator="testSequence")
#TableGenerator(name="testSequence", table="SEQUENCE",
pkColumnName="SEQ_NAME", valueColumnName="SEQ_COUNT",
pkColumnValue="TEST_GEN")
private int id;
You will have to verify that SEQUENCE table and column names and values being used.
you've to tell you database at table creation to take in concideration the creation of the ID.
in the case of MySql :
CREATE TABLE `test`
(
`ID` int(11) NOT NULL **AUTO_INCREMENT**,
`EMAIL` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
)
the entity should looks like :
#Entity
#Table(name = "supplier")
public class supplier implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
**#GeneratedValue(strategy = GenerationType.IDENTITY)**
#Column(name = "ID")

Categories