Mybatis中怎么实现注解增删改查操作
这篇文章给大家介绍Mybatis中怎么实现注解增删改查操作,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
成都创新互联为客户提供专业的网站制作、成都网站设计、程序、域名、空间一条龙服务,提供基于WEB的系统开发. 服务项目涵盖了网页设计、网站程序开发、WEB系统开发、微信二次开发、移动网站建设等网站方面业务。
需要在config.xml中注册Java接口
要用class=
查
public interface PeopleMapper { @Select("select * from people") ListgetPeopleList(); }
增 可以先开启事务自动提交
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(); } }
因为已经自动提交了,所以不需要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中怎么实现注解增删改查操作就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
网页名称:Mybatis中怎么实现注解增删改查操作
文章来源:http://scyanting.com/article/jsohsd.html