简体   繁体   English

如何使用 spring 数据 JPA 为现有父实体添加子实体?

[英]How to add child entity for existing parent entity using spring data JPA?

I am totally new to Spring data JPA and hibernate.What i am trying to is creating OneToOne to relation between two entity's shown below.我对 Spring 数据 JPA 和 hibernate 完全陌生。我正在尝试创建 OneToOne 以建立如下所示的两个实体之间的关系。

 @Entity
    public class Student {
    
        @Id
        @GeneratedValue
        private int id;
        private String name;
    
        @OneToOne
        @JoinColumn(name="id")
        private Passport passport;
    
        public Student() {
        }
    
    }

And Second:-其次:-

@Entity
public class Passport {

    @Id
    @GeneratedValue
    private  int id;
    private String number;

    public Passport() {
    }

    public Passport(int id, String number) {
        this.id = id;
        this.number = number;
    }
}

After running the program i inserted some dummy values to student and passport table and call the following function from CommandLineRunner to update specific student with passport.运行程序后,我将一些虚拟值插入到学生和护照表中,并从 CommandLineRunner 调用以下函数来更新特定学生的护照。

 public void SaveStudentPassword(int student_id, Passport passport){
        Student student = entityManager.find(Student.class,student_id);
        logger.info("Details of student  -> {}",student);
        student.setPassport(passport);
        entityManager.persist(student);
        entityManager.flush();
    }

Main Class implementing Command LineRunner:-实现 Command LineRunner 的主类:-

@SpringBootApplication
public class DemoApplication implements  CommandLineRunner{

    @Autowired
    private StudentRepository studentRepository;
    
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
 
        studentRepository.SaveStudentPassword(1,new Passport(6,"pass151020"));
    }
}

Bellow is Exception What i get:-波纹管是例外我得到的:-

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:798) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:779) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
    at com.example.demo.DemoApplication.main(DemoApplication.java:26) ~[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:564) ~[na:na]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.3.3.RELEASE.jar:2.3.3.RELEASE]
Caused by: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:298) ~[spring-orm-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255) ~[spring-orm-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528) ~[spring-orm-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) ~[spring-tx-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153) ~[spring-tx-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367) ~[spring-tx-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118) ~[spring-tx-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at com.example.demo.Repository.StudentRepository$$EnhancerBySpringCGLIB$$ef432965.SaveStudentPassword(<generated>) ~[classes/:na]
    at com.example.demo.DemoApplication.run(DemoApplication.java:36) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
    ... 10 common frames omitted
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3450) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3312) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3726) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:201) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:723) ~[na:na]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1363) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1350) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    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:564) ~[na:na]
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:314) ~[spring-orm-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at com.sun.proxy.$Proxy61.flush(Unknown Source) ~[na:na]
    at com.example.demo.Repository.StudentRepository.SaveStudentPassword(StudentRepository.java:27) ~[classes/:na]
    at com.example.demo.Repository.StudentRepository$$FastClassBySpringCGLIB$$f105aebb.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    ... 20 common frames omitted
Caused by: java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`testdb`.`student`, CONSTRAINT `FK6i2dofwfuu97njtfprqv68pib` FOREIGN KEY (`passport_id`) REFERENCES `passport` (`id`))
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1347) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.5.jar:na]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197) ~[hibernate-core-5.4.20.Final.jar:5.4.20.Final]
    ... 46 common frames omitted

Based on an error from log its looks like you need to join using passport_id根据日志中的错误,您似乎需要使用passport_id加入

Cannot add or update a child row: a foreign key constraint fails (`testdb`.`student`, CONSTRAINT `FK6i2dofwfuu97njtfprqv68pib` FOREIGN KEY (`passport_id`) REFERENCES `passport` (`id`))

I believe you need to join Student and Passport as shown belwo我相信你需要加入StudentPassport ,如图所示
@JoinColumn(name = "passport_id", referencedColumnName = "id", nullable = true)

Mapped in the entity as below在实体中映射如下

@Entity
public class Student {
    
        @Id
        @GeneratedValue
        private int id;
        private String name;
    
        @OneToOne
        @JoinColumn(name = "passport_id", referencedColumnName = "id", nullable = true)
        private Passport passport;
    
        public Student() {
        }    
}

暂无
暂无

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

相关问题 如何使用子实体检索父实体-Spring数据JPA - How to retrieve parent entity using child entity-Spring data JPA SpringMVC / JSTL / JPA集成:使用Spring MVC更新现有的子元素并将新的子元素添加到父实体 - SpringMVC/JSTL/JPA Integration: update existing child element and add new child element to a parent entity using Spring MVC 如何使用 Spring JPA DATA 仅获取特定的子实体及其具有特定值的父实体 - How to fetch only the specific child entity along with its Parent entities with specific value using Spring JPA DATA 在 JPA 中使用父实体获取子实体 - Fetch a child entity using parent entity in JPA 如何创建引用spring数据rest / HATEOAS中已存在的子实体的新父实体 - How to create a new parent entity that references an already existing child entity in spring data rest / HATEOAS 为父实体JPA-GAE分配现有的子实体 - Assign existing child entity for parent entity JPA- GAE 使用spring data jpa保存和更新实体父子的最佳方法 - Best way to save and update entity Parent and child using spring data jpa 如何从spring data jpa中的子主键获取父实体? - How to get the parent entity from the child primary key in spring data jpa? 如何在 Spring JPA/Hibernate 中使用 JoinTable 仅通过 ID 设置引用父实体的子实体 - How to set up a child entity referencing parent by only ID using a JoinTable in Spring JPA/Hibernate Spring JPA从新的子实体合并父实体 - Spring JPA merge parent entity from new child entity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM