6

I am new to hibernate and I have getting some strange behavior from it, below is the scenario.

My java files are

UserDetails.java

package org.javabrains.faisal.dto; import java.util.ArrayList; import java.util.Collection; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name = "USER_DETAILS") public class UserDetails { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "USER_ID") private int userId; @Column(name = "USER_NAME") private String userName; @ManyToMany @JoinTable(name="USER_VEHICLE",joinColumns=@JoinColumn(name="USER_ID"),inverseJoinColumns=@JoinColumn(name="VEHICLE_ID")) private Collection<Vehicle> vehicle = new ArrayList<>(); public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Collection<Vehicle> getVehicle() { return vehicle; } public void setVehicle(Collection<Vehicle> vehicle) { this.vehicle = vehicle; } } 

Vehicle.java

package org.javabrains.faisal.dto; import java.util.ArrayList; import java.util.Collection; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="VEHICLE") public class Vehicle { @Id @GeneratedValue @Column(name="VEHICLE_ID") private int vehicleId; @Column(name="VEHICLE_NAME") private String vehicleName; @ManyToMany(mappedBy="vehicle") private Collection<UserDetails> userList=new ArrayList<UserDetails>(); public Collection<UserDetails> getUserList() { return userList; } public void setUserList(Collection<UserDetails> userList) { this.userList = userList; } public int getVehicleId() { return vehicleId; } public void setVehicleId(int vehicleId) { this.vehicleId = vehicleId; } public String getVehicleName() { return vehicleName; } public void setVehicleName(String vehicleName) { this.vehicleName = vehicleName; } } 

HibernateTest.java

package org.javabrain.faisal.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.javabrains.faisal.dto.UserDetails; import org.javabrains.faisal.dto.Vehicle; public class HibernateTest { public static void main(String[] args) { UserDetails user = new UserDetails(); UserDetails user2 = new UserDetails(); user.setUserName("Faisal"); user2.setUserName("Raza"); Vehicle vehicle=new Vehicle(); Vehicle vehicle2=new Vehicle(); Vehicle vehicle3=new Vehicle(); vehicle.setVehicleName("Bullet ThunderBird"); vehicle2.setVehicleName("yamaha"); vehicle3.setVehicleName("bullet"); //Didirectional relationship user.getVehicle().add(vehicle); vehicle.getUserList().add(user); user.getVehicle().add(vehicle2); vehicle2.getUserList().add(user); user2.getVehicle().add(vehicle3); vehicle3.getUserList().add(user2); // sessionFactory one object per application SessionFactory sessionFactory = new Configuration().configure() .buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(user); session.save(user2); session.save(vehicle); session.save(vehicle2); session.save(vehicle3); session.getTransaction().commit(); session.close(); } } 

hibernate.cfg.xml file

<?xml version='1.0' encoding='utf-8'?> <!-- ~ Hibernate, Relational Persistence for Idiomatic Java ~ ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later. ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. --> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 3306 is default port number for mysql --> <property name="connection.url">jdbc:mysql://localhost:3306/hibernatedb</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- re-create the database every time --> <property name="hbm2ddl.auto">create</property> <!-- Name the annotated entity class Here we have declared the class which have entities if you define a new entity class; an entry goes here below --> <mapping class="org.javabrains.faisal.dto.UserDetails"/> <mapping class="org.javabrains.faisal.dto.Vehicle"/> </session-factory> </hibernate-configuration> 

I added below code in userDetails.java

@JoinTable(name="USER_VEHICLE",joinColumns=@JoinColumn(name="USER_ID"),inverseJoinColumns=@JoinColumn(name="VEHICLE_ID")) 

and run the application:-

Full stack trace while there were tables defined from previous application run(the one without above line) in the database..

Feb 26, 2016 12:58:13 AM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {5.1.0.Final} Feb 26, 2016 12:58:13 AM org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found Feb 26, 2016 12:58:13 AM org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist Feb 26, 2016 12:58:13 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final} Feb 26, 2016 12:58:13 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) Feb 26, 2016 12:58:13 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/hibernatedb] Feb 26, 2016 12:58:13 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001001: Connection properties: {user=root, password=****} Feb 26, 2016 12:58:13 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001003: Autocommit mode: false Feb 26, 2016 12:58:13 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init> INFO: HHH000115: Hibernate connection pool size: 1 (min=1) Feb 26, 2016 12:58:14 AM org.hibernate.dialect.Dialect <init> INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect Hibernate: alter table USER_VEHICLE drop foreign key FK48dbrk0k7004g3jff5xftyrxx Hibernate: alter table USER_VEHICLE drop foreign key FKay5vn6ovfwhmoi2w1wrxxry0 Hibernate: drop table if exists hibernate_sequence Hibernate: drop table if exists USER_DETAILS Feb 26, 2016 12:58:15 AM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException WARN: GenerationTarget encountered exception accepting command : Unable to execute command [drop table if exists USER_DETAILS] org.hibernate.tool.schema.spi.CommandAcceptanceException: Unable to execute command [drop table if exists USER_DETAILS] at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:63) at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:370) at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:355) at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:240) at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:153) at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:125) at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:111) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:137) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:64) at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:458) at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724) at org.javabrain.faisal.hibernate.HibernateTest.main(HibernateTest.java:40) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails 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:400) at com.mysql.jdbc.Util.getInstance(Util.java:383) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2541) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2499) at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:844) at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:748) at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:51) ... 13 more Hibernate: drop table if exists USER_VEHICLE Hibernate: drop table if exists VEHICLE Feb 26, 2016 12:58:16 AM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException WARN: GenerationTarget encountered exception accepting command : Unable to execute command [drop table if exists VEHICLE] org.hibernate.tool.schema.spi.CommandAcceptanceException: Unable to execute command [drop table if exists VEHICLE] at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:63) at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:370) at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:355) at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:240) at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:153) at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:125) at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:111) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:137) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:64) at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:458) at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724) at org.javabrain.faisal.hibernate.HibernateTest.main(HibernateTest.java:40) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails 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:400) at com.mysql.jdbc.Util.getInstance(Util.java:383) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2541) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2499) at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:844) at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:748) at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:51) ... 13 more Hibernate: create table hibernate_sequence (next_val bigint) Hibernate: insert into hibernate_sequence values ( 1 ) Hibernate: insert into hibernate_sequence values ( 1 ) Hibernate: create table USER_DETAILS (USER_ID integer not null, USER_NAME varchar(255), primary key (USER_ID)) Feb 26, 2016 12:58:16 AM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException WARN: GenerationTarget encountered exception accepting command : Unable to execute command [create table USER_DETAILS (USER_ID integer not null, USER_ NAME varchar(255), primary key (USER_ID))] org.hibernate.tool.schema.spi.CommandAcceptanceException: Unable to execute command [create table USER_DETAILS (USER_ID integer not null, USER_NAME va rchar(255), primary key (USER_ID))] at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:63) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:423) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:408) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:310) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:165) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:134) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:120) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:148) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:64) at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:458) at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724) at org.javabrain.faisal.hibernate.HibernateTest.main(HibernateTest.java:40) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'user_details' already exists 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:400) at com.mysql.jdbc.Util.getInstance(Util.java:383) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:980) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2541) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2499) at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:844) at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:748) at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:51) ... 13 more Hibernate: create table USER_VEHICLE (USER_ID integer not null, VEHICLE_ID integer not null) Hibernate: create table VEHICLE (VEHICLE_ID integer not null, VEHICLE_NAME varchar(255), primary key (VEHICLE_ID)) Feb 26, 2016 12:58:16 AM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException WARN: GenerationTarget encountered exception accepting command : Unable to execute command [create table VEHICLE (VEHICLE_ID integer not null, VEHICLE _NAME varchar(255), primary key (VEHICLE_ID))] org.hibernate.tool.schema.spi.CommandAcceptanceException: Unable to execute command [create table VEHICLE (VEHICLE_ID integer not null, VEHICLE_NAME v archar(255), primary key (VEHICLE_ID))] at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:63) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:423) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:408) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:310) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:165) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:134) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:120) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:148) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:64) at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:458) at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724) at org.javabrain.faisal.hibernate.HibernateTest.main(HibernateTest.java:40) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'vehicle' already exists 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:400) at com.mysql.jdbc.Util.getInstance(Util.java:383) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:980) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2541) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2499) at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:844) at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:748) at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:51) ... 13 more 

Re-running the application again with (no code changes) and getting no errors in the stacktrace

Feb 26, 2016 1:01:22 AM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {5.1.0.Final} Feb 26, 2016 1:01:22 AM org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found Feb 26, 2016 1:01:22 AM org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist Feb 26, 2016 1:01:22 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final} Feb 26, 2016 1:01:22 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) Feb 26, 2016 1:01:22 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/hibernatedb] Feb 26, 2016 1:01:22 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001001: Connection properties: {user=root, password=****} Feb 26, 2016 1:01:22 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001003: Autocommit mode: false Feb 26, 2016 1:01:22 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init> INFO: HHH000115: Hibernate connection pool size: 1 (min=1) Feb 26, 2016 1:01:23 AM org.hibernate.dialect.Dialect <init> INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect Hibernate: alter table USER_VEHICLE drop foreign key FK48dbrk0k7004g3jff5xftyrxx Hibernate: alter table USER_VEHICLE drop foreign key FKay5vn6ovfwhmoi2w1wrxxry0 Hibernate: drop table if exists hibernate_sequence Hibernate: drop table if exists USER_DETAILS Hibernate: drop table if exists USER_VEHICLE Hibernate: drop table if exists VEHICLE Hibernate: create table hibernate_sequence (next_val bigint) Hibernate: insert into hibernate_sequence values ( 1 ) Hibernate: insert into hibernate_sequence values ( 1 ) Hibernate: create table USER_DETAILS (USER_ID integer not null, USER_NAME varchar(255), primary key (USER_ID)) Hibernate: create table USER_VEHICLE (USER_ID integer not null, VEHICLE_ID integer not null) Hibernate: create table VEHICLE (VEHICLE_ID integer not null, VEHICLE_NAME varchar(255), primary key (VEHICLE_ID)) Hibernate: alter table USER_VEHICLE add constraint FK48dbrk0k7004g3jff5xftyrxx foreign key (VEHICLE_ID) references VEHICLE (VEHICLE_ID) Hibernate: alter table USER_VEHICLE add constraint FKay5vn6ovfwhmoi2w1wrxxry0 foreign key (USER_ID) references USER_DETAILS (USER_ID) Feb 26, 2016 1:01:28 AM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@1ad9bb2' Hibernate: select next_val as id_val from hibernate_sequence for update Hibernate: update hibernate_sequence set next_val= ? where next_val=? Hibernate: select next_val as id_val from hibernate_sequence for update Hibernate: update hibernate_sequence set next_val= ? where next_val=? Hibernate: select next_val as id_val from hibernate_sequence for update Hibernate: update hibernate_sequence set next_val= ? where next_val=? Hibernate: select next_val as id_val from hibernate_sequence for update Hibernate: update hibernate_sequence set next_val= ? where next_val=? Hibernate: select next_val as id_val from hibernate_sequence for update Hibernate: update hibernate_sequence set next_val= ? where next_val=? Hibernate: insert into USER_DETAILS (USER_NAME, USER_ID) values (?, ?) Hibernate: insert into USER_DETAILS (USER_NAME, USER_ID) values (?, ?) Hibernate: insert into VEHICLE (VEHICLE_NAME, VEHICLE_ID) values (?, ?) Hibernate: insert into VEHICLE (VEHICLE_NAME, VEHICLE_ID) values (?, ?) Hibernate: insert into VEHICLE (VEHICLE_NAME, VEHICLE_ID) values (?, ?) Hibernate: insert into USER_VEHICLE (USER_ID, VEHICLE_ID) values (?, ?) Hibernate: insert into USER_VEHICLE (USER_ID, VEHICLE_ID) values (?, ?) Hibernate: insert into USER_VEHICLE (USER_ID, VEHICLE_ID) values (?, ?) 

So my question is why does the application didn't run successfully in the first run and why did it run successfully in second run.

4 Answers 4

6

use

 @ManyToMany(cascade=CascadeType.ALL) @JoinTable(name="USER_VEHICLE",joinColumns=@JoinColumn(name="USER_ID"),inverseJoinColumns=@JoinColumn(name="VEHICLE_ID")) private Collection<Vehicle> vehicle = new ArrayList<>(); 

also remove or modify this property in hibernate.cfg.xml

<property name="hbm2ddl.auto">update</property> 
Sign up to request clarification or add additional context in comments.

4 Comments

By using update , I got no errors, but I have to re-create the database in every run of the application
Hibernate: alter table USER_VEHICLE drop foreign key FK48dbrk0k7004g3jff5xftyrxx Hibernate: alter table USER_VEHICLE drop foreign key FKay5vn6ovfwhmoi2w1wrxxry0 getting errors in above two lines Hibernate: drop table if exists hibernate_sequence Hibernate: drop table if exists USER_DETAILS Hibernate: drop table if exists USER_VEHICLE Hibernate: drop table if exists VEHICLE
its mappedBy in vehicle
1

When you use

<property name="hbm2ddl.auto">create</property>

Hibernate first tries to drop the tables that you're using and then recreates them every time.

So when you're running your application for the first time, since the tables doesn't exist in the database, you're facing the error. When you run your program from next time, you'll not see the above error, as the tables exist and hibernate will be able to drop them successfully.

Hope this helps.

Comments

0

the error that you have is because of the order you are creating/deleting your tables:

Cannot delete or update a parent row: a foreign key constraint fails

This is because you are having a FK that you are not deleting when you run this:

drop table if exists USER_DETAILS 

you need to change your relation to allow Cascade for deleting child objects.

this is an example: http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-cascade

4 Comments

added line @ManyToMany(cascade=CascadeType.ALL) and found that it still gives an error for the first time
I am not deleting it manually, I just run the java application
try to change this: <property name="hbm2ddl.auto">create</property> to: <property name="hbm2ddl.auto">create-drop</property>
0

I check your mapping — everything works fine, using the same Hibernate 5.1 version. Looks like a problem is not with mapping. So what you can try to do

  1. I use old MySQL version (4.1). If you use MySQL 5, try to set

    <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

  2. Check MySQL driver. I use mysql-connector-java-5.1.37.jar.

  3. Drop all database (not tables, but all database) using MySQL.

SQL commands from log of my try (you can execute it using MySQL)

alter table USER_VEHICLE drop foreign key FK48dbrk0k7004g3jff5xftyrxx alter table USER_VEHICLE drop foreign key FKay5vn6ovfwhmoi2w1wrxxry0 drop table if exists USER_DETAILS drop table if exists USER_VEHICLE drop table if exists VEHICLE create table USER_DETAILS ( USER_ID integer not null, USER_NAME varchar(255), primary key (USER_ID) ) create table USER_VEHICLE ( USER_ID integer not null, VEHICLE_ID integer not null ) create table VEHICLE ( VEHICLE_ID integer not null, VEHICLE_NAME varchar(255), primary key (VEHICLE_ID) ) alter table USER_VEHICLE add constraint FK48dbrk0k7004g3jff5xftyrxx foreign key (VEHICLE_ID) references VEHICLE (VEHICLE_ID) alter table USER_VEHICLE add constraint FKay5vn6ovfwhmoi2w1wrxxry0 foreign key (USER_ID) references USER_DETAILS (USER_ID) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.