Spring

ApplicationContext를 언급하는 Spring Boot 애플리케이션이 즉시 종료됩니다.

기록만이살길 2021. 3. 8. 09:07
반응형

ApplicationContext를 언급하는 Spring Boot 애플리케이션이 즉시 종료됩니다.

1. 질문(문제점):

언급 한 유일한 오류는 ApplicationContext를 시작하는 동안 오류가 발생했다는 것입니다.

다음은 관련 코드 및 출력입니다.

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

User.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);
    }
}

콘솔 로그

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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.

참고 : pom 파일의 Java 버전은 11이라고 말하지만 jdk 15가 있지만 중요하다고 생각하지 않습니다.

주 2 : 내가 한 debug=trueapplication.properties실제로 그것을 시작되지 않습니다, 단지 더 자세한 출력

2. 해결방안:

문제는 다음과 같습니다.

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

OneToMany 또는 ManyToOne을 모두에게 계단식으로 만들 수 있습니다.

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

또는 어노테이션에 설명 된대로 먼저 내부 개체를 저장 한 다음 외부 개체를 저장할 수 있습니다.

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));
}
65735671
반응형