gpt4 book ai didi

java - hibernate 中的异常(一对一)

转载 作者:行者123 更新时间:2023-11-30 08:19:55 27 4
gpt4 key购买 nike

我正在学习基本的 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

最佳答案

在我看来,您可能对 Hibernate 实际如何设置这些关系感到有些困惑。我认为你的异常是由你说你的 clientId 引起的列/字段是映射到 Facture 的生成值表,当您实际上希望它引用 clientIdClient 上的列/字段表作为外键。所以你试图保存你的 Facture对象,导致 Facture.clientId要生成的列(因为您用 @GenericGenerator 对其进行了注释)。因为设置了这个值,Hibernate 尝试更新现有的 Client具有生成的 ID 的对象。因为它实际上并不存在,所以您会得到您发布的异常。

您尝试做的实际上是允许 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 正确保存对象所需的全部内容。

试试这个,如果你不能让它工作,请告诉我。

关于java - hibernate 中的异常(一对一),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26457891/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com