在使用Spring JPA保存实体时删除外键列中的值

bgibtngc  于 12个月前  发布在  Spring
关注(0)|答案(3)|浏览(156)

在我的数据库中,我有两个实体,它们之间有单向关系。
使用者:

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
);


这就是我如何使用Spring JPAMap这些实体:

@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;
}


在我的REST控制器中,我暴露了一个端点来创建消息。这个端点只需要两个用户(发送者和接收者)和消息的内容:

@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));
}


我已经检查了调试器,

messageRepository.save(message)


两个用户(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).


下面是我使用的JSON:

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


userRepository正确地找到2个用户时,为什么我会得到这个异常?

编辑1

我尝试从Message实体的@JoinColumn注解中删除属性insertable = false, updatable = false。这是更新后的代码:

@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;
}


然而,现在我在启动应用程序时遇到了一个异常,它说它需要我删除的属性:

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

jaxagkaj

jaxagkaj1#

我认为你的@JoinColumn名称有问题。对我来说,你应该使用不同的名称,并使用referencedColumnName引用外来列名。

@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;

字符串

wvmv3b1j

wvmv3b1j2#

删除insertable = false, updatable = false。这是告诉JPA在生成的SQL语句中保留此列。

e5nqia27

e5nqia273#

我也遇到了同样的问题,问题出在@JoinColumn的标志配置上

*我使用insertable = trueremove element from annotation * 解决了(它将使用默认的true值)。See relations in database

这是给阿斯图里亚斯的

@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
}

字符串
关于其他关系的额外信息

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

相关问题