@Insert("insert into user(userId,userName,password,comment) values(#{userId},#{userName},#{password},#{comment})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
public int insert ( User user );
这个操作有没有和Mapper.xml中的Sql很相似,没错注解@Insert就是干这样的事。
注意@Insert注解中Value的值是个数组,那么下面这个Insert注解也是合法的:
@Insert(value={"insert into user(userId,userName,password,comment) "," values(#{userId},#{userName},#{password},#{comment})"})
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
public int insert ( User user );
mybatis生成Sql语句时,会将数组拼接,生成最终的Sql,不过貌似这个功能不应该这么鸡肋,大家可以仔细思考下这个功能点究竟在什么地方。
@Options注解中的工作就比较有意思,我们在插入记录时,一般是定义主键自增(auto_increment),但是在某些情况下,我们插入一条记录后,还想得到这条记录的自增主键ID,useGeneratedKeys=true就是定义数据库返回主键ID的。
在Options中,定义了不少的属性:
once you engage the Options annotation, your statement is subject to all of the default values.
如果你使用了这个属性,SQL的执行就会使用Options的默认值,如果你没有重新定义的话。仔细看下keyColumn的默认值是空,这个如果和你数据库设定不一致的话,就会出问题;所以一旦决定使用主键返回功能,推荐同时使用useGeneratedKeys、keyProperty、keyColumn这三个属性,即使是冗余也没有关系。
下面看下删除操作:
@Delete("delete from user where userName = #{userName}")
public int delete ( String userName );
这个没有什么特殊的操作,理解了Insert操作之后这个delete操作就比较简单了。
更新操作也没有什么问题:
@Update("update user set userId=#{userId},password=#{password},comment=#{comment} where userName=#{userName}")
public int update ( User user );
@Update("update user set userName=#{userName} where userId=#{userId}")
public int updateUser(@Param("userName")String userName,@Param("userId")String userId);
我们使用@Param参数,只是传递我们感兴趣的参数即可。
有人可能会有疑问,@Param参数貌似没有什么用,这个参数本身就可以获取的。没错,看下面这种格式的update:
@Update("update user set userName=#{name} where userId=#{Id}")
public int updateUser ( @Param("name") String userName, @Param("Id") String userId );
传入的参数是userName,而在@Param中被重新定义成name,那么在Sql中就可以通过${name}直接使用了,这个实际上是解决函数参数和Sql参数的阻抗不匹配情况。
最后我们再看下数据库和POJO阻抗不匹配时的解决方法:
@Select("select * from user order by id asc")
// @Results(value = {
// @Result(property="userId",column="userId",javaType=Integer.class,jdbcType=JdbcType.VARCHAR,typeHandler=UnknownTypeHandler.class),
// @Result(property="name", column="userName"),
// @Result(property="psword", column="password"),
// @Result(property="comment", column="comment")
// })
public List<User> selectAll ();
@Results能够重新定义数据库和POJO之间字段的对应关系,其中每一个属性对应都由Result重新定义,和上面代码中注掉的地方一样。
那么Result能够重新定义哪些字段呢?注意上文代码中注掉的代码仅供演示使用,并无真正实际映射的必要。如JDBC的Varchar本身就被映射为String类型。
The one attribute is for single associations, similar to <association>, and the many attribute is for collections, similar to <collection>. They are named as they are to avoid class naming conflicts.
而One和Many属性就是定义字段的对应关系。