这篇文章给大家介绍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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。