Mybatis接口类注释增删改查

Posted (。・∀・)ノ゙嗨,小鼻涕孩

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis接口类注释增删改查相关的知识,希望对你有一定的参考价值。

员工实体类:

 

 创建接口类,WorkerMapper.java

 package com.xiaobiti.dao;
 
 import com.xiaobiti.pojo.Worker;
 import org.apache.ibatis.annotations.*;
 
 public interface WorkerMapper 
     //查询
     @Select("select * from tb_worker where id = #id")
     Worker findById(int id);
     //插入
     @Insert("insert into tb_worker(name,age,sex,worker_id) values (#name,#age,#sex,#worker_id)")
     void addWorker(Worker w);
     //更新
     @Update("update tb_worker set name=#name,age=#age,sex=#sex,worker_id=#worker_id where id = #id")
     void updateWorker(Worker w);
     //删除
     @Delete("delete from tb_worker where id=#id")
     void deleteWorker(int id);
     //传入参数的查询方式
     @Select("select * from tb_worker where id=#workId and name=#workName")
     Worker findByIdAndName(@Param("workId") int id,@Param("workName")String name);
 

 

需要在mybatis-config.xml配置文件中添加:

 

 测试类运行代码:

 //查询
     @Test
     public void findById()
         SqlSession session = MybatisUtils.getSession();
         WorkerMapper mapper = session.getMapper(WorkerMapper.class);
         Worker worker = mapper.findById(2);
         System.out.println(worker);
     
 
     //插入
     @Test
     public void addWorker()
         SqlSession session = MybatisUtils.getSession();
         WorkerMapper mapper = session.getMapper(WorkerMapper.class);
         Worker worker = new Worker();
         worker.setAge(20);
         worker.setName("jojo");
         worker.setSex("男");
         worker.setWorker_id(1008);
         mapper.addWorker(worker);
         session.commit();
         System.out.println(worker);
     
 
     //更新
     @Test
     public void updateWorker()
         SqlSession session = MybatisUtils.getSession();
         WorkerMapper mapper = session.getMapper(WorkerMapper.class);
         Worker worker = new Worker();
         worker.setId(2);
         worker.setAge(20);
         worker.setName("jojo");
         worker.setSex("男");
         worker.setWorker_id(1008);
         mapper.updateWorker(worker);
         session.commit();
         System.out.println(worker);
     
 
     //删除
     @Test
     public void deleteWorker()
         SqlSession session = MybatisUtils.getSession();
         WorkerMapper mapper = session.getMapper(WorkerMapper.class);
         mapper.deleteWorker(5);
         session.commit();
     
 
     //传入参数的查询
     @Test
     public void findByIdAndName()
         SqlSession session = MybatisUtils.getSession();
         WorkerMapper mapper = session.getMapper(WorkerMapper.class);
         Worker worker = mapper.findByIdAndName(3,"李四");
         System.out.println(worker);
     

 

以上是关于Mybatis接口类注释增删改查的主要内容,如果未能解决你的问题,请参考以下文章

Mybatis框架—简单的增删改查

Mybatis框架—简单的增删改查

Maven+Mybatis实现数据库增删改查

ssm 框架实现增删改查CRUD操作(Spring + SpringMVC + Mybatis 实现增删改查)

Mybatis实现增删改查

mybatis增删改查