mybatis注釈形式で削除・変更を行う

3003 ワード

mySql :
CREATE TABLE `test` (
  `t_id` int(11) NOT NULL AUTO_INCREMENT,
  `t_name` varchar(200) NOT NULL,
  `create_date` datetime NOT NULL,
  `update_date` datetime DEFAULT NULL,
   PRIMARY KEY (`t_id`)
)

 
Model:
//@Data   lombok  
@Data  
public class Test implements Serializable {

    private static final long serialVersionUID = 1L;
    
    private Integer tId;
    private String tName;
    private Date createDate;
    @DateTimeFormat(pattern="yyyy-MM-dd")   //               
    private Date updateDate;
}

 
Mapper:
@Mapper
public interface TestMapper {


    @Select(""
            + "select t.t_id,t.t_name from test t where 1=1"
            + "<if test=\"tId != null and tId != '' \"> and t.t_id=#{tId}</if>"
            + "")
    @Results({
                    @Result(column = "t_id", property = "tId"),
                    @Result(column = "t_name", property = "tName")
            })
    public List query(@Param("tId") String tId)

    

    //t_id       
    @Insert("INSERT INTO test (t_name, create_date, update_date) VALUES"
            + "(#{test.tName},now(),now())"
            + "")
    @SelectKey(before = false, keyProperty = "test.tId", resultType = Integer.class,
            statementType = StatementType.STATEMENT, statement = "SELECT LAST_INSERT_ID() AS t_id")
    public int insert(@Param("test") Test test);
    


    @Update("UPDATE test set update_date = "
            +"<choose> <when test=\"test.updateDate != null \"> #{test.updateDate}</when>"
            +"<otherwise> now()</otherwise>"
            + "</choose>"
            + " where t_id=#{test.tId}")
    public int update(@Param("test") Test test);
    


    @Delete("delete FROM test where t_id = #{tId}")
    public int delete(@Param("tId") String tId);
    

    //    ,       ,#   *   ,#   ?  ,*           
    @Insert("" + "insert into test (`t_name`, `create_date`, `update_date`) VALUES "
            + "<foreach collection =\"testList\" item=\"testModel\" index= \"index\" separator =\",\"> "
            + "(<![CDATA[ #{testModel.tName},now(),now()]])>"
            + "</foreach > "
            + "")
    @SelectKey(before = false, keyProperty = "tId", resultType = int.class,
            statementType = StatementType.STATEMENT, statement = "SELECT LAST_INSERT_ID() AS t_id")
    public int insertList(@Param("testList") List testList);

}  

 
という形では感覚があまりはっきりしない場合は、@SelectProvider,@InsertProvider,@UpdateProvider,@DeleteProvider,@
providerはSQLを返すだけですが、@Paramの使い方に注意してください.