m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

doma2のsql文調査

SQL文の複合条件とか気になるので調べる

SELECT、INSERT、UPDATEらへんの挙動

SELECT

基本的にはSQLを作らなければならない

基本形
@Select
List<Item> findAll();

※@Selectアノテーションを付けたものが対象となります。

対応するSQL

select
    /*%expand*/*
from
    item
order by 
	id asc

SQLバインド変数が存在しないので直接設定する。

条件あり
@Select
Item findCondOne(Integer id);

※引数を設定することでsqlバインド変数を設定できる

select
    /*%expand*/*
from
    item 
where
	id = /* id */1
	
	
可変条件
@Select
List<Item> findCondAll(Integer id, String name, Integer price);

select
    /*%expand*/*
from
    item 

    where
/*%if id != null || name != null || price != null */
	/*%if id != null */
		id = /* id */1
	/*%end*/
	
	/*%if name != null */
		and
		name = /* name */'a'
	/*%end*/ 
	
	/*%if price != null */
		and
		price = /* price */1
	/*%end*/
/*%end*/

	
order by 
	id asc

※複数の条件を任意に条件に設定する場合はちょっと工夫が必要

INSERT

SQLを必要とする場合と必要ない場合がある。

基本形
@Insert
int insert(Item entity);

SQLは不要

SQLを作成する
@Insert(sqlFile = true)
int insertExecute(Item entity);

アノテーションにsqlFile = trueを付与

insert into item (name, price, create_at, update_at)
values (/* entity.getName() */'a',
        /* entity.getPrice() */100,
        /* entity.getCreateAt() */'2016-12-20T11:22:33',
        /* entity.getUpdateAt() */'2016-12-20T11:22:33')

バインド変数を設定する

UPDATE

SQLを必要とする場合と必要ない場合がある。

基本形
@Update
int update(Item entity);

SQLは不要

SQLを作成する
@Update(sqlFile = true)
int updateExecute(Item entity, String update);

update 
	item 
set 
	name = /* entity.getName() */'a',
	price = /* entity.getPrice() */1,
	update_at = /* entity.getUpdateAt() */'2016-12-24 02:56:55.33'
where
	id = /* entity.getId() */1
	and update_at = /* update */'2016-12-24 02:56:55.33'

バインド変数を設定する


今回はここまで