Mybatis使用注解開發CRUD

jopen 10年前發布 | 33K 次閱讀 MyBatis3 持久層框架 MyBatis

使用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();  
}  </pre><a class="About" title="?" href="/misc/goto?guid=4959615652242808476"></a></div>

</div> </div>
然后一定不要忘了在conf.xml配置文件中,注冊這個類

</div> </div>

    <mappers>  
            <mapper resource="com/bird/mybatis/bean/userMapper.xml" />  
            <mapper class="com.bird.mybatis.bean.UserMapper"/>  
        </mappers>  

下面就是使用這個類了

@Test  
    public void testAdd2() {  
        SqlSession openSession = factory.openSession();  
        UserMapper mapper = openSession.getMapper(UserMapper.class);  
        mapper.add(new Users(-1,"娃娃",99));  
        openSession.commit();  
        openSession.close();  
    }  
</div> </div> 來自:http://blog.csdn.net/a352193394/article/details/39940259

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!