JPA 기본 설정 완성 후
소스 작업 전 테스트 소스를 먼저 만들어보자
Base도메인 설정
@MappedSuperclass
@EntityListeners(value = { AuditingEntityListener.class })
//spring jpa AuditingEntityListener 에서 가져옴
// 해당 클래스가 적용되면 엔티티가 데이터베이스에 추가 / 변경될 때 자동으로 시간 값을 저장
// AuditingEntityListener 활성화 하기 위해 프로젝트 설정에 @EnableJpaAuditing 추가 해야함
@Getter
public class BaseEntity {
@CreatedDate
@Column(name = "regdate", updatable = false)
private LocalDateTime regDate;
@LastModifiedDate
@Column(name = "moddate")
private LocalDateTime modDate;
}
repository 인터페이스 설정
// spring jpa data 이용할 때 JpaRepository 인터페이스를 이용해서
// 인터페이스 선언만으로 데이터 베이스 기본 작업 CRUD 와 페이징 처리가 가능하다.
public interface BoardRepository extends JpaRepository<Board, Long> {}
실제 사용 Board 도메인 설정
@Entity
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Board extends BaseEntity {
//BaseEntity 에서 전체 적용 되는 데이터베이스 값을 가져온다
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
// GenerationType.IDENTITY 데이터 베이스에 위임-auto_increment (mysql/maria)
private Long bno;
@Column(length = 500 , nullable = false) //컬럼 길이와 null 허용 여부
private String title;
@Column(length = 2000 , nullable = false)
private String content;
@Column(length = 50 , nullable = false)
private String writer;
}
인서트 테스트 코드 작성 후 RUN ~~~
@SpringBootTest
@Log4j2
public class BoardRepositoryTest {
@Autowired
private BoardRepository boardRepository;
@Test
public void testInsert(){
IntStream.rangeClosed(1,100).forEach( i ->{
Board board = Board.builder()
.title("제목 ... "+i)
.content("내용 ... "+ i)
.writer("user"+(i%10))
.build();
Board result = boardRepository.save(board);
log.info("BNO : " + result.getBno());
});
}
}
위 코드를 GPT가 분석해 줌
위의 자바 코드는 빌더 패턴을 이용하여 board 객체를 생성하는 코드입니다. 빌더 패턴은 복잡한 객체를 생성할 때, 객체의 생성과 표현을 분리하여 객체를 생성하는 디자인 패턴입니다. 이 코드에서는 빌더를 사용하여 제목, 내용 및 작성자가 있는 게시판 객체를 생성합니다. 빌더는 메소드 호출 체인으로 사용되고 있습니다. title() 메소드는 i 변수의 값과 문자열을 연결하여 게시판의 제목을 설정합니다. content() 메소드는 i 변수의 값과 문자열을 연결하여 게시판의 내용을 설정합니다. writer() 메소드는 i를 10으로 나눈 나머지와 문자열을 연결하여 게시판의 작성자를 설정합니다. 마지막으로 build() 메소드가 호출되어 빌더가 설정한 값으로 새로운 board 객체가 생성되고 반환됩니다. |
실제 스프링 띄우면서 JPA 테이블 생성하고 인서트 까지 이상없이 실행
Starting Gradle Daemon...
Gradle Daemon started in 1 s 5 ms
> Task :compileJava
> Task :processResources UP-TO-DATE
> Task :classes
> Task :compileTestJava
> Task :processTestResources NO-SOURCE
> Task :testClasses
> Task :test
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.0.5)
2023-04-22T17:35:45.154+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : Starting BoardRepositoryTest using Java 17.0.4 with PID 6100 (started by user in C:\Users\user\IdeaProjects\jisou)
2023-04-22T17:35:45.155+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : No active profile set, falling back to 1 default profile: "default"
2023-04-22T17:35:45.570+09:00 INFO 6100 --- [ Test worker] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2023-04-22T17:35:45.616+09:00 INFO 6100 --- [ Test worker] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 38 ms. Found 1 JPA repository interfaces.
2023-04-22T17:35:45.925+09:00 INFO 6100 --- [ Test worker] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2023-04-22T17:35:45.976+09:00 INFO 6100 --- [ Test worker] org.hibernate.Version : HHH000412: Hibernate ORM core version 6.1.7.Final
2023-04-22T17:35:46.227+09:00 INFO 6100 --- [ Test worker] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2023-04-22T17:35:46.373+09:00 INFO 6100 --- [ Test worker] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@18b40fe6
2023-04-22T17:35:46.375+09:00 INFO 6100 --- [ Test worker] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2023-04-22T17:35:46.427+09:00 INFO 6100 --- [ Test worker] SQL dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Hibernate:
create table board (
bno bigint not null auto_increment,
moddate datetime(6),
regdate datetime(6),
content varchar(2000) not null,
title varchar(500) not null,
writer varchar(50) not null,
primary key (bno)
) engine=InnoDB
2023-04-22T17:35:47.117+09:00 INFO 6100 --- [ Test worker] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2023-04-22T17:35:47.126+09:00 INFO 6100 --- [ Test worker] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2023-04-22T17:35:47.217+09:00 WARN 6100 --- [ Test worker] 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
2023-04-22T17:35:47.663+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : Started BoardRepositoryTest in 2.684 seconds (process running for 3.944)
Hibernate:
insert
into
board
(content, moddate, regdate, title, writer)
values
(?, ?, ?, ?, ?)
2023-04-22T17:35:47.872+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : BNO : 1
Hibernate:
insert
into
board
(content, moddate, regdate, title, writer)
values
(?, ?, ?, ?, ?)
2023-04-22T17:35:47.891+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : BNO : 2
Hibernate:
insert
into
board
(content, moddate, regdate, title, writer)
values
(?, ?, ?, ?, ?)
2023-04-22T17:35:47.907+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : BNO : 3
Hibernate:
insert
into
board
(content, moddate, regdate, title, writer)
values
(?, ?, ?, ?, ?)
2023-04-22T17:35:47.925+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : BNO : 4
Hibernate:
insert
into
board
(content, moddate, regdate, title, writer)
values
(?, ?, ?, ?, ?)
2023-04-22T17:35:47.942+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : BNO : 5
Hibernate:
insert
into
board
(content, moddate, regdate, title, writer)
values
(?, ?, ?, ?, ?)
2023-04-22T17:35:47.959+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : BNO : 6
Hibernate:
insert
into
board
(content, moddate, regdate, title, writer)
values
(?, ?, ?, ?, ?)
2023-04-22T17:35:47.974+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : BNO : 7
Hibernate:
insert
into
board
(content, moddate, regdate, title, writer)
values
(?, ?, ?, ?, ?)
2023-04-22T17:35:47.989+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : BNO : 8
Hibernate:
insert
into
board
(content, moddate, regdate, title, writer)
values
(?, ?, ?, ?, ?)
2023-04-22T17:35:48.014+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : BNO : 9
Hibernate:
insert
into
board
(content, moddate, regdate, title, writer)
values
(?, ?, ?, ?, ?)
2023-04-22T17:35:48.030+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : BNO : 10
Hibernate:
insert
into
board
(content, moddate, regdate, title, writer)
values
(?, ?, ?, ?, ?)
2023-04-22T17:35:48.047+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : BNO : 11
Hibernate:
insert
into
board
(content, moddate, regdate, title, writer)
values
(?, ?, ?, ?, ?)
2023-04-22T17:35:48.060+09:00 INFO 6100 --- [ Test worker] o.d.j.repository.BoardRepositoryTest : BNO : 12
Hibernate:
insert
into
board
(content, moddate, regdate, title, writer)
values
(?, ?, ?, ?, ?)
반응형
':::: 개발 :::: > └ JSP & SPRING' 카테고리의 다른 글
인텔리제이 could not find mysql:mysql-connector-java (7) | 2023.04.19 |
---|---|
스프링 부트 http 컨트롤 spring boot http status / header controll (0) | 2023.01.23 |
JPA Specification ( 조회 조건 조합 다이나믹 쿼리) (0) | 2022.07.28 |
@PostConstruct 어노테이션 (0) | 2020.11.13 |
spring boot 로딩된 bean 목록 출력 소스... (0) | 2020.11.13 |
spring boot rest api 애러 처리 (0) | 2020.11.09 |
@ResponseBody response 처리 혹은 예외 처리 (0) | 2020.11.05 |
spring @RequestBody Map<String, Object> Json 핸들링 (0) | 2020.10.30 |