mybatis CRUD

除了XML配置,還有註解方式

首先,
/**
 * @author gacl
 * 定義sql映射的接口,使用註解指明方法要執行的SQL
 */
public interface UserMapperI {

    //使用@Insert註解指明add方法要執行的SQL
    @Insert("insert into users(name, age) values(#{name}, #{age})")
    public int add(User user);
   
    //使用@Delete註解指明deleteById方法要執行的SQL
    @Delete("delete from users where id=#{id}")
    public int deleteById(int id);
   
    //使用@Update註解指明update方法要執行的SQL
    @Update("update users set name=#{name},age=#{age} where id=#{id}")
    public int update(User user);
   
    //使用@Select註解指明getById方法要執行的SQL
    @Select("select * from users where id=#{id}")
    public User getById(int id);
   
    //使用@Select註解指明getAll方法要執行的SQL
    @Select("select * from users")
    public List<User> getAll();
}

需要說明的是,我們不需要針對UserMapperI接口去編寫具體的實現類代碼,這個具體的實現類由MyBatis幫我們動態構建出來,我們只需要直接拿來使用即可。
同時,在conf.xml文件中註冊這個映射接口:
    <mappers>
        <!-- 註冊userMapper.xml文件,
        userMapper.xml位於me.gacl.mapping這個包下,所以resource寫成me/gacl/mapping/userMapper.xml-->
        <mapper resource="me/gacl/mapping/userMapper.xml"/>
        <!-- 註冊UserMapper映射接口-->
        <mapper class="me.gacl.mapping.UserMapperI"/>
    </mappers>

使用時:
        SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
        //得到UserMapperI接口的實現類對象,UserMapperI接口的實現類對象由sqlSession.getMapper(UserMapperI.class)動態構建出來
        UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
        User user = new User();
        user.setName("用戶xdp");
        user.setAge(20);
        int add = mapper.add(user);
        //使用SqlSession執行完SQL之後需要關閉SqlSession
        sqlSession.close();
        System.out.println(add);


public class MyBatisUtil {

    /**
     * 獲取SqlSessionFactory
     * @return SqlSessionFactory
     */
    public static SqlSessionFactory getSqlSessionFactory() {
        String resource = "conf.xml";
        InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        return factory;
    }
   
    /**
     * 獲取SqlSession
     * @return SqlSession
     */
    public static SqlSession getSqlSession() {
        return getSqlSessionFactory().openSession();
    }
   
    /**
     * 獲取SqlSession
     * @param isAutoCommit
     *         true 表示創建的SqlSession對象在執行完SQL之後會自動提交事務
     *         false 表示創建的SqlSession對象在執行完SQL之後不會自動提交事務,這時就需要我們手動調用sqlSession.commit()提交事務
     * @return SqlSession
     */
    public static SqlSession getSqlSession(boolean isAutoCommit) {
        return getSqlSessionFactory().openSession(isAutoCommit);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章