JooqTemplate으로 레코드 삽입
Source: Dev.to
JooqTemplate은 JOOQ을 감싸는 래퍼로, 간결한 CRUD 메서드를 제공합니다. 주요 특징:
- 테이블을 문자열 이름으로 바로 조작 — 코드 생성이 필요 없음
- 조건을 전달하는 세 가지 방법: Condition / List / varargs
conditions()를 통해 필드명에 연산자를 삽입 — 한 줄에 여러 조건을 결합- 내장된 Java Bean ↔ Map 변환, camelCase ↔ snake_case 상호 변환 및 기타 유틸리티 제공
1. SETUP
프로젝트에 net.sf.sprtool:sprtool-jooq:1.1.0 의존성을 추가합니다.
Maven
<dependency>
<groupId>net.sf.sprtool</groupId>
<artifactId>sprtool-jooq</artifactId>
<version>1.1.0</version>
</dependency>
Gradle
// Groovy DSL
implementation 'net.sf.sprtool:sprtool-jooq:1.1.0'
// Kotlin DSL
implementation("net.sf.sprtool:sprtool-jooq:1.1.0")
Java
@Autowired
JooqTemplate jt;
2. INSERT
단일 레코드를 데이터베이스 테이블에 삽입합니다.
public int insert(String table, Map map)
public int insert(Table table, Map map)
- table: 테이블 이름, 예)
"user_table"혹은T("user_table") - map: 컬럼‑값 맵; 키는 컬럼명, 값은 삽입할 값
- 반환값:
int— 영향을 받은 행 수
예시
Map user = new HashMap();
user.put("name", "John");
user.put("birthday", LocalDate.now());
user.put("create_time", LocalDateTime.now());
jt.insert("user_table", user);
3. insertReturningv
레코드를 삽입하고 지정한 필드들의 값을 반환합니다 (주로 자동 생성된 ID를 얻을 때 사용).
public Record insertReturningv(String table, Map map, Object... fields)
public Record insertReturningv(Table table, Map map, Object... fields)
- 반환값:
Record— 반환된 필드 값을 담고 있는 JOOQ 레코드.get("id", Integer.class)와 같이 값을 추출할 수 있습니다.
예시
Map values = JooqMaps.toSnakeCaseWithNull(user);
values.remove("id");
values.put("create_time", LocalDateTime.now());
Record r = jt.insertReturningv("user_table", values, "id");
int newId = r.get("id", Integer.class);
4. Batch insert
여러 레코드를 한 번에 배치 삽입합니다.
public int insert(String table, List bean)
public int insert(Table table, List bean)
예시
List batch = new ArrayList();
for(int i = 0; i < 10; i++) {
Map user = new HashMap();
user.put("name", "User" + i);
batch.add(user);
}
jt.insert("user_table", batch); 