休眠中的异常(一对一)
Posted
技术标签:
【中文标题】休眠中的异常(一对一)【英文标题】:Exception in hibernate (One To One) 【发布时间】:2014-12-14 23:27:32 【问题描述】:我正在学习基本的休眠教程。我正在尝试在 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
【问题讨论】:
在创建客户端后先尝试保存它。它正在尝试更新似乎不存在的客户记录。 @BrianHoover 是的,我保存了它,但它不起作用:( 如果您遇到困难,请查看我为 Hibernate 4 编写的 guide。它为您提供了各种关系类型所需的注释。我认为您的问题可能是因为您为一对一关系指定了@JoinColumn
,但我不是 100% 的。忽略有关 Spring 的部分,因为您只是使用普通的 Hibernate。
@JamesMassey 好的,我会看一下指南,然后再试一次,看看它是否有效。谢谢
查看此链接:***.com/questions/21124361/…
【参考方案1】:
在我看来,您可能对 Hibernate 实际如何建立这些关系感到有些困惑。我认为您的异常是由于您说您的clientId
列/字段是映射到Facture
表的生成值,而您实际上希望它引用clientId
Client
上的列/字段表作为外键。因此,您正在尝试保存 Facture
对象,这会导致生成 Facture.clientId
列(因为您使用 @GenericGenerator
对其进行了注释)。因为设置了这个值,Hibernate 尝试使用生成的 ID 更新现有的 Client
对象。因为它实际上并不存在,所以您会得到您发布的异常。
您尝试做的实际上是允许 Hibernate 在外键关系之间进行映射,以便您可以从 Facture
获取 Client
,反之亦然。
您不需要指定连接列,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 正确保存对象所需的全部内容。
试试这个,如果你不能让它工作,请告诉我。
【讨论】:
【参考方案2】: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]
谢谢你们的帮助,它有效:)
【讨论】:
以上是关于休眠中的异常(一对一)的主要内容,如果未能解决你的问题,请参考以下文章