简体   繁体   English

使用 Spring JPA 保存实体时,外键列中的 Null 值

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

In my database I have 2 entities with a unidirectional relationship between them.在我的数据库中,我有 2 个实体,它们之间存在单向关系。

User:用户:

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

Message:信息:

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:这就是我使用 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.在我的 REST controller 中,我公开了一个端点以创建一条消息。 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 (ie those UUIDs refer to 2 distinct, existing, users) However, when I invoke that endpoint I get this exception:两个用户( senderreceiver )不是 null 并且它们具有有效的 UUID(即那些 UUID 指的是 2 个不同的现有用户)但是,当我调用该端点时,我得到了这个异常:

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:这是我正在使用的 JSON:

{
    "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?userRepository正确找到 2 个用户时,为什么会出现该异常?


EDIT 1编辑 1

I've tried to remove the attributes insertable = false, updatable = false from the @JoinColumn annotations in the Message entity.我试图从Message实体中的 @JoinColumn 注释中删除属性insertable = false, updatable = false @JoinColumn = false 。 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

I think that you have a problem in your @JoinColumn names.我认为您的@JoinColumn名称有问题。 For me, you should use different names and use referencedColumnName to reference foreign column name对我来说,您应该使用不同的名称并使用referencedColumnName来引用外国列名

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

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

Remove the insertable = false, updatable = false .删除insertable = false, updatable = false This is telling JPA to leave this column out of the generated SQL statements.这告诉 JPA 将此列排除在生成的 SQL 语句之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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