인프런 커뮤니티 질문&답변

dev_prao님의 프로필 이미지
dev_prao

작성한 질문수

자바 ORM 표준 JPA 프로그래밍 - 기본편

즉시 로딩과 지연 로딩

즉시 로딩과 지연 로딩 강의 2:30 NullPointerException 관련

해결된 질문

작성

·

496

0

[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예)2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예)3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예)[질문 내용]

 

package hellojpa;

import javax.persistence.*;

public class JpaMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");

        EntityManager em = emf.createEntityManager();

        EntityTransaction tx = em.getTransaction();
        tx.begin();

        try {

            Team team = new Team();
            team.setName("teamA");
            em.persist(team);

            Member member1 = new Member();
            member1.setUsername("member1");
            member1.setTeam(team);
            em.persist(member1);

            em.flush();
            em.clear();

            Member m = em.find(Member.class, member1.getId());

            System.out.println("m = " + m.getTeam().getClass());

            tx.commit();
        } catch (Exception e) {
            tx.rollback();
            e.printStackTrace();
        } finally {
            em.close();
        }
        emf.close();
    }
}

위와 같이 강사님의 코드를 그대로 받아쓰고 실행을 하였습니다.

 

java.lang.NullPointerException
	at hellojpa.JpaMain.main(JpaMain.java:30)
Jun 23, 2023 10:53:10 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:h2:tcp://localhost/~/test]

위와 같은 에러가 발생하였습니다. team 객체를 생성하였는데 왜 NullPointerException 에러가 발생한 것일까요? 답변주시면 감사하겠습니다!!

답변 1

0

안녕하세요. dev_prao님, 공식 서포터즈 David입니다.

혹시 질문에 올려주신 로그가 오류의 전부인걸까요??

오류 로그 전문을 올려주시면 답변에 큰 도움이 됩니다.

감사합니다.


dev_prao님의 프로필 이미지
dev_prao
질문자

Jun 25, 2023 5:56:53 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
	name: hello
	...]
Jun 25, 2023 5:56:53 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.3.10.Final}
Jun 25, 2023 5:56:53 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 25, 2023 5:56:53 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
Jun 25, 2023 5:56:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jun 25, 2023 5:56:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.h2.Driver] at URL [jdbc:h2:tcp://localhost/~/test]
Jun 25, 2023 5:56:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=sa}
Jun 25, 2023 5:56:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jun 25, 2023 5:56:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jun 25, 2023 5:56:54 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate: 
    
    drop table Album if exists
Hibernate: 
    
    drop table Book if exists
Hibernate: 
    
    drop table Member if exists
Hibernate: 
    
    drop table MemberProduct if exists
Hibernate: 
    
    drop table Movie if exists
Hibernate: 
    
    drop table Product if exists
Hibernate: 
    
    drop table Team if exists
Hibernate: 
    
    drop sequence if exists hibernate_sequence
Jun 25, 2023 5:56:54 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@36c54a56] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: 
    
    create table Album (
       id bigint not null,
        name varchar(255),
        price integer not null,
        artist varchar(255),
        primary key (id)
    )
Hibernate: 
    
    create table Book (
       id bigint not null,
        name varchar(255),
        price integer not null,
        author varchar(255),
        isbn varchar(255),
        primary key (id)
    )
Hibernate: 
    
    create table Member (
       MEMBER_ID bigint not null,
        INSERT_MEMBER varchar(255),
        createdDate timestamp,
        UPDATE_MEMBER varchar(255),
        lastModifiedDate timestamp,
        USERNAME varchar(255),
        TEAM_ID bigint,
        primary key (MEMBER_ID)
    )
Hibernate: 
    
    create table MemberProduct (
       id bigint not null,
        count integer not null,
        orderDateTime timestamp,
        price integer not null,
        MEMBER_ID bigint,
        PRODUCT_ID bigint,
        primary key (id)
    )
Hibernate: 
    
    create table Movie (
       id bigint not null,
        name varchar(255),
        price integer not null,
        actor varchar(255),
        director varchar(255),
        primary key (id)
    )
Hibernate: 
    
    create table Product (
       id bigint not null,
        name varchar(255),
        primary key (id)
    )
Jun 25, 2023 5:56:54 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@68ace111] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: 
    
    create table Team (
       TEAM_ID bigint not null,
        INSERT_MEMBER varchar(255),
        createdDate timestamp,
        UPDATE_MEMBER varchar(255),
        lastModifiedDate timestamp,
        name varchar(255),
        primary key (TEAM_ID)
    )
Hibernate: 
    
    alter table Member 
       add constraint FKl7wsny760hjy6x19kqnduasbm 
       foreign key (TEAM_ID) 
       references Team
Hibernate: 
    
    alter table MemberProduct 
       add constraint FKjnj8ungt7v35y6lfxuxcrjbbr 
       foreign key (MEMBER_ID) 
       references Member
Hibernate: 
    
    alter table MemberProduct 
       add constraint FKrgt6jorh7iaec1tae84ljye8c 
       foreign key (PRODUCT_ID) 
       references Product
Jun 25, 2023 5:56:54 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@4fbb001b'
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    /* insert hellojpa.Team
        */ insert 
        into
            Team
            (INSERT_MEMBER, createdDate, UPDATE_MEMBER, lastModifiedDate, name, TEAM_ID) 
        values
            (?, ?, ?, ?, ?, ?)
Hibernate: 
    /* insert hellojpa.Member
        */ insert 
        into
            Member
            (INSERT_MEMBER, createdDate, UPDATE_MEMBER, lastModifiedDate, USERNAME, MEMBER_ID) 
        values
            (?, ?, ?, ?, ?, ?)
Hibernate: 
    select
        member0_.MEMBER_ID as MEMBER_I1_3_0_,
        member0_.INSERT_MEMBER as INSERT_M2_3_0_,
        member0_.createdDate as createdD3_3_0_,
        member0_.UPDATE_MEMBER as UPDATE_M4_3_0_,
        member0_.lastModifiedDate as lastModi5_3_0_,
        member0_.TEAM_ID as TEAM_ID7_3_0_,
        member0_.USERNAME as USERNAME6_3_0_ 
    from
        Member member0_ 
    where
        member0_.MEMBER_ID=?
java.lang.NullPointerException
	at hellojpa.JpaMain.main(JpaMain.java:30)
Jun 25, 2023 5:56:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:h2:tcp://localhost/~/test]

Process finished with exit code 0

실행 시 나오는 코드 전문입니다!

오류 전문 감사합니다.

아무래도 실행 가능한 코드로 돌려보고 확인해 보아야 할 것 같습니다:)

아래 가이드를 참고하셔서 프로젝트 공유 부탁드립니다.

 


실제 동작하는 전체 프로젝트를 압축해서 구글 드라이브로 공유해서 링크를 남겨주세요.

구글 드라이브 업로드 방법은 다음을 참고해주세요.

https://bit.ly/3fX6ygx

주의: 업로드시 링크에 있는 권한 문제 꼭 확인해주세요

dev_prao님의 프로필 이미지
dev_prao
질문자

답변 감사합니다 David님. 주말간에 계속 코드를 뜯어보다가 member 클래스의 team team 객체를 생성하고 어노테이션으로 JoinColumn 조건에 nullable과 updatable을 false로 설정해둔 것이 문제였던 것으로 확인했습니다. 감사합니다:)

dev_prao님의 프로필 이미지
dev_prao

작성한 질문수

질문하기