我是hibernate的新手,我从中获得了一些奇怪的行为,下面就是这个场景。
我的java文件是
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文件
<?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>
我在userDetails.java
中添加了以下代码@JoinTable(name="USER_VEHICLE",joinColumns=@JoinColumn(name="USER_ID"),inverseJoinColumns=@JoinColumn(name="VEHICLE_ID"))
并运行应用程序: -
完整的堆栈跟踪,同时在数据库中运行了先前应用程序运行的表(没有上面一行)...
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
使用(无代码更改)重新运行应用程序并在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 (?, ?)
所以我的问题是为什么应用程序在第一次运行中没有成功运行,为什么它在第二次运行中成功运行。
答案 0 :(得分:6)
使用
@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name="USER_VEHICLE",joinColumns=@JoinColumn(name="USER_ID"),inverseJoinColumns=@JoinColumn(name="VEHICLE_ID"))
private Collection<Vehicle> vehicle = new ArrayList<>();
还在hibernate.cfg.xml中删除或修改此属性
<property name="hbm2ddl.auto">update</property>
答案 1 :(得分:1)
使用时
<property name="hbm2ddl.auto">create</property>
Hibernate首先尝试删除您正在使用的表,然后每次都重新创建它们。
因此,当您第一次运行应用程序时,由于数据库中不存在这些表,您将面临错误。当你下次运行你的程序时,你不会看到上面的错误,因为表存在并且hibernate将能够成功地删除它们。
希望这有帮助。
答案 2 :(得分:0)
您遇到的错误是因为您创建/删除表格的顺序:
无法删除或更新父行:外键约束 失败
这是因为你在运行时没有删除FK:
drop table if exists USER_DETAILS
您需要更改关系以允许Cascade删除子对象。
这是一个例子:http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-cascade
答案 3 :(得分:0)
我检查你的映射 - 一切正常,使用相同的Hibernate 5.1版本。看起来问题不在于映射。所以你可以尝试做什么
我使用旧的MySQL版本(4.1)。如果您使用MySQL 5,请尝试设置
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
检查MySQL驱动程序。我使用mysql-connector-java-5.1.37.jar
。
使用MySQL删除所有数据库(不是表,而是所有数据库)。
我的try日志中的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)