您好,登錄后才能下訂單哦!
這篇文章給大家介紹Mybatis中怎么實現注解增刪改查操作,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
需要在config.xml中注冊Java接口
<mappers> <mapper class="com.mybatis.DAO.PeopleMapper"/> </mappers>
要用class=
public interface PeopleMapper { @Select("select * from people") List<People> getPeopleList(); }
增 可以先開啟事務自動提交
public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(true); } } Mapper.java ```java public interface PeopleMapper { @Select("select * from people") List<People> getPeopleList(); @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); List<People> people = 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(); } }
因為已經自動提交了,所以不需要sqlSession.commit();
注解@Param 只能用于基本數據類型 傳入的參數只能和sql語句中參數一樣 多個參數 樣例
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(); } }
關于Mybatis中怎么實現注解增刪改查操作就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。