我正在关注一个基本的hibernate教程。我想在2个表之间建立一对一的关系。
当我尝试在Client
表中插入它时,它会起作用,但当我尝试相反时(在Facture
表中插入)我得到了这个例外:
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: alter table facture drop foreign key FK_i4kuo9pjcqstd2tpftv9eprbk
oct. 20, 2014 3:15:05 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table facture drop foreign key FK_i4kuo9pjcqstd2tpftv9eprbk
oct. 20, 2014 3:15:05 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: Table 'mybase.facture' doesn't exist
Hibernate: drop table if exists client
Hibernate: drop table if exists facture
Hibernate: create table client (client_id integer not null auto_increment, Nom varchar(255), primary key (client_id))
Hibernate: create table facture (num_fact integer not null auto_increment, client_id integer, primary key (num_fact))
Hibernate: alter table facture add constraint FK_i4kuo9pjcqstd2tpftv9eprbk foreign key (client_id) references client (client_id)
oct. 20, 2014 3:15:05 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into facture (client_id) values (?)
oct. 20, 2014 3:15:05 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1452, SQLState: 23000
oct. 20, 2014 3:15:05 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Cannot add or update a child row: a foreign key constraint fails (`mybase`.`facture`, CONSTRAINT `FK_i4kuo9pjcqstd2tpftv9eprbk` FOREIGN KEY (`client_id`) REFERENCES `client` (`client_id`))
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:72)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at com.zack.hibernate.Main.main(Main.java:28)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`mybase`.`facture`, CONSTRAINT `FK_i4kuo9pjcqstd2tpftv9eprbk` FOREIGN KEY (`client_id`) REFERENCES `client` (`client_id`))
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
这是Client
类:
@Entity
@Table (name="client")
public class Client implements java.io.Serializable {
@Id /* pour dire a hibernate que id est une cle primaire*/
@GeneratedValue /* pour que hibernate générer automatiquement la clé primaire*/
private int client_id;
@Column(name="Nom")/* pour forcer hibernate a nommer la colonne par "Nom"*/
private String nom;
@OneToOne (mappedBy = "c")
private Facture f;
这是Facture
类:
@Entity
@Table(name="facture")
public class Facture implements java.io.Serializable {
@Id
@GeneratedValue
private int num_fact;
@OneToOne
@JoinColumn(name = "client_id")
private Client c;
这是Main
类:
public class Main {
public class Main {
public static void main(String[] args) {
Client c = new Client();
c.setClient_id(1);
c.setNom("Zack Smith");
Facture f = new Facture();
f.setNum_fact(1);
//c une étape importante
c.setF(f);
f.setC(c);
SessionFactory s = new AnnotationConfiguration().configure().buildSessionFactory();
Session ss = s.openSession();
ss.beginTransaction();
ss.save(f);
ss.getTransaction().commit();
ss.close();
s.close();
}
}
数据库图片:http://hpics.li/f1a3ee7
答案 0 :(得分:2)
在我看来,你可能会对Hibernate如何建立这些关系感到有些困惑。我认为您的异常是由于您说clientId
列/字段是映射到Facture
表的生成值,当您实际希望它引用clientId
列/时Client
表上的字段作为外键。因此,您试图保存Facture
对象,这会导致生成Facture.clientId
列(因为您使用@GenericGenerator
对其进行了注释)。由于此值已设置,因此Hibernate尝试使用生成的ID更新现有Client
对象。因为它实际上并不存在,所以你得到了你发布的例外。
您尝试做的主要是允许Hibernate在外键关系之间进行映射,以便您可以从Client
获取Facture
,反之亦然。
您不需要指定连接列,Hibernate默认为所有关系的@Id
列。您应该修改Client
课程,如下所示
@Entity
@Table (name="client")
public class Client implements java.io.Serializable {
@Id
@GeneratedValue
private int clientId;
//Keep the nom field, I just removed it for brevity.
@OneToOne (cascade = CascadeType.ALL)
private Facture facture;
并修改您的Facture
课程,如下所示:
@Entity
@Table(name="facture")
public class Facture implements java.io.Serializable {
@Id
@GeneratedValue
private int factureId;
@OneToOne (cascade = CascadeType.ALL)
private Client client;
假设您的数据库设置正确,那么当您在其中任何一个上调用save时,这应该是Hibernate正确保存对象所需的全部内容。
试试这个,如果你无法让它发挥作用,请告诉我。
答案 1 :(得分:1)
public class Main {
public static void main(String[] args) {
Client c = new Client();
c.setId(1);;
c.setNom("Zack");
Facture f = new Facture();
f.setNum_fact(1);
f.setC(c);
c.setF(f);
// Facture f = new Facture();
// f.setNum_fact(1);
// //c une étape importante
// c.setF(f);
//
// f.setC(c);
SessionFactory s = new AnnotationConfiguration().configure().buildSessionFactory();
Session ss = s.openSession();
ss.beginTransaction();
ss.save(c);
ss.save(f);
ss.getTransaction().commit();
ss.close();
s.close();
}
}
=============================================== ================================================
oct. 22, 2014 6:50:34 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: alter table Facture drop foreign key FK_rqdue6x5d4b9lg97rxve2fq20
oct. 22, 2014 6:50:34 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table Facture drop foreign key FK_rqdue6x5d4b9lg97rxve2fq20
oct. 22, 2014 6:50:34 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: Table 'mybase.facture' doesn't exist
Hibernate: drop table if exists Client
Hibernate: drop table if exists Facture
Hibernate: create table Client (id integer not null auto_increment, nom varchar(255), primary key (id))
Hibernate: create table Facture (num_fact integer not null auto_increment, client_id integer, primary key (num_fact))
Hibernate: alter table Facture add constraint FK_rqdue6x5d4b9lg97rxve2fq20 foreign key (client_id) references Client (id)
oct. 22, 2014 6:50:34 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Client (nom) values (?)
Hibernate: insert into Facture (client_id) values (?)
oct. 22, 2014 6:50:34 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost:3306/mybase]
谢谢你们的帮助,它有效:)