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

작성자 없음

작성자 정보가 삭제된 글입니다.

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

기본 키 매핑

H2 database GenerationType.IDENTITY 오류 질문입니다.

작성

·

5.6K

2

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

[질문 내용]
여기에 질문 내용을 남겨주세요.
 
<dependencies>
<!-- H2 데이터베이스-->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.0.202</version>
</dependency>
<!-- JPA 하이버네이트-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.6.1.Final</version>
</dependency>
</dependencies>

@Entity
public class Member {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
}
public class EntityMapping {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();

tx.begin();
try{
Member member = new Member();;
member.setUsername("AAA");
em.persist(member);

tx.commit();

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

실행하면 콘솔에서

Hibernate: drop table if exists Member CASCADE Hibernate: create table Member ( id bigint generated by default as identity, name varchar(255) not null, primary key (id) )

와 같이 테이블이 생성되고

Hibernate: 

    /* insert hellojpa.Member

        */ insert 

        into

            Member

            (id, name) 

        values

 

          (null, ?)

insert 쿼리는 위와 같이 데이터베이스로 호출하는것이 보입니다.

 

[오류로그]

12월 23, 2021 10:44:53 오후 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions

ERROR: NULL not allowed for column "ID"; SQL statement:

/* insert hellojpa.Member */ insert into Member (id, name) values (null, ?) [23502-202]

javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement

at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)

at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)

at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)

at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:780)

at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:760)

at hellojpa.EntityMapping.main(EntityMapping.java:18)

Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement

at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)

at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:37)

at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)

at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)

at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200)

at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)

at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:43)

at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3279)

at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3885)

at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:84)

at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645)

at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282)

at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)

at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317)

at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:330)

at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287)

at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)

at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:123)

at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:185)

at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128)

at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55)

at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)

at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:774)

... 2 more

Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column "ID"; SQL statement:

 

/* insert hellojpa.Member */ insert into Member (id, name) values (null, ?) [23502-202]

null이 들어 갈수 없다고 나오는데 강의중에는 어떻게 오류가 안나고 되는지 궁금합니다.

 

 

답변 3

4

H2 2.1.210 버전에서 ;MODE=MySQL 추가하면 잘 됩니다.

spring.datasource.url=jdbc:h2:tcp://localhost/~/test;MODE=MySQL

또는 
Member.java의
@GeneratedValue(strategy = GenerationType.IDENTITY)
-> @GeneratedValue(strategy = GenerationType.SEQUENCE)
 수정하면 됩니다.

4

혹시 1.4.200으로 변경했는데도 안되시는 분들은

<property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/~/test;MODE=LEGACY"/>

맨 뒤에   ;MODE=LEGACY   붙여서 한번 시도해보세요!!

3

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

.
H2 1.4.200 버전을 사용해주세요.

h2 신버전에서 발생하는 오류입니다.
.
감사합니다.

방금 github에서 이슈 확인해서 글 지울려고 보니 댓글을 이미 달아주셨네요. 빠른 답변 감사합니다~

작성자 없음

작성자 정보가 삭제된 글입니다.

질문하기