hibernate error: java.sql.BatchUpdateException: ORA-00932: inconsistent datatypes: expected NUMBER got BINARY - oracle

I am trying to insert a row into a table called Mstrauthorizations. When doing so, I get an error saying Could not execute JDBC batch update. The row is not in the DB - so - I do not see how it could be updating anything at all. The database being used is Oracle. When doing the insert, the keyid is generated with the help of Oracle sequences. My understanding is that the auto-increment of key ids (primary key) is not possible until Oracle 12c. The Mstrauthorizations.java code was generated using Hibernate.
Update: made changes to the Mstrauthorizations.java file and am now getting the following error: java.sql.BatchUpdateException: ORA-00932: inconsistent datatypes: expected NUMBER got BINARY I have initialized the attribuetes/fields of the table in the Mstrauthorizations.java file (so no null values would be passed in) but this is not working.
How can I at least see the column that the hibernate command is complaining about? I am trying to do an insert. Why is an update being performed?
log information
1323 [main] DEBUG org.hibernate.transaction.JDBCTransaction - current autocommit status: false
1327 [main] DEBUG org.hibernate.event.def.AbstractSaveEventListener - generated identifier: 0, using strategy: org.hibernate.id.Assigned
1347 [main] DEBUG org.hibernate.transaction.JDBCTransaction - commit
1348 [main] DEBUG org.hibernate.event.def.AbstractFlushingEventListener - processing flush-time cascades
1349 [main] DEBUG org.hibernate.event.def.AbstractFlushingEventListener - dirty checking collections
1350 [main] DEBUG org.hibernate.event.def.AbstractFlushingEventListener - Flushed: 1 insertions, 0 updates, 0 deletions to 1 objects
1350 [main] DEBUG org.hibernate.event.def.AbstractFlushingEventListener - Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
1351 [main] DEBUG org.hibernate.pretty.Printer - listing entities:
1351 [main] DEBUG org.hibernate.pretty.Printer - com.apostx.tables.Mstrauthorizations{employeeid=0, lastlogints=0, reclockts=2007-09-23 10:10:10.0, authorizationsid=0, memo=no value, logonid=joney#mitchell.com, lastname=Mitchell, firstname=Joney, logonpassword=1234567, archived=0, reclockpid=3434, reclockhost=no host, reclocktype=6, active=0, tenantid=5, worktype=0, reclockid=999999}
1368 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
1373 [main] DEBUG org.hibernate.SQL - insert into ORAAPPS.MSTRAUTHORIZATIONS (ACTIVE, ARCHIVED, EMPLOYEEID, FIRSTNAME, LASTLOGINTS, LASTNAME, LOGONID, LOGONPASSWORD, MEMO, RECLOCKHOST, RECLOCKID, RECLOCKPID, RECLOCKTS, RECLOCKTYPE, TENANTID, WORKTYPE, AUTHORIZATIONSID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1482 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - Executing batch size: 1
1496 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
1498 [main] DEBUG org.hibernate.util.JDBCExceptionReporter - Could not execute JDBC batch update [insert into ORAAPPS.MSTRAUTHORIZATIONS (ACTIVE, ARCHIVED, EMPLOYEEID, FIRSTNAME, LASTLOGINTS, LASTNAME, LOGONID, LOGONPASSWORD, MEMO, RECLOCKHOST, RECLOCKID, RECLOCKPID, RECLOCKTS, RECLOCKTYPE, TENANTID, WORKTYPE, AUTHORIZATIONSID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]
java.sql.BatchUpdateException: ORA-00932: inconsistent datatypes: expected NUMBER got BINARY
at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:343)
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10656)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
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 com.apostx.hibernate.soverflow.test.TestStack.main(TestStack.java:32)
1498 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 932, SQLState: 42000
1498 [main] ERROR org.hibernate.util.JDBCExceptionReporter - ORA-00932: inconsistent datatypes: expected NUMBER got BINARY
1498 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 932, SQLState: 42000
1498 [main] ERROR org.hibernate.util.JDBCExceptionReporter - ORA-00932: inconsistent datatypes: expected NUMBER got BINARY
1499 [main] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
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 com.apostx.hibernate.soverflow.test.TestStack.main(TestStack.java:32)
Caused by: java.sql.BatchUpdateException: ORA-00932: inconsistent datatypes: expected NUMBER got BINARY
at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:343)
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10656)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 8 more
Exception in thread "main" org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
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 com.apostx.hibernate.soverflow.test.TestStack.main(TestStack.java:32)
Caused by: java.sql.BatchUpdateException: ORA-00932: inconsistent datatypes: expected NUMBER got BINARY
at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:343)
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10656)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 8 more
TIA
Main program - dbconnection test - working
package com.apostx.dbconnection.test;
import java.sql.*;
public class TestDBConnection {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#scar:1527:DSV", "ora787", "Huiu7ti" );
Statement statement = con.createStatement();
String sql = "select * from MstrAuthorizations";
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
System.out.println("first col " + rs.getInt(1) + " second col " + rs.getString(2));
System.out.println( "login id is " + rs.getString("logonid"));
}
con.close();
}
catch ( Exception e ) {
System.out.println("Database Connection Testing Error : " + e);
e.printStackTrace();
}
}
}
Main Program : Not working
package com.apostx.hibernate.test;
import java.math.BigDecimal;
import org.apache.log4j.BasicConfigurator;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.apostx.tables.Mstrauthorizations;
public class AddRecord {
public static void main(String[] args) {
BasicConfigurator.configure();
// create session factory
SessionFactory factory = new Configuration().
configure("hibernate.cfg.xml").
addAnnotatedClass(Mstrauthorizations.class).
buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// create object
System.out.println("about to start the work ....");
Mstrauthorizations mstr = new Mstrauthorizations();
BigDecimal tenantid=new BigDecimal(5);
mstr.setFirstname("Joney"); mstr.setLastname("Mitchell");
mstr.setTenantid(tenantid);mstr.setLogonid("joney#mitchell.com");
mstr.setLogonpassword("1234567");mstr.setReclockid(new BigDecimal(999999));
mstr.setReclockhost("no host");mstr.setReclockpid(new BigDecimal(3434));
mstr.setReclocktype(new BigDecimal(6));
// start transaction
session.beginTransaction();
// save info
System.out.println("about to save the data ...");
session.save(mstr);
// commit transaction
session.getTransaction().commit();
System.out.println("All Saved ...");
}
catch ( Exception e ) {
System.out.println("error message is " + e.getLocalizedMessage());
}
finally {
factory.close();
}
}
}
Mstrauthorizations.java
package com.apostx.tables;
// Generated Jun 22, 2017 9:30:03 PM by Hibernate Tools 4.0.0
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
/**
* Mstrauthorizations generated by hbm2java
*/
#Entity
#Table(name = "MSTRAUTHORIZATIONS", schema = "ORAAPPS", uniqueConstraints = {
#UniqueConstraint(columnNames = { "TENANTID", "LOGONID" }),
#UniqueConstraint(columnNames = { "TENANTID", "EMPLOYEEID" }) })
public class Mstrauthorizations {
private BigDecimal authorizationsid = new BigDecimal(0);
private BigDecimal tenantid = new BigDecimal(0);
private BigDecimal employeeid = new BigDecimal(0);
private String logonid = new String("no value");
private String logonpassword = new String("no value");
private BigDecimal worktype = new BigDecimal(0);
private BigDecimal lastlogints = new BigDecimal(0);
private String memo = new String("no value");
private String firstname = new String("no value");
private String lastname = new String("no value");
private BigDecimal active = new BigDecimal(0);
private BigDecimal archived = new BigDecimal(0);
private BigDecimal reclocktype = new BigDecimal(0);
private BigDecimal reclockid = new BigDecimal(0);
private String reclockhost = new String("no value");
private BigDecimal reclockpid = new BigDecimal(0);
private Timestamp reclockts = java.sql.Timestamp.valueOf("2007-09-23 10:10:10.0");
public Mstrauthorizations() {
}
public Mstrauthorizations(BigDecimal authorizationsid) {
this.authorizationsid = authorizationsid;
}
public Mstrauthorizations(BigDecimal authorizationsid, BigDecimal tenantid,
BigDecimal employeeid, String logonid, String logonpassword,
BigDecimal worktype, BigDecimal lastlogints, String memo,
String firstname, String lastname, BigDecimal active,
BigDecimal archived, BigDecimal reclocktype, BigDecimal reclockid,
String reclockhost, BigDecimal reclockpid, Timestamp reclockts) {
this.authorizationsid = authorizationsid;
this.tenantid = tenantid;
this.employeeid = employeeid;
this.logonid = logonid;
this.logonpassword = logonpassword;
this.worktype = worktype;
this.lastlogints = lastlogints;
this.memo = memo;
this.firstname = firstname;
this.lastname = lastname;
this.active = active;
this.archived = archived;
this.reclocktype = reclocktype;
this.reclockid = reclockid;
this.reclockhost = reclockhost;
this.reclockpid = reclockpid;
this.reclockts = reclockts;
}
#Id
#Column(name = "AUTHORIZATIONSID", unique = true, nullable = false, precision = 22, scale = 0)
public BigDecimal getAuthorizationsid() {
return this.authorizationsid;
}
public void setAuthorizationsid(BigDecimal authorizationsid) {
this.authorizationsid = authorizationsid;
}
#Column(name = "TENANTID", precision = 22, scale = 0)
public BigDecimal getTenantid() {
return this.tenantid;
}
public void setTenantid(BigDecimal tenantid) {
this.tenantid = tenantid;
}
#Column(name = "EMPLOYEEID", precision = 22, scale = 0)
public BigDecimal getEmployeeid() {
return this.employeeid;
}
public void setEmployeeid(BigDecimal employeeid) {
this.employeeid = employeeid;
}
#Column(name = "LOGONID", length = 60)
public String getLogonid() {
return this.logonid;
}
public void setLogonid(String logonid) {
this.logonid = logonid;
}
#Column(name = "LOGONPASSWORD", length = 40)
public String getLogonpassword() {
return this.logonpassword;
}
public void setLogonpassword(String logonpassword) {
this.logonpassword = logonpassword;
}
#Column(name = "WORKTYPE", precision = 22, scale = 0)
public BigDecimal getWorktype() {
return this.worktype;
}
public void setWorktype(BigDecimal worktype) {
this.worktype = worktype;
}
#Column(name = "LASTLOGINTS", precision = 22, scale = 0)
public BigDecimal getLastlogints() {
return this.lastlogints;
}
public void setLastlogints(BigDecimal lastlogints) {
this.lastlogints = lastlogints;
}
#Column(name = "MEMO", length = 100)
public String getMemo() {
return this.memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
#Column(name = "FIRSTNAME", length = 30)
public String getFirstname() {
return this.firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
#Column(name = "LASTNAME", length = 30)
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Column(name = "ACTIVE", precision = 22, scale = 0)
public BigDecimal getActive() {
return this.active;
}
public void setActive(BigDecimal active) {
this.active = active;
}
#Column(name = "ARCHIVED", precision = 22, scale = 0)
public BigDecimal getArchived() {
return this.archived;
}
public void setArchived(BigDecimal archived) {
this.archived = archived;
}
#Column(name = "RECLOCKTYPE", precision = 22, scale = 0)
public BigDecimal getReclocktype() {
return this.reclocktype;
}
public void setReclocktype(BigDecimal reclocktype) {
this.reclocktype = reclocktype;
}
#Column(name = "RECLOCKID", precision = 22, scale = 0)
public BigDecimal getReclockid() {
return this.reclockid;
}
public void setReclockid(BigDecimal reclockid) {
this.reclockid = reclockid;
}
#Column(name = "RECLOCKHOST", length = 80)
public String getReclockhost() {
return this.reclockhost;
}
public void setReclockhost(String reclockhost) {
this.reclockhost = reclockhost;
}
#Column(name = "RECLOCKPID", precision = 22, scale = 0)
public BigDecimal getReclockpid() {
return this.reclockpid;
}
public void setReclockpid(BigDecimal reclockpid) {
this.reclockpid = reclockpid;
}
#Column(name = "RECLOCKTS")
public Serializable getReclockts() {
return this.reclockts;
}
public void setReclockts(Timestamp reclockts) {
this.reclockts = reclockts;
}
}

Fixed when following this:
Hibernate: Where do insertable = false, updatable = false belong in composite primary key constellations involving foreign keys?
When data saved to table, ID generated on DB side. Just set "insertable" and "updatable" to false for ID and Timestamp.

Related

HQL with parameters giving error IllegalArgumentException

I am getting an exception while trying to fetch some data using HQL with parameters. Below is the exception and the code.
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: TESTDB.ORDER_DETAILS is not mapped [SELECT DATE,ORDER_NAME,DESCRIPTION FROM TESTDB.ORDER_DETAILS WHERE ORDER_ID = :orderId ORDER BY DATE DESC]
//*************************************************************
OrderDetailDTO orderDetailDTO = new OrderDetailDTO();
List<OrderDetailDTO> orderList = new ArrayList<OrderDetailDTO>();
ResultSet rs = null;
String queryStr = "SELECT DATE,ORDER_NAME,DESCRIPTION "
+ "FROM TESTDB.ORDER_DETAILS WHERE ORDER_ID = :orderId "
+ "ORDER BY DATE DESC";
org.hibernate.query.Query query = session.createQuery(queryStr).setParameter("orderId", ordId);
rs = (ResultSet)query.getResultList();
while(rs.next()!=false){
orderDetailDTO.setOrderName(rs.getString("ORDER_NAME"));
orderDetailDTO.setDescription(rs.getString("DESCRIPTION"));
orderDetailDTO.setDate(rs.getTimestamp("DATE"));
orderList.add(orderDetailDTO);
}
//*************************************************************
//ordId : This one I have as argument in the method
I have to use this parameterised HQL to avoid SQL injection. Can anyone figure out why the weird error of IllegalArgumentException is comming.
The solution is done by using the entity names instead of the database table names. There is the catch. In JPQL we need to use the java bean class name in the query. When I replaced the java bean class name with the java bean fields name everything worked fine.
Also in JPQL mentioning the schema name is not required as in case of JPQL hibernate will use the schema
as defined by the hibernate.default_schema configuration property. The URL used for reference is https://vladmihalcea.com/how-to-resolve-the-hibernate-global-database-schema-and-catalog-for-native-sql-queries/
Below is the working code :
The java code for the database table :
package demo.jpql;
import java.io.Serializable;
import javax.persistence.*;
import java.sql.Timestamp;
#Entity
#Table( name = "ORDER_DETAILS" )
public class OrderDetails implements Serializable {
private static final long serialVersionUID = 1L;
#Column( name = "ORDER_NAME", length = 50 )
private String orderName;
#Column( name = "DESCRIPTION", length = 50 )
private String desc;
#Column( name = "DATE" )
private Timestamp date;
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Timestamp getDate() {
return date;
}
public void setDate(Timestamp date) {
this.date = date;
}
}
//*************************************************************
OrderDetailDTO orderDetailDTO = new OrderDetailDTO();
List<OrderDetailDTO> orderList = new ArrayList<OrderDetailDTO>();
ResultSet rs = null;
String queryStr = "SELECT date,orderName,desc"
+ "FROM OrderDetails WHERE orderID =:orderId "
+ "ORDER BY date DESC";
org.hibernate.query.Query query =
session.createQuery(queryStr).setParameter("orderId", ordId);
List<Object> rsltLstOrderDtls = (List<Object>)query.getResultList();
Iterator<Object> itr = rsltLstOrderDtls.iterator();
while (itr.hasNext()) {
Object[] obj = (Object[]) itr.next();
orderDetailDTO.setOrderName(String.valueOf(obj[1]));
orderDetailDTO.setDescription(String.valueOf(obj[2]));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
java.util.Date parsedDate = dateFormat.parse(String.valueOf(obj[0]));
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
orderDetailDTO.setDate(timestamp);
orderList.add(orderDetailDTO);
}
//*************************************************************

Hibernate not retrieving correct value with SELECT and ORA-00984: column not allowed here error

I am facing two issues here :
Issue 1) I am trying to get the COMPANY_ID using the selectCompanyID variable as shown below. I am storing the value returned into getCompanyID variable.When I tried to print it, as shown in the console output below, it's always printing number 1. However, when I tried to run the actual SQL in the
Oracle SQL developer SQL Worksheeet, I got different number. Because of this I could insert wrong ID in the following INSERT statement where it's
getting used.
Issue 2) As shown in the SQL, I am also getting ORA-00984: column not allowed here error. Noticed, people encountering similar error in the following post :
"column not allowed here" error in INSERT statement
But here I don't have straightforward SQL INSERT statement as the one mentioned in the above post with missing quotes.
public boolean insertEmployeeDetails(Employee employee)
{
logger.debug("Starting EmployeeDaoImpl.insert() .....");
Session session = null;
Transaction tx = null;
boolean status = true;
try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
//The following SELECT query returns a number when I ran it in the Oracle SQL developer SQL worksheet
String selectCompanyID = "SELECT"
+ " VALUE_EMP_ID"
+" FROM "
+ " COMPANY_DATA"
+" WHERE"
+ " testing_id = 1234"
+" AND "
+ " company_employee_id = 3345";
int getCompanyID = session.createSQLQuery(selectCompanyID)
.executeUpdate();
System.out.println("GetCompanyID Test below");
System.out.println(getCompanyID);
String hqlInsert = "INSERT INTO Employee (NAME, IS_CORRECT,IS_WRONG,COMPANY_ID, TRANSACTION_ID,DEFINITION) VALUES"
+ "( SELECT value_emp_id FROM COMPANY_DATA WHERE testing_id = 1234 AND"
+ " company_employee_id = 3345))";
String hqlInsert = "INSERT INTO Employee (NAME,IS_CORRECT,IS_WRONG,COMPANY_ID,TRANSACTION_ID,DEFINITION) VALUES "
+ "("
+employee.getName()+","
+employee.getIsCorrect()+","
+employee.getIsWrong()+","
+getCompanyID+","
+employee.getTransactionId()+","
+employee.getDefinition()+")";
System.out.println("October 3 Checking for hqlInsert");
System.out.println(hqlInsert);
int createdEntities = session.createSQLQuery( hqlInsert )
.executeUpdate();
session.persist(employee);
tx.commit();
System.out.println("October 3 BELOW Checking for hqlInsert");
System.out.println(hqlInsert);
System.out.println("Checking for CreatedEntities");
System.out.println(createdEntities);
} catch(Exception ex) {
tx.rollback();
ex.printStackTrace();
status = false;
} finally {
session.close();
}
logger.debug("Completed EmployeeDaoImpl.insert() .....");
return status;
}
Console :
Hibernate:
SELECT
VALUE_EMP_ID
FROM
COMPANY_DATA
WHERE
testing_id = 1234
AND company_employee_id = 3345
GetCompanyID Test below
1
October 3 Checking for hqlInsert
INSERT INTO Employee (NAME,IS_CORRECT,IS_WRONG,COMPANY_ID,TRANSACTION_ID,DEFINITION) VALUES (Terminology,0,0,1,0,definitionTest)
Hibernate:
INSERT
INTO
Employee
(NAME,IS_CORRECT,IS_WRONG,COMPANY_ID,TRANSACTION_ID,DEFINITION)
VALUES
(Terminology,0,0,1,0,definitionTest)
2017-10-03 11:32:43.753 WARN 5392 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 984, SQLState: 42000
2017-10-03 11:32:43.753 ERROR 5392 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-00984: column not allowed here
Here is my Entity Class Employee.java is as follows:
package abc.def.mypackage.orm
#Entity
#Table(name = "EMPLOYEE")
public class Employee {
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIsCorrect() {
return isCorrect;
}
public void setIsCorrect(int isCorrect) {
this.isCorrect = isCorrect;
}
public int getIsWrong() {
return isWrong;
}
public void setIsWrong(int isWrong) {
this.isWrong = isWrong;
}
public int getCompanyId() {
return companyId;
}
public void setCompanyId(int companyId) {
this.companyId = companyId;
}
public Integer getTransactionId() {
return transactionId;
}
public void setTransactionId(Integer transactionId) {
this.transactionId = transactionId;
}
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
#Id
#Column(name = "EMPLOYEE_ID")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "seqgen")
#SequenceGenerator(name = "seqgen", sequenceName = "EMPLOYEE_AUTOINC_SEQ")
private int employeeId;
#Column(name = "NAME")
private String name;
#Column(name = "DEFINITION")
private String definition;
#Column(name = "IS_CORRECT")
private int isCorrect;
#Column(name = "IS_WRONG")
private int isWrong;
#Column(name = "COMPANY_ID")
private int companyId;
#Column(name = "TRANSACTION_ID", nullable = true)
private Integer transactionId;
}
Try putting your String values employee.getName() and employee.getDefinition() in your insert statement into quotes '
String hqlInsert = "INSERT INTO Employee (NAME,IS_CORRECT,IS_WRONG,COMPANY_ID,TRANSACTION_ID,DEFINITION) VALUES "
+ "('"
+employee.getName()+"',"
+employee.getIsCorrect()+","
+employee.getIsWrong()+","
+getCompanyID+","
+employee.getTransactionId()+",'"
+employee.getDefinition()+"')";

Spring H2 Database, Not Creating table in Database

The following code is creating test.mv.db file. It also run properly and show that it has inserted data in the database.
Schema:
create table Customer (
id identity,
firstname varchar(20) not null,
lastname varchar(20) not null
);
Main Class:
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
CustomerRepository repo = ctx.getBean(CustomerRepository.class);
Customer c1 = new Customer("John", "Doe");
Customer c2 = new Customer("Jane", "Doe");
// insert
c1 = repo.save(c1);
c2 = repo.save(c2);
for(Customer t : repo.findAll()) {
System.out.println(t.getFirstName()+", "+t.getLastName());
}
ctx.close();
}
}
Config:
#Configuration
#ComponentScan
public class Config {
#Bean
public DataSource datasource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("org.h2.Driver");
ds.setUrl("jdbc:h2:~/test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
Resource schema = new ClassPathResource("schema.sql");
ResourceDatabasePopulator dbp = new ResourceDatabasePopulator();
dbp.addScript(schema);
DatabasePopulatorUtils.execute(dbp, ds);
return ds;
}
#Bean
public JdbcOperations jdbcTemplate(DataSource ds) {
return new JdbcTemplate(ds);
}
}
Customer Class:
public class Customer {
private Long id;
private String firstName;
private String lastName;
public Customer() {}
public Customer(Long id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public Customer(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
CustomerRepository Interface:
public interface CustomerRepository {
Customer findOne(long id);
Customer save(Customer cust);
List<Customer> findAll();
int update(Customer cust);
int delete (Customer cust);
}
CustomerRepositoryImpl:
#Repository
public class CustomerRepositoryImpl implements CustomerRepository {
#Autowired
private JdbcOperations jdbc;
private static final String SQL_INSERT = "insert into customer (firstname, lastname) values (?, ?)";
private static final String SQL_UPDATE = "update customer set firstname=?, lastname=? where id=?";
private static final String SQL_FIND_ONE = "select * from customer where id = ?";
private static final String SQL_FIND_ALL = "select * from customer order by lastname";
private static final String SQL_DELETE_ONE = "delete from customer where id = ?";
public Customer findOne(long id) {
return jdbc.queryForObject(SQL_FIND_ONE, new CustomerRowMapper(), id);
}
public Customer save(final Customer cust) {
KeyHolder holder = new GeneratedKeyHolder();
int rows = jdbc.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
PreparedStatement ps = conn.prepareStatement(SQL_INSERT, new String[]{"id"});
ps.setString(1, cust.getFirstName());
ps.setString(2, cust.getLastName());
return ps;
}
}, holder);
if(rows == 1) { // success, so apply ID to the customer object
cust.setId((Long)holder.getKey());
return cust;
}
return null;
}
public List<Customer> findAll() {
return jdbc.query(SQL_FIND_ALL, new CustomerRowMapper());
}
public int update(Customer cust) {
return jdbc.update(SQL_UPDATE, cust.getFirstName(), cust.getLastName(), cust.getId());
}
public int delete(Customer cust) {
return jdbc.update(SQL_DELETE_ONE, cust.getId());
}
private class CustomerRowMapper implements RowMapper<Customer> {
public Customer mapRow(ResultSet rs, int row) throws SQLException {
return new Customer(rs.getLong("id"), rs.getString("firstname"), rs.getString("lastname"));
}
}
}
Stacktrace:
Aug 14, 2017 9:45:42 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#b81eda8: startup date [Mon Aug 14 21:45:42 BDT 2017]; root of context hierarchy
Aug 14, 2017 9:45:43 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: org.h2.Driver
Aug 14, 2017 9:45:43 PM org.springframework.jdbc.datasource.init.ScriptUtils executeSqlScript
INFO: Executing SQL script from class path resource [schema.sql]
Aug 14, 2017 9:45:43 PM org.springframework.jdbc.datasource.init.ScriptUtils executeSqlScript
INFO: Executed SQL script from class path resource [schema.sql] in 28 ms.
Aug 14, 2017 9:45:43 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#b81eda8: startup date [Mon Aug 14 21:45:42 BDT 2017]; root of context hierarchy
John, Doe
Jane, Doe
Problem
But on second run previously saved data is no more there. First I checked with dbeaver, if there is any table within the database named Customer. I Could not find any.
Then I commented out the following lines -
c1 = repo.save(c1);
c2 = repo.save(c2);
from App.java
Becasue, if there are any data it will just read it from there with
for(Customer t : repo.findAll()) {
System.out.println(t.getFirstName()+", "+t.getLastName());
}
But no luck here as well.
What can be the problem please?
A working solution with derby is also welcome where the database is saved in the PC.

Converter doesn't work and not taken by criteria

i'm new here^^
i'm working with a db in which boolean are registered as VARCHAR(3) So i made a converter :
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
#Converter
public class BooleanToStringConverter implements
AttributeConverter<Boolean, String> {
#Override
public String convertToDatabaseColumn(Boolean value) {
if (value == null)
return "";
else if (value)
return "OUI";
else
return "NON";
}
#Override
public Boolean convertToEntityAttribute(String value) {
if (value == null)
return null;
else if (value.trim().equals("OUI"))
return true;
else if (value.trim().equals("NON"))
return false;
else if (value.trim().equals(""))
return null;
else
throw new IllegalStateException("Invalid boolean character: "
+ value);
}
}
i put my annotations #Convert:
public class Institution extends AbstractHREntity {
#Column(name = "IDOU00")
private String code;
#Column(table = "ZEXX", name = "LBOULG")
private String libelle;
#Column(table = "ZEXX", name = "LBOUSH")
private String abreviation;
#Column(table = "ZEYY", name = "LIBEXL")
private String libelleLong;
#Convert(converter = BooleanToStringConverter.class)
#Column(table = "ZEZZ", name = "ESTBUDGET", length = 3)
private Boolean isBudget;[/CODE]
But when i do a request with a criteria :
public List<Institution> findInstitutions(RechercheInstitutionData datas) throws DaoException{
List<Institution> resultList = new ArrayList<Institution>();
DetachedCriteria criteria = DetachedCriteria.forClass(Institution.class, "institution");
if(null!=datas.getInstitutionSearched())
{
if (StringUtils.isNotBlank(datas.getInstitutionSearched().getLibelleLong())){
criteria.add(Restrictions.like("institution.libelleLong", datas.getInstitutionSearched().getLibelleLong().toUpperCase(), MatchMode.START));
}
if (StringUtils.isNotBlank(datas.getInstitutionSearched().getAbreviation())){
criteria.add(Restrictions.like("institution.abreviation", datas.getInstitutionSearched().getAbreviation().toUpperCase(), MatchMode.START));
}
if (StringUtils.isNotBlank(datas.getInstitutionSearched().getLibelle())){
criteria.add(Restrictions.like("institution.libelle", datas.getInstitutionSearched().getLibelle(), MatchMode.START).ignoreCase());
}
if (StringUtils.isNotBlank(datas.getInstitutionSearched().getCode())){
criteria.add(Restrictions.like("institution.code", datas.getInstitutionSearched().getCode(), MatchMode.START));
}
criteria.addOrder(Order.asc("institution.code"));
}
resultList = find(criteria);
return resultList;
}
i had this error that occurred :
10:25:31,172 INFO [RechercheInstitution.beans.RechercheInstitutionBean] (http-localhost/127.0.0.1:8080-5) --> findInstitutions()
10:25:32,549 INFO [stdout] (http-localhost/127.0.0.1:8080-5) Hibernate: select this_.NUDOSS as NUDOSS1_35_0_, this_.IDOU00 as IDOU2_35_0_, this_1_.TBUDGE as TBUDGE1_39_0_, this_2_.LIBEXL as LIBEXL1_37_0_, this_3_.LBOUSH as LBOUSH1_36_0_, this_3_.LBOULG as LBOULG2_36_0_ from ZE00 this_ left outer join ZEWD this_1_ on this_.NUDOSS=this_1_.NUDOSS left outer join ZE04 this_2_ on this_.NUDOSS=this_2_.NUDOSS left outer join ZE01 this_3_ on this_.NUDOSS=this_3_.NUDOSS where this_3_.LBOUSH like ? order by this_.IDOU00 asc
10:25:33,310 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:8080-5) SQL Error: -99999, SQLState: 07006
10:25:33,311 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:8080-5) Data type mismatch. (For input string: "OUI")
10:25:33,313 ERROR [RechercheInstitution.ejb.institution.InstitutionMgrBean] (http-localhost/127.0.0.1:8080-5) InstitutionMgrBean.findInstitutions : common_HR.exception.DaoException: org.hibernate.exception.SQLGrammarException: could not execute query
10:25:33,315 INFO [RechercheInstitution.beans.RechercheInstitutionBean] (http-localhost/127.0.0.1:8080-5) <-- findInstitutions()
It looks like it doesn't use my converter, i tried breakpoints it doesn't go into my converter... In converter doc it says "all you have to do is put the #convert" but apparently no... Please help i'm really lost.

Display Oracle date in a given format with JSTL using Hibernate

I have a date field in a table in an Oracle(10g) database which is mapped by TemporalType.TIMESTAMP in Hibernate like,
#Column(name = "DISCOUNT_START_DATE")
#Temporal(TemporalType.TIMESTAMP)
private Date discountStartDate;
//Setter and getter.
It fetches dates and displays like the following (which are already inserted into the database),
2012-08-29 01:53:10.0
2012-08-20 02:32:22.0
2012-08-01 14:00:21.0
2012-08-20 13:58:01.0
2012-08-30 04:14:13.0
2012-09-10 16:13:45.0
When I attempt to display them using JSTL like,
<fmt:formatDate pattern="dd-MMM-yyyy hh:mm:ss" value="${row.discountStartDate}"/>
it throws an exception,
javax.el.ELException: Cannot convert 2012-08-29 01:53:10.0 of type
class java.lang.String to class java.util.Date
I have tried to change TemporalType.TIMESTAMP to TemporalType.DATE but didn't work.
Earlier, it was working with XML mapping files (xxx.hbm.xml) like.
<property name="discountStartDate" type="date">
<column length="7" name="DISCOUNT_START_DATE"/>
</property>
but with annotations, it failed. How to apply this format dd-MMM-yyyy hh:mm:ss to display those dates in JSP using JSTL?
EDIT:
The following is the Discount entity class which is mapped with the DSCOUNT table in Oracle (the equals() and the toString() methods have been omitted).
#Entity
#Table(name = "DISCOUNT", catalog = "", schema = "WAGAFASHIONDB")
public class Discount implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "DISCOUNT_ID", nullable = false, precision = 35, scale = 0)
#SequenceGenerator(name = "discountIdSequence", sequenceName = "DISCOUNT_SEQ", allocationSize=1, initialValue=1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "discountIdSequence")
private Long discountId;
#Column(name = "DISCOUNT_CODE", length = 100)
private String discountCode;
#Column(name = "DISCOUNT_PER", precision = 35, scale = 2)
private double discountPer;
#Column(name = "DISCOUNT_START_DATE")
#Temporal(TemporalType.TIMESTAMP)
private Date discountStartDate;
#Column(name = "DISCOUNT_END_DATE")
#Temporal(TemporalType.TIMESTAMP)
private Date discountEndDate;
#OneToMany(mappedBy = "discountId", fetch = FetchType.LAZY)
private Set<OrderTable> orderTableSet;
public Discount() {
}
public Discount(Long discountId) {
this.discountId = discountId;
}
public Long getDiscountId() {
return discountId;
}
public void setDiscountId(Long discountId) {
this.discountId = discountId;
}
public String getDiscountCode() {
return discountCode;
}
public void setDiscountCode(String discountCode) {
this.discountCode = discountCode;
}
public double getDiscountPer() {
return discountPer;
}
public void setDiscountPer(double discountPer) {
this.discountPer = discountPer;
}
public Date getDiscountStartDate() {
return discountStartDate;
}
public void setDiscountStartDate(Date discountStartDate) {
this.discountStartDate = discountStartDate;
}
public Date getDiscountEndDate() {
return discountEndDate;
}
public void setDiscountEndDate(Date discountEndDate) {
this.discountEndDate = discountEndDate;
}
public Set<OrderTable> getOrderTableSet() {
return orderTableSet;
}
public void setOrderTableSet(Set<OrderTable> orderTableSet) {
this.orderTableSet = orderTableSet;
}
}
In JSP, the following loop is used to display data (reducing the code complexity).
<c:forEach var="row" items="${list}" varStatus="loop">
<fmt:formatDate pattern="dd-MMM-yyyy hh:mm:ss" value="${row.discountStartDate}"/>
</c:forEach>
and in Spring DAO, the list which is iterated by the preceding loop is simply retrieved as follows.
#SuppressWarnings("unchecked")
public List<Discount>getList(int currentPage, int rowsPerPage)
{
List<Discount> list = sessionFactory.getCurrentSession()
.createQuery("from Discount order by discountId desc")
.setFirstResult(currentPage)
.setMaxResults(rowsPerPage).list();
for(Discount d:list)
{
System.out.println(d.getDiscountStartDate()+" : "+d.getDiscountEndDate());
}
return list;
}
The preceding loop is just for the sake of demonstration. It displays the dates from the table as follows.
2012-08-29 01:53:10.0 : 2012-08-31 01:53:16.0
2012-08-20 02:32:22.0 : 2012-08-24 02:34:36.0
2012-08-01 14:00:21.0 : 2012-08-31 14:01:30.0
2012-08-20 13:58:01.0 : 2012-08-21 13:58:20.0
2012-08-30 04:14:13.0 : 2012-11-23 16:21:57.0
2012-09-10 16:13:45.0 : 2012-10-26 16:13:39.0
2012-08-22 16:06:23.0 : 2012-08-15 16:06:17.0
2012-08-22 10:35:04.0 : 2012-08-17 10:34:56.0
2012-08-17 10:35:29.0 : 2012-08-10 10:35:35.0
2012-10-08 10:35:56.0 : 2013-03-08 10:35:49.0

Resources