java 休眠的奇怪行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35643664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:24:09  来源:igfitidea点击:

Strange behavior of hibernate

javahibernate

提问by Md Faisal

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

我是休眠的新手,我从中得到了一些奇怪的行为,下面是场景。

My java files are

我的java文件是

UserDetails.java

用户详细信息.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

车辆.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

休眠测试.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

hibernate.cfg.xml 文件

<?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

我在 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.

所以我的问题是为什么应用程序在第一次运行时没有成功运行,为什么它在第二次运行中成功运行。

采纳答案by Musaddique

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

还删除或修改 hibernate.cfg.xml 中的此属性

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

回答by Santosh Kumar

When you use

当你使用

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

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

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

Hibernate 首先尝试删除您正在使用的表,然后每次都重新创建它们。

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.

希望这可以帮助。

回答by v.ladynev

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

我检查您的映射 - 一切正常,使用相同的 Hibernate 5.1 版本。看起来问题不在于映射。那么你可以尝试做什么

  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.

  1. 我使用旧的 MySQL 版本 (4.1)。如果您使用 MySQL 5,请尝试设置

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

  2. 检查 MySQL 驱动程序。我用mysql-connector-java-5.1.37.jar.

  3. 使用 MySQL 删除所有数据库(不是表,而是所有数据库)。

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

来自我尝试日志的 SQL 命令(您可以使用 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)

回答by mvlaicevich

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:

这是因为当您运行此命令时,您没有删除 FK:

drop table if exists USER_DETAILS

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

您需要更改关系以允许 Cascade 删除子对象。

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

这是一个例子:http: //docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-cascade