i am new in Hibernate, i am getting exception when trying to save Friend_Job object on database.
I am getting Friend and Job object from database and creating new Frien_Job object.
Test.java
SessionFactory sessionFectory = new Configuration().configure().buildSessionFactory();
Session session = sessionFectory.openSession();
Transaction transaction = session.beginTransaction();
Friend friend= (Friend) session.load(Friend.class, new Integer(1));
Job job = (Job) session.load(Job.class, new Integer(3));
Friend_Job friend_Job = new Friend_Job();
friend_Job.setFriend(friend);
friend_Job.setJob(job);
friend_Job.setCompanyName(job.getCompanyName());
session.save(friend_Job);
transaction.commit(); //Exception here
Friend_Job.hbm.xml
<hibernate-mapping>
<class name="hibernateTest.Friend_Job" table="FRIEND_JOB">
<id name="primaryKey" column="PRIMARY_KEY">
<generator class="increment"/>
</id>
<property name="companyName" type="string" column="COMPANY_NAME"/>
<property name="salary" column="SALARY"/>
<many-to-one name="friend" class="hibernateTest.Friend" cascade="none" column="FK_FRIEND_ID"/>
<many-to-one name="job" class="hibernateTest.Job" cascade="none" column="FK_JOB_ID"/>
</class>
</hibernate-mapping>
Exception :-
org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)
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:1027)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at hibernateTest.Test.main(Test.java:20)
Caused by: java.sql.BatchUpdateException: ORA-00932: inconsistent datatypes: expected BINARY got NUMBER
Friend_Job.java
public class Friend_Job {
private int primaryKey;
private String companyName;
private int salary = 0;
private Friend friend;
private Job job;
and else are setter and getter.
Please let me know if more info required….
Thanks in advance.
i am fresher to hibernate framework,i try to run my first hibernate application i got the following exception,
Exception
Exception in thread "main" org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.java4s.insert.InsertMain.main(InsertMain.java:26) Caused by: java.sql.BatchUpdateException: 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 'insert (user, pass, sno) values ('krish', 'password', 1)' at line 1 at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2045)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1468)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)... 8 more Caused by: 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 'insert (user, pass, sno) values ('krish', 'password', 1)' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2683)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2144)
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver-class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="show_sql">true</property>
<property name="dilect">org.hibernate.dialect.MySQL.Dialect</property>
<property name="hbm2dll.auto">update</property>
<mapping resource="Insert.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Insert.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.java4s.insert.Insert" table="insert">
<id name="sno" column="sno"/>
<property name="username" column="user"/>
<property name="password" column="pass"/>
</class>
</hibernate-mapping>
Insert.java(POJO class)
public class Insert {
private int sno;
private String username;
private String password;
//setter and getter method;
}
InsertMain(Configuration class)
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class InsertMain {
public static void main(String[] args) {
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory=cfg.buildSessionFactory();
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
Insert i=new Insert();
i.setSno(1);
i.setUsername("krish");
i.setPassword("password");
session.save(i);
System.out.println("Object saved successfully.....!!");
tx.commit();
session.close();
factory.close();
}
}
i am new in Hibernate, i am getting exception when trying to save Friend_Job object on database.
I am getting Friend and Job object from database and creating new Frien_Job object.
Test.java
SessionFactory sessionFectory = new Configuration().configure().buildSessionFactory();
Session session = sessionFectory.openSession();
Transaction transaction = session.beginTransaction();
Friend friend= (Friend) session.load(Friend.class, new Integer(1));
Job job = (Job) session.load(Job.class, new Integer(3));
Friend_Job friend_Job = new Friend_Job();
friend_Job.setFriend(friend);
friend_Job.setJob(job);
friend_Job.setCompanyName(job.getCompanyName());
session.save(friend_Job);
transaction.commit(); //Exception here
Friend_Job.hbm.xml
<hibernate-mapping>
<class name="hibernateTest.Friend_Job" table="FRIEND_JOB">
<id name="primaryKey" column="PRIMARY_KEY">
<generator class="increment"/>
</id>
<property name="companyName" type="string" column="COMPANY_NAME"/>
<property name="salary" column="SALARY"/>
<many-to-one name="friend" class="hibernateTest.Friend" cascade="none" column="FK_FRIEND_ID"/>
<many-to-one name="job" class="hibernateTest.Job" cascade="none" column="FK_JOB_ID"/>
</class>
</hibernate-mapping>
Exception :-
org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)
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:1027)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at hibernateTest.Test.main(Test.java:20)
Caused by: java.sql.BatchUpdateException: ORA-00932: inconsistent datatypes: expected BINARY got NUMBER
Friend_Job.java
public class Friend_Job {
private int primaryKey;
private String companyName;
private int salary = 0;
private Friend friend;
private Job job;
and else are setter and getter.
Please let me know if more info required….
Thanks in advance.
Could not execute JDBC batch update error reason
tags: java hibernate frame
**Could not execute JDBC batch update error reason **
org.hibernate.QueryTimeoutException: Could not execute JDBC batch update
Cause #1: The length of the content you are about to insert into the database exceeds the actual length of the field in the database.
Modify the length of the field in the database
Error Cause 2: The type of the property in the java class and the Hibernate configuration file. The inconsistency in the .hbm.xml statement can cause the above error.
Intelligent Recommendation
Spring — JDBC Batch Update
A JDBC batch update is multiple updates using the same database session. That is, we don’t have to open connections multiple times. In our previous example, let’s say we want to insert multiple Person…
Hibernate batch update and jdbc batch update
Header batch update refers to updating large amounts of data in one transaction. Bulk deletion refers to deleting large amounts of data in one transaction. The following program batch updates the AGE …
More Recommendation
![]()
JPA error (could not execute statement)
Error message could not execute statement; nested exception is org.hibernate.exception.GenericJDBCException: could not execute statement The error code The error occurred while saving the user, after …
Hibernate не удалось выполнить причину и способ устранения ошибки пакетного обновления JDBC
При использовании гибернации в качестве системы сегодня произошла ошибка Не удалось выполнить пакетное обновление JDBC, которая теперь устранена.
Позвольте мне сначала поговорить о моем коде:
Это файл конфигурации, соответствующий таблице ролей. Когда я удалял информацию о выбранной роли на странице jsp списка управления ролями, я сообщал об ошибке выше.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
<class name="com.cms.po.Trole" table="trole">
<id name="roleId" type="integer">
<column name="roleId" />
<generator class="native" />
</id>
<property name="roleName" type="string">
<column name="roleName" length="50" />
</property>
<property name="isDel" type="string">
<column name="isDel" length="2" />
</property>
<property name="roleDescribe" type="string">
<column name="roleDescribe" length="500" />
</property>
<property name="createTime" type="string">
<column name="createTime" length="32" />
</property> <! - Создан индивидуальный идентификатор пользователя ->
<many-to-one
name="tsysuser"
column="userId"
unique="true"
class="com.cms.po.Tsysuser" lazy="false"/>
</class>
</hibernate-mapping>
Каждая созданная роль соответствует идентификатору создателя, но для проверки проблемы я непосредственно вставил данные в таблицу и не вставил в таблицу userId создателя, а затем посмотрел код:
/**
* Удалить роли в пакете
*/
public boolean deleteRoles(String roleids) throws Exception {
String[] roleidArray = roleids.split(",");
for(int i=0; i<roleidArray.length; i++){
Trole trole = (Trole)this.getHibernateTemplate().get(Trole.class,new Integer(roleidArray[i]));
trole.setIsDel("1");
this.getHibernateTemplate().saveOrUpdate(trole);
}
return true;
}
Проблем нет, но я сообщил об ошибке «Не удалось выполнить пакетное обновление JDBC», главным образом из-за того, что файл конфигурации настроен как связанный, но данные не связаны. Пока данные верны, проблем нет.
Кроме того, причиной может быть то, что пакет jar драйвера базы данных не поддерживается.
Есть также следующие проблемы, упомянутые в столбце dizhang csdn:
1. Поскольку Hibernate Tools (или Database Explorer в самом Eclipse) генерирует инструмент * .hbn.xml, который содержит такие атрибуты, как catalog = «***» (* обозначает имя базы данных), удалите этот атрибут.
2. Предполагается, что в имени столбца есть ключевое слово. Не используйте дату, идентификатор … это ключевое слово при именовании столбца.
Проблемы с запросом Hibernate.
Каким-то образом сообщили о следующих ошибках,
org.hibernate.exception.GenericJDBCException: could not execute query
Не удалось выполнить JDBC. Ошибка пакетного обновления может быть вызвана китайской проблемой. Если вы используете JBoos4.2GA, не забудьте решить китайскую проблему:
1. Установите кодировку соединения JBoss: URIEcoding = «utf-8»
2. Используйте фильтр для решения китайских задач, много информации об этом онлайн
От: [url] http://blog.csdn.net/derpvailzhangfan/article/details/2332795 [/ url]
