Kotlin QueryDsl 4장 join

github 주소

너무나도 늦게…. 조인을…..하… 할거 많은데

샘플

서비스를 운영중인 사이트에서 이메일을 받기를 동의한 사람들의 리스트가 필요하다 가장하고 진행해보자

일단 QueryDsl은 명시적으로 database에 연관관계를 맺지 않고 Entity class에서도 맺지 않아도 쉽게 조인이 가능(어떤 버젼 부터인지는 모름) 하다

Tabel 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
CREATE TABLE `users` (
`seq` int(9) NOT NULL AUTO_INCREMENT,
`user_Id` varchar(45) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`name` varchar(20) NOT NULL,
`age` int(10) unsigned NOT NULL,
`email` varchar(100) NOT NULL,
`gender` varchar(1) NOT NULL,
`created_at` datetime DEFAULT CURRENT_TIMESTAMP,
`created_by` varchar(45) DEFAULT NULL,
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_by` varchar(45) DEFAULT NULL,
PRIMARY KEY (`seq`)
) ENGINE=InnoDB AUTO_INCREMENT=107 DEFAULT CHARSET=utf8


CREATE TABLE `user_terms` (
`seq` int(11) NOT NULL AUTO_INCREMENT,
`user_Id` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
`first_term` varchar(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'N',
`second_term` varchar(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'N',
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_by` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`seq`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

users의 user_id, user_terms의 user_id의 관계를 엮을 예정이다. 물론 제대로 database를 구성하려면 인덱스 설정과 저렇게 막 db를 짜면안되는 것은… 그냥 테스트이니 작동을 중요시!!

UserRepository 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15


override fun getUserEmailList(): MutableList<String>? {
val table = QUserEntity.userEntity
val termTable = QUserTermEntity.userTermEntity


return from(table)
.select(table.email)
.innerJoin(termTable).on(termTable.userId.eq(table.userId)
, termTable.firstTerm.eq('Y'))
.fetch()


}

위의 코드는 아래와 같이 작동한다

1
Hibernate: select userentity0_.email as col_0_0_ from users userentity0_ inner join user_terms usertermen1_ on (usertermen1_.user_id=userentity0_.user_id and usertermen1_.first_term=?)

짠 실행하면 이메일 리스트가 나온다.

left join, inner join등을 지원한다! 너무나도 쉬우니.. 예제는 패스…