Satu-satunya kesalahan yang disebutkan adalah bahwa ada kesalahan saat memulai ApplicationContext.

Berikut kode dan output yang relevan:

TodoListApplication.java

    package com.foobar.TodoList;

    import java.util.ArrayList;
    import java.util.List;

    import com.foobar.TodoList.model.User;
    import com.foobar.TodoList.model.User.TodoItem;
    import com.foobar.TodoList.repository.UserRepository;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;

    @SpringBootApplication
    public class TodoListApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(TodoListApplication.class, args);
    }

    @Autowired
    private UserRepository userRepository;
    
    @Override
    public void run(String... args) throws Exception {
        List<TodoItem> todoItems = new ArrayList<TodoItem>();
        todoItems.add(new TodoItem("mow the lawn", false));

        this.userRepository.save(new User("Joe", "password", todoItems));
    }
}

Pengguna.java

package com.isanoui.TodoList.model;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "name")
    private String name;
    
    @Column(name = "password")
    private String password;
    
    // @Column(name = "todos")
    @OneToMany
    @JoinColumn(name = "user_id")
    private List<TodoItem> todos = new ArrayList<TodoItem>();

    @Entity
    @Table(name = "todo_item")
    public static class TodoItem {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        protected long id;

        @Column(name = "todo")
        protected String todo;

        @Column(name = "completed")
        protected boolean completed;

        public TodoItem() {}

        public TodoItem(String todo, boolean completed) {
            // super();
            this.todo = todo;
            this.completed = completed;
        }

        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public String getTodo() {
            return todo;
        }

        public void setTodo(String todo) {
            this.todo = todo;
        }

        public boolean isCompleted() {
            return completed;
        }

        public void setCompleted(boolean completed) {
            this.completed = completed;
        }
    }

    public User() {}

    public User(String name, String password, List<TodoItem> todos) {
        super();
        this.name = name;
        this.password = password;
        this.todos = todos;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<TodoItem> getTodos() {
        return todos;
    }

    public void setTodos(TodoItem todoItem) {
        this.todos.add(todoItem);
    }
}

Log Konsol

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.1)

2021-01-15 03:16:36.526  INFO 17160 --- [           main] c.isanoui.TodoList.TodoListApplication   : Starting TodoListApplication using Java 15.0.1 on Isa with PID 17160 (C:\Users\Aissa\Downloads\TodoList\target\classes started by Aissa in c:\Users\Aissa\Downloads\TodoList)
2021-01-15 03:16:36.528  INFO 17160 --- [           main] c.isanoui.TodoList.TodoListApplication   : No active profile set, falling back to default profiles: default
2021-01-15 03:16:37.071  INFO 17160 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-01-15 03:16:37.123  INFO 17160 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 45 ms. Found 1 JPA repository interfaces.
2021-01-15 03:16:37.625  INFO 17160 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-01-15 03:16:37.635  INFO 17160 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-01-15 03:16:37.635  INFO 17160 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.41]
2021-01-15 03:16:37.759  INFO 17160 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-01-15 03:16:37.759  INFO 17160 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1194 ms
2021-01-15 03:16:37.911  INFO 17160 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2021-01-15 03:16:38.069  INFO 17160 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2021-01-15 03:16:38.120  INFO 17160 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-01-15 03:16:38.175  INFO 17160 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.25.Final
2021-01-15 03:16:38.312  INFO 17160 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-01-15 03:16:38.436  INFO 17160 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2021-01-15 03:16:39.019  INFO 17160 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-01-15 03:16:39.025  INFO 17160 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-01-15 03:16:39.319  WARN 17160 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2021-01-15 03:16:39.435  INFO 17160 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2021-01-15 03:16:39.608  WARN 17160 --- [           main] ion$DefaultTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2021-01-15 03:16:39.722  INFO 17160 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-01-15 03:16:39.733  INFO 17160 --- [           main] c.isanoui.TodoList.TodoListApplication   : Started TodoListApplication in 3.472 seconds (JVM running for 4.008)
2021-01-15 03:16:39.807  INFO 17160 --- [           main] o.h.e.j.b.internal.AbstractBatchImpl     : HHH000010: On release of batch it still contained JDBC statements
2021-01-15 03:16:39.813  INFO 17160 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-01-15 03:16:39.831 ERROR 17160 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:807) ~[spring-boot-2.4.1.jar:2.4.1]
 SpringApplication.java
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:788) ~[spring-boot-2.4.1.jar:2.4.1]
 SpringApplication.java
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:333) ~[spring-boot-2.4.1.jar:2.4.1]
 SpringApplication.java
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1309) ~[spring-boot-2.4.1.jar:2.4.1]
 SpringApplication.java
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1298) ~[spring-boot-2.4.1.jar:2.4.1]
 SpringApplication.java
    at com.isanoui.TodoList.TodoListApplication.main(TodoListApplication.java:19) ~[classes/:na]
 TodoListApplication.java
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.isanoui.TodoList.model.User$TodoItem; nested exception is java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.isanoui.TodoList.model.User$TodoItem
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:371) ~[spring-orm-5.3.2.jar:5.3.2]
 EntityManagerFactoryUtils.java
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:235) ~[spring-orm-5.3.2.jar:5.3.2]
 HibernateJpaDialect.java
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:566) ~[spring-orm-5.3.2.jar:5.3.2]
 JpaTransactionManager.java
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743) ~[spring-tx-5.3.2.jar:5.3.2]
 AbstractPlatformTransactionManager.java
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) ~[spring-tx-5.3.2.jar:5.3.2]
 AbstractPlatformTransactionManager.java
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:654) ~[spring-tx-5.3.2.jar:5.3.2]
 TransactionAspectSupport.java
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:407) ~[spring-tx-5.3.2.jar:5.3.2]
 TransactionAspectSupport.java
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.2.jar:5.3.2]
 TransactionInterceptor.java
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
 ReflectiveMethodInvocation.java
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.2.jar:5.3.2]
 PersistenceExceptionTranslationInterceptor.java
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
 ReflectiveMethodInvocation.java
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174) ~[spring-data-jpa-2.4.2.jar:2.4.2]
 CrudMethodMetadataPostProcessor.java
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
 ReflectiveMethodInvocation.java
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.2.jar:5.3.2]
 ExposeInvocationInterceptor.java
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
 ReflectiveMethodInvocation.java
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.2.jar:5.3.2]
 JdkDynamicAopProxy.java
    at com.sun.proxy.$Proxy76.save(Unknown Source) ~[na:na]
    at com.isanoui.TodoList.TodoListApplication.run(TodoListApplication.java:30) ~[classes/:na]
 TodoListApplication.java
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:804) ~[spring-boot-2.4.1.jar:2.4.1]
 SpringApplication.java
    ... 5 common frames omitted
Caused by: java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.isanoui.TodoList.model.User$TodoItem
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:151) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 ExceptionConverterImpl.java
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 ExceptionConverterImpl.java
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 ExceptionConverterImpl.java
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1366) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 SessionImpl.java
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:453) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 SessionImpl.java
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3212) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 SessionImpl.java
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2380) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 SessionImpl.java
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 JdbcCoordinatorImpl.java
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 JdbcResourceLocalTransactionCoordinatorImpl.java
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 JdbcResourceLocalTransactionCoordinatorImpl.java
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 JdbcResourceLocalTransactionCoordinatorImpl.java
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 TransactionImpl.java
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:562) ~[spring-orm-5.3.2.jar:5.3.2]
 JpaTransactionManager.java
    ... 21 common frames omitted
Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.isanoui.TodoList.model.User$TodoItem
    at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:347) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 ForeignKeys.java
    at org.hibernate.type.EntityType.getIdentifier(EntityType.java:507) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 EntityType.java
    at org.hibernate.type.EntityType.nullSafeSet(EntityType.java:280) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 EntityType.java
    at org.hibernate.persister.collection.AbstractCollectionPersister.writeElement(AbstractCollectionPersister.java:930) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 AbstractCollectionPersister.java
    at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1352) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 AbstractCollectionPersister.java
    at org.hibernate.persister.collection.OneToManyPersister.recreate(OneToManyPersister.java:187) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 OneToManyPersister.java
    at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:52) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 CollectionRecreateAction.java
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 ActionQueue.java
    at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 ActionQueue.java
    at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:723) ~[na:na]
 LinkedHashMap.java
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 ActionQueue.java
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 DefaultFlushEventListener.java
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 EventListenerGroupImpl.java
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1362) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 SessionImpl.java
    ... 30 common frames omitted

2021-01-15 03:16:39.862  INFO 17160 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2021-01-15 03:16:39.863  INFO 17160 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-01-15 03:16:39.863  INFO 17160 --- [           main] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2021-01-15 03:16:39.870  INFO 17160 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2021-01-15 03:16:39.872  INFO 17160 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Catatan: versi Java dalam file pom mengatakan 11, tetapi saya memiliki jdk 15, jangan berpikir itu penting

Catatan 2: Saya melakukan debug=true di application.properties tetapi tidak benar-benar memulainya, hanya keluaran yang lebih detail

0
Jakkie Chan 15 Januari 2021, 14:56

3 jawaban

Jawaban Terbaik

Masalahnya adalah sebagai berikut

Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.isanoui.TodoList.model.User$TodoItem
    at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:347) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
 ForeignKeys.java

Anda dapat membuat kaskade OneToMany atau ManyToOne untuk semua dengan

// @Column(name = "todos")
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private List<TodoItem> todos = new ArrayList<TodoItem>();

Atau Anda bisa seperti yang dijelaskan dalam komentar untuk menyimpan terlebih dahulu objek dalam dan kemudian luar.

public void run(String... args) throws Exception {

    TodoItem item = new TodoItem("mow the lawn", false);
    this.itemRepository.save(item); 

    List<TodoItem> todoItems = new ArrayList<TodoItem>();
    todoItems.add(item);
    this.userRepository.save(new User("Joe", "password", todoItems));
}
1
Boug 15 Januari 2021, 12:35

Ini mungkin disebabkan, karena Anda ingin menjalankan CommandLineRunner. Saya selalu menggunakannya dengan secara eksplisit menjalankan kacang CommandLineRunner. Dalam kasus Anda, itu saja:

@Bean
    public CommandLineRunner prepopulateDB(UserRepository userRepository) {
        return args -> {
    List<TodoItem> todoItems = new ArrayList<TodoItem>();
    todoItems.add(new TodoItem("mow the lawn", false));

    userRepository.save(new User("Joe", "password", todoItems));
        };
    }
0
Przemek 15 Januari 2021, 12:06

Kesalahan memberitahu:

 object references an unsaved transient instance - save the transient instance before flushing: com.isanoui.TodoList.model.User$TodoItem; nested exception is java.lang.IllegalStateException:

Saya kira Anda memiliki hubungan OneToMany antara Pengguna dan TodoItem bahwa hubungan di antara mereka tidak benar, Anda menghapus sesi dari hibernasi tetapi sebelum itu Anda dapat menyimpan entitas. (saya pikir Anda harus memperbaiki hubungan antara 2 entitas dan itu mungkin benar jika tidak, periksa kembali bagaimana objek terus bekerja)

0
Alireza Hakimrabet 15 Januari 2021, 12:20