Mybatis之使用註解開發CRUD,mybatis註解crud
上一篇示範了如何使用XML來操作Mybatis實現CRUD,但是大量的XML設定檔的編寫是非常煩人的。因此
Mybatis也提供了基於註解的配置方式,下面我們來示範一下使用介面加註解來實現CRUD的的例子。
首先是建立一個介面。
package com.bird.mybatis.bean;import java.util.List;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;public interface UserMapper {@Insert("insert into users(name, age) values(#{name}, #{age})")public int add(Users user);@Delete("delete from users where id = #{id}")public int deleteById(int id);@Update("update users set name = #{name}, age = #{age} where id = #{id}")public int update(Users user);@Select("select * from users where id = #{id}")public Users getUserById(int id);@Select("select * from users")public List<Users> getAllUsers();}
然後一定不要忘了在conf.xml設定檔中,註冊這個類
<mappers><mapper resource="com/bird/mybatis/bean/userMapper.xml" /><mapper class="com.bird.mybatis.bean.UserMapper"/></mappers>
下面就是使用這個類了
@Testpublic void testAdd2() {SqlSession openSession = factory.openSession();UserMapper mapper = openSession.getMapper(UserMapper.class);mapper.add(new Users(-1,"娃娃",99));openSession.commit();openSession.close();}
mybatis怎實現對象參數與註解參數同時傳入
自訂對象也用@param註解.
在mapper.xml中使用的時候,#{對象別名.屬性名稱},如#{user.id}
注意,使用了@pram註解的話在mapper.xml不加parameterType。
public List<UserExtension> selectAllUsers( @Param("user") UserExtension user, @Param("begin") int begin, @Param("end") int end);
只使用mybatis不用spring怎管理事務?最好有代碼帶注釋的
全過程,自己管理