Criteria criteria = sess.createCriteria(Zipcode.class); List<Zipcode> zipcodeList = crit.list(); |
select * from tbl_zipcode where seq = 1555
criteria.add(Restrictions.eq("seq", 1555));
select * from tbl_zipcode where seq = 45
criteria.add(Restrictions.idEq(45)); // idEq() 를 사용하면 PK 칼럼으로 검색합니다.
select * from tbl_zipcode where dong like '방화%'
criteria.add(Restrictions.like("dong", "방화", MatchMode.START)); // '방화%'
MatchMode 종류는 ANYWHERE, END, EXACT, START 4가지 종류가 있습니다.
딱 보면 아시겠지만 '%방화%', '방화%', '방화', '%방화' 이렇게 됩니다.
select * from tbl_zipcode where sido = '서울' and zipcode like '157%'
Map<String, String> map = new Hashtable<String, String>();
map.put("sido", "서울");
map.put("dong", "방화2동");
map.put("stBunji", "514");
criteria.add(Restrictions.allEq(map));
여러개의 eq를 사용할 경우 Map 을 사용할 수 있습니다.
주의 해야 할 것은 2번째 인자는 Object 형태라는 것입니다.
ge(>=), gt(>), le(<=), lt(<) 가 있습니다.
select * from tbl_zipcode where sido in ('서울', '부산')
String[] in = {"서울", "부산"};
criteria.add(Restrictions.in("sido", in)); // Collection 또는 Object[] 사용 가능
select * from tbl_zipcode where ( sido = '서울' and zipcode like '157%' )
criteria.add(
Restrictions.conjunction() // and 연산으로 그룹
.add( Restrictions.eq("sido", "서울") )
.add( Restrictions.like("zipcode", "157", MatchMode.START) )
);
and 조건을 여러개 사용할 경우 그냥 계속 .add() 해도 되지만 Restrictions.conjunction() 로 그룹할 수 있습니다.
Restrictions.conjunction() 은 and 로 그룹하고, Restrictions.disjunction() 은 or 로 그룹합니다.
select * from tbl_zipcode where ( (dong like '방화%' or dong like '%1동') and (zipcode like '157%' or zipcode like '431') )
crit.add(
Restrictions.conjunction()
.add(
Restrictions.disjunction()
.add(Restrictions.like("dong", "방화", MatchMode.START))
.add(Restrictions.like("dong", "1동", MatchMode.END))
)
.add(
Restrictions.disjunction()
.add(Restrictions.like("zipcode", "157", MatchMode.START))
.add(Restrictions.like("zipcode", "431", MatchMode.START))
)
);
- 동이 '방화'로 시작하거나 '1동'으로 끝나고 우편번호가 157로 시작하거나 431로 시작하는 데이터를 조회 합니다.
- (동이 '방화'로 시작 or 동이 '1동'으로 끝) and (우편번호가 '157'로 시작 or 우편번호가 '431'로 시작)
select * from tbl_zipcode where st_bunji between '157' and '158'
criteria.add(Restrictions.between("stBunji", "157", "158"));
select * from tbl_zipcode where ( dong like '방%' and dong like '%1동' )
criteria.add( Restrictions.and( Restrictions.eq("sido", "서울"), Restrictions.like("dong", "1동", MatchMode.END) ) );
Restrictions.and(조건, 조건) 은 두개의 조건을 and 로 그룹합니다.
Restrictions.or(조건, 조건) 은 두개의 조건을 or 로 그룹합니다.
select * from tbl_zipcode where not ( sido in ('서울', '부산') )
criteria.add( Restrictions.not( Restrictions.in("sido", new String[] { "서울", "부산" }) ) );