员工实体类:
创建接口类,WorkerMapper.java
1 package com.xiaobiti.dao; 2 3 import com.xiaobiti.pojo.Worker; 4 import org.apache.ibatis.annotations.*; 5 6 public interface WorkerMapper { 7 //查询 8 @Select("select * from tb_worker where id = #{id}") 9 Worker findById(int id); 10 //插入 11 @Insert("insert into tb_worker(name,age,sex,worker_id) values (#{name},#{age},#{sex},#{worker_id})") 12 void addWorker(Worker w); 13 //更新 14 @Update("update tb_worker set name=#{name},age=#{age},sex=#{sex},worker_id=#{worker_id} where id = #{id}") 15 void updateWorker(Worker w); 16 //删除 17 @Delete("delete from tb_worker where id=#{id}") 18 void deleteWorker(int id); 19 //传入参数的查询方式 20 @Select("select * from tb_worker where id=#{workId} and name=#{workName}") 21 Worker findByIdAndName(@Param("workId") int id,@Param("workName")String name); 22 }
需要在mybatis-config.xml配置文件中添加:
测试类运行代码:
1 //查询 2 @Test 3 public void findById(){ 4 SqlSession session = MybatisUtils.getSession(); 5 WorkerMapper mapper = session.getMapper(WorkerMapper.class); 6 Worker worker = mapper.findById(2); 7 System.out.println(worker); 8 } 9 10 //插入 11 @Test 12 public void addWorker(){ 13 SqlSession session = MybatisUtils.getSession(); 14 WorkerMapper mapper = session.getMapper(WorkerMapper.class); 15 Worker worker = new Worker(); 16 worker.setAge(20); 17 worker.setName("jojo"); 18 worker.setSex("男"); 19 worker.setWorker_id(1008); 20 mapper.addWorker(worker); 21 session.commit(); 22 System.out.println(worker); 23 } 24 25 //更新 26 @Test 27 public void updateWorker(){ 28 SqlSession session = MybatisUtils.getSession(); 29 WorkerMapper mapper = session.getMapper(WorkerMapper.class); 30 Worker worker = new Worker(); 31 worker.setId(2); 32 worker.setAge(20); 33 worker.setName("jojo"); 34 worker.setSex("男"); 35 worker.setWorker_id(1008); 36 mapper.updateWorker(worker); 37 session.commit(); 38 System.out.println(worker); 39 } 40 41 //删除 42 @Test 43 public void deleteWorker(){ 44 SqlSession session = MybatisUtils.getSession(); 45 WorkerMapper mapper = session.getMapper(WorkerMapper.class); 46 mapper.deleteWorker(5); 47 session.commit(); 48 } 49 50 //传入参数的查询 51 @Test 52 public void findByIdAndName(){ 53 SqlSession session = MybatisUtils.getSession(); 54 WorkerMapper mapper = session.getMapper(WorkerMapper.class); 55 Worker worker = mapper.findByIdAndName(3,"李四"); 56 System.out.println(worker); 57 }
标签:mapper,改查,worker,session,Worker,Mybatis,WorkerMapper,接口类,id From: https://www.cnblogs.com/xiaobiti/p/17240301.html