Ricky Sixx
Ricky Sixx

Reputation: 653

Null values in foreign key columns when saving an entity with Spring JPA

In my database I have 2 entities in a unidirectional relationship, User and Message:

CREATE TABLE public."user" (
    uuid uuid NOT NULL DEFAULT uuid_generate_v4(),
    "name" varchar NULL,
    CONSTRAINT user_pk PRIMARY KEY (uuid)
);

CREATE TABLE public.message (
    sender uuid NOT NULL,
    receiver uuid NOT NULL,
    "content" varchar NULL,
    uuid uuid NOT NULL,
    CONSTRAINT message_pk PRIMARY KEY (uuid),
    CONSTRAINT message_fk FOREIGN KEY (sender) REFERENCES "user"(uuid) ON UPDATE RESTRICT ON DELETE RESTRICT,
    CONSTRAINT message_fk_1 FOREIGN KEY (receiver) REFERENCES "user"(uuid) ON UPDATE RESTRICT ON DELETE RESTRICT
);

This is how I mapped those entities with Spring JPA:

@Entity
@Table(name = "user", schema = "public")
public class User
{
    @Id
    @Column(name = "uuid", insertable = false, updatable = false)
    private UUID uuid;

    @Column(name = "name")
    private String name;
}

@Entity
@Table(name = "message", schema = "public")
public class Message
{
    @Id
    @Column(name = "uuid")
    private UUID uuid;

    @ManyToOne
    @JoinColumn(name = "uuid", insertable = false, updatable = false) // this uuid is in the User entity
    private User sender;

    @ManyToOne
    @JoinColumn(name = "uuid", insertable = false, updatable = false) // this uuid is in the User entity
    private User receiver;

    @Column(name = "content")
    private String content;
}

In my REST controller I expose an endpoint to create a message. This endpoint simply takes two users (the sender and the receiver) and a content for the message:

@PostMapping
@RequestMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CreateMessageResponseRO> createMessage(@RequestBody CreateMessageRequestRO request)
{
    Message message = new Message();
    User sender = userRepository.findById(UUID.fromString(request.getSender())).get();
    User receiver = userRepository.findById(UUID.fromString(request.getReceiver())).get();
    String content = request.getContent();

    message.setSender(sender); // sender is not null here
    message.setReceiver(receiver); // receiver is not null here
    message.setContent(content);

    messageRepository.save(message);

    return ResponseEntity.ok(new CreateMessageResponseRO(message));
}

I've checked with the debugger and at the line

messageRepository.save(message)

the two users (sender and receiver) are not null and they have a valid UUID (i.e. those UUIDs refer to 2 distinct, existing, users) However, when I invoke that endpoint I get this exception:

org.postgresql.util.PSQLException: ERROR: null value in column "sender" of relation "message" violates not-null constraint
  Detail: Failing row contains (null, null, hello world!, 818ea408-fa40-49f8-93a1-85e2ff026dac).

This is the JSON I'm using:

{
    "sender": "75090bb0-0e29-4cd8-84ab-2bf2727419d2",
    "receiver": "3539c23f-42f8-4074-a5f8-a8d3f0be8aeb",
    "content": "hello world!"
}

Why do I get that exception, when the userRepository correctly finds the 2 users?


EDIT 1

I've tried to remove the attributes insertable = false, updatable = false from the @JoinColumn annotations in the Message entity. This is the updated code:

@Entity
@Table(name = "message", schema = "public")
public class Message
{
    @Id
    @Column(name = "uuid")
    private UUID uuid;

    @ManyToOne
    @JoinColumn(name = "uuid")
    private User sender;

    @ManyToOne
    @JoinColumn(name = "uuid")
    private User receiver;

    @Column(name = "content")
    private String content;
}

However, now I get an exception during the startup of my application, which says that it requires the attributes I've removed:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: com.akwares.sccs.entity.Message column: uuid (should be mapped with insert="false" update="false")
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786) ~[spring-beans-5.3.5.jar!/:5.3.5]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602) ~[spring-beans-5.3.5.jar!/:5.3.5]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.5.jar!/:5.3.5]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.5.jar!/:5.3.5]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.5.jar!/:5.3.5]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.5.jar!/:5.3.5]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.5.jar!/:5.3.5]
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.5.jar!/:5.3.5]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.5.jar!/:5.3.5]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.5.jar!/:5.3.5]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144) ~[spring-boot-2.4.4.jar!/:2.4.4]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:769) ~[spring-boot-2.4.4.jar!/:2.4.4]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) ~[spring-boot-2.4.4.jar!/:2.4.4]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426) ~[spring-boot-2.4.4.jar!/:2.4.4]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) ~[spring-boot-2.4.4.jar!/:2.4.4]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1313) ~[spring-boot-2.4.4.jar!/:2.4.4]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302) ~[spring-boot-2.4.4.jar!/:2.4.4]
        at com.akwares.sccs.Application.main(Application.java:11) ~[classes!/:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) ~[server-1.0-SNAPSHOT.jar:na]
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:107) ~[server-1.0-SNAPSHOT.jar:na]
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) ~[server-1.0-SNAPSHOT.jar:na]
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88) ~[server-1.0-SNAPSHOT.jar:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: com.akwares.sccs.entity.Message column: uuid (should be mapped with insert="false" update="false")
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:421) ~[spring-orm-5.3.5.jar!/:5.3.5]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.5.jar!/:5.3.5]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.5.jar!/:5.3.5]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1845) ~[spring-beans-5.3.5.jar!/:5.3.5]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1782) ~[spring-beans-5.3.5.jar!/:5.3.5]
        ... 25 common frames omitted
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.akwares.sccs.entity.Message column: uuid (should be mapped with insert="false" update="false")
        at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:862) ~[hibernate-core-5.4.29.Final.jar!/:5.4.29.Final]
        at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:880) ~[hibernate-core-5.4.29.Final.jar!/:5.4.29.Final]
        at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:902) ~[hibernate-core-5.4.29.Final.jar!/:5.4.29.Final]
        at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:634) ~[hibernate-core-5.4.29.Final.jar!/:5.4.29.Final]
        at org.hibernate.mapping.RootClass.validate(RootClass.java:267) ~[hibernate-core-5.4.29.Final.jar!/:5.4.29.Final]
        at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:354) ~[hibernate-core-5.4.29.Final.jar!/:5.4.29.Final]
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:298) ~[hibernate-core-5.4.29.Final.jar!/:5.4.29.Final]
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:468) ~[hibernate-core-5.4.29.Final.jar!/:5.4.29.Final]
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1259) ~[hibernate-core-5.4.29.Final.jar!/:5.4.29.Final]
        at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.5.jar!/:5.3.5]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.5.jar!/:5.3.5]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.5.jar!/:5.3.5]
        ... 29 common frames omitted

Upvotes: 7

Views: 8902

Answers (3)

Ricardo Gonzalez
Ricardo Gonzalez

Reputation: 1

I had the same problem. The problem was in my flags configurations of @JoinColumn

I solved using insertable = true or remove element from annotantion (It will be use th default true value). See relations in database

This is for Usuarios

@Entity
@Table(name = "tw_usuario")
public class Usuario implements Serializable {
    @Id
    private Long id;
    //Other fields

    @ManyToOne
    @JoinColumn(name = "id_rol", insertable = true, updatable = false)
    // Above line is equals to @JoinColumn(name = "id_rol", updatable = false)
    private Rol rol;

    // Getters and Setters
}

Extra information about the other relation

@Entity
@Table(name = "tc_rol")
public class Rol implements Serializable {  
    @Id
    private Long id;
    
    //More  fields
    //Declare Getters and Setters
}

Upvotes: 0

Ahmed HENTETI
Ahmed HENTETI

Reputation: 1128

I think that you have a problem in your @JoinColumn names. For me, you should use different names and use referencedColumnName to reference foreign column name

@ManyToOne
@JoinColumn(name = "sender_uuid", 
            referencedColumnName = "uuid", // this uuid is in the User entity
            insertable = false, updatable = false) 
private User sender;

@ManyToOne
@JoinColumn(name = "receiver_uuid", 
            referencedColumnName = "uuid", // this uuid is in the User entity
            insertable = false, updatable = false) 
private User receiver;

Upvotes: 5

Hopey One
Hopey One

Reputation: 1816

Remove the insertable = false, updatable = false. This is telling JPA to leave this column out of the generated SQL statements.

Upvotes: 2

Related Questions