服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Mybatis注解增删改查的实例代码

Mybatis注解增删改查的实例代码

2021-08-19 11:49KittyGuy Java教程

这篇文章主要给大家介绍了关于Mybatis注解增删改查的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

要点

有另一种方法来完成语句映射。 它们映射的语句可以不用 XML 来配置,而可以使用 Java 注解来配置。

使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。

如果你需要做一些很复杂的操作,最好用 XML 来映射语句。

需要在config.xml中注册Java接口

  1. <mappers>
  2. <mapper class="com.mybatis.DAO.PeopleMapper"/>
  3. </mappers>

要用class=

  1. public interface PeopleMapper {
  2. @Select("select * from people")
  3. List<People> getPeopleList();
  4. }


可以先开启事务自动提交

  1. public static SqlSession getSqlSession(){
  2. return sqlSessionFactory.openSession(true);
  3. }
  4. }

Mapper.java

  1. public interface PeopleMapper {
  2. @Select("select * from people")
  3. List<People> getPeopleList();
  4. @Insert("insert into people(id, name, age, address) VALUES (#{id},#{name},#{age},#{address})")
  5. int addPeople(People people);
  6. }

test

  1. public class PeopleDAOtest {
  2. @Test
  3. public void print() {
  4. SqlSession sqlSession = MybatisUtils.getSqlSession();
  5. PeopleMapper peopleMapper = sqlSession.getMapper(PeopleMapper.class);
  6. List<People> people = peopleMapper.getPeopleList();
  7. for (People p :people){
  8. System.out.println(p);
  9. }
  10. sqlSession.close();
  11. }
  12. @Test
  13. public void add(){
  14. SqlSession sqlSession = MybatisUtils.getSqlSession();
  15. PeopleMapper peopleMapper = sqlSession.getMapper(PeopleMapper.class);
  16. peopleMapper.addPeople(new People(6,"圣迭戈",456,"啥地方"));
  17. print();
  18. }
  19. }

因为已经自动提交了,所以不需要sqlSession.commit();

注解@Param

只能用于基本数据类型

传入的参数只能和sql语句中参数一样

Mybatis注解增删改查的实例代码

多个参数

Mybatis注解增删改查的实例代码

样例

  1. public interface PeopleMapper {
  2. @Delete("delete people from people where id=#{uid}")
  3. int delPeople(@Param("uid") int i);
  4. }

test

  1. public class PeopleDAOtest {
  2. @Test
  3. public void del(){
  4. SqlSession sqlSession = MybatisUtils.getSqlSession();
  5. PeopleMapper peopleMapper = sqlSession.getMapper(PeopleMapper.class);
  6. peopleMapper.delPeople(6);
  7. print();
  8. }
  9. }

Mapper.java

  1. public interface PeopleMapper {
  2. @Update("update mybatis.people set name=#{name} ,age=#{age} ,address=#{address} where id=#{id}")
  3. int updateP(People people);
  4. }

test

  1. public class PeopleDAOtest {
  2. @Test
  3. public void update(){
  4. SqlSession sqlSession = MybatisUtils.getSqlSession();
  5. PeopleMapper peopleMapper = sqlSession.getMapper(PeopleMapper.class);
  6. peopleMapper.updateP(new People(5,"圣迭戈",456,"啥地方"));
  7. print();
  8. }
  9. }

总结

到此这篇关于Mybatis注解增删改查的文章就介绍到这了,更多相关Mybatis注解增删改查内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://juejin.cn/post/6933495094414835726

延伸 · 阅读

精彩推荐