简体   繁体   中英

SQL Foreign Key Error using Hibernate POJOs

We have the following situation: We use Java's Hibernate to write POJO-Classes to a database. The classes are annotated as follow:

@Entity
@Table(name = "dbo.SaveEvents")

We get the following error when writing to the database (Table: dbo.CodeDocuments )

WARN: SQL Error: 547, SQLState: 23000
Feb 06, 2017 2:06:42 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_SaveEvents_CodeDocuments". The conflict occurred in database "OSBLEPlus_eclipse", table "dbo.CodeDocuments", column 'Id'.
org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:112)

We tried to satisfy the Foreign Key constraint by adding: @SecondaryTable(name = "dbo.CodeDocuments") But this doesn't solve our problem. We also didn't find a lot about how to use the SecondaryTable annotation properly. The mapping FK <-> PK is as follows:

CodeDocuments.sql:
CREATE TABLE [dbo].[CodeDocuments] (
    [Id]    INT         IDENTITY (1, 1) NOT NULL,
    [FileName] VARCHAR (MAX) NOT NULL,
    [Content]  VARCHAR (MAX) NOT NULL,
    CONSTRAINT [PK_CodeDocuments_Id] PRIMARY KEY CLUSTERED ([Id] ASC)
);

SaveEvents.sql:
CREATE TABLE [dbo].[SaveEvents] (
    [Id]        INT         IDENTITY (1, 1) NOT NULL,
    [EventLogId]   INT          NOT NULL,
    [EventDate] DATETIME    NOT NULL,
    [SolutionName] VARCHAR (MAX) NOT NULL,
    [DocumentId]   INT          NOT NULL,
    CONSTRAINT [PK_SaveEvents] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_SaveEvents_EventLogs] FOREIGN KEY ([EventLogId]) REFERENCES [dbo].[EventLogs] ([Id]),
    CONSTRAINT [FK_SaveEvents_CodeDocuments] FOREIGN KEY ([DocumentId]) REFERENCES [dbo].[CodeDocuments] ([Id])
);

How would one go about inserting into 2 tables at once using Hibernate POJOs aka fixing the foreign key error?

You simply need to make sure you persist your CodeDocument entity first folllowed by the associated SaveEvents entities:

CodeDocument codeDocument = new CodeDocument();
// set the values 
session.save( codeDocument );

SaveEvents saveEvents = new SaveEvents();
// set the values
saveEvents.setDocument( codeDocument );
session.save( saveEvents );

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM