Mybatis之使用註解開發CRUD,mybatis註解crud

來源:互聯網
上載者:User

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怎管理事務?最好有代碼帶注釋的

全過程,自己管理
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.