這篇文章給大家介紹Mybatis中怎么實現(xiàn)注解增刪改查操作,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
成都創(chuàng)新互聯(lián)為客戶提供專業(yè)的網(wǎng)站制作、成都網(wǎng)站設(shè)計、程序、域名、空間一條龍服務(wù),提供基于WEB的系統(tǒng)開發(fā). 服務(wù)項目涵蓋了網(wǎng)頁設(shè)計、網(wǎng)站程序開發(fā)、WEB系統(tǒng)開發(fā)、微信二次開發(fā)、移動網(wǎng)站建設(shè)等網(wǎng)站方面業(yè)務(wù)。
需要在config.xml中注冊Java接口
要用class=
public interface PeopleMapper { @Select("select * from people") ListgetPeopleList(); }
增 可以先開啟事務(wù)自動提交
public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(true); } } Mapper.java ```java public interface PeopleMapper { @Select("select * from people") ListgetPeopleList(); @Insert("insert into people(id, name, age, address) VALUES (#{id},#{name},#{age},#{address})") int addPeople(People people); }
test
public class PeopleDAOtest { [@Test](https://my.oschina.net/azibug) public void print() { SqlSession sqlSession = MybatisUtils.getSqlSession(); PeopleMapper peopleMapper = sqlSession.getMapper(PeopleMapper.class); Listpeople = peopleMapper.getPeopleList(); for (People p :people){ System.out.println(p); } sqlSession.close(); } [@Test](https://my.oschina.net/azibug) public void add(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); PeopleMapper peopleMapper = sqlSession.getMapper(PeopleMapper.class); peopleMapper.addPeople(new People(6,"圣迭戈",456,"啥地方")); print(); } }
因為已經(jīng)自動提交了,所以不需要sqlSession.commit();
注解@Param 只能用于基本數(shù)據(jù)類型 傳入的參數(shù)只能和sql語句中參數(shù)一樣 多個參數(shù) 樣例
public interface PeopleMapper { @Delete("delete people from people where id=#{uid}") int delPeople(@Param("uid") int i); }
test
public class PeopleDAOtest { @Test public void del(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); PeopleMapper peopleMapper = sqlSession.getMapper(PeopleMapper.class); peopleMapper.delPeople(6); print(); } }
Mapper.java
public interface PeopleMapper { @Update("update mybatis.people set name=#{name} ,age=#{age} ,address=#{address} where id=#{id}") int updateP(People people); }
test
public class PeopleDAOtest { @Test public void update(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); PeopleMapper peopleMapper = sqlSession.getMapper(PeopleMapper.class); peopleMapper.updateP(new People(5,"圣迭戈",456,"啥地方")); print(); } }
關(guān)于Mybatis中怎么實現(xiàn)注解增刪改查操作就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。