mybatis 梳理5-- 增删改查 基于注解
作者:互联网
1、接口中添加注解
public interface AdminMapper { /** * 保存管理员 * @param admin * @return */ @Insert("insert into admin (username,password) values (#{username},#{password})") int saveAdmin(Admin admin); /** * 更新管理员 * @param admin * @return */ @Update("update admin set username=#{username} , password=#{password} where id = # {id}") int updateAdmin(Admin admin); /** * 删除管理员 * @param admin * @return */ @Delete("delete from admin where id=#{id}") int deleteAdmin(int id); /** * 根据id查找管理员 * @param id * @return */ @Select("select id,username,password from admin where id=#{id}") Admin findAdminById(@Param("id") int id); /** * 查询所有的管理员 * @return */ @Select("select id,username,password from admin") List<Admin> findAllAdmins(); }
2、核心配置文件中配置
<mappers> <mapper class="com.xinzhi.dao.AdminMapper"/> </mappers>
3、进行测试
public class TestAdmin { private SqlSession session; @Before public void before() { try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); session = sqlSessionFactory.openSession(); } catch (IOException e) { e.printStackTrace(); } }
@Test public void testSaveAdmin() { AdminMapper mapper = session.getMapper(AdminMapper.class); Admin admin = new Admin(1,"微微姐","12345678"); int i = mapper.saveAdmin(admin); System.out.println(i); }
@Test public void testUpdateAdmin() { AdminMapper mapper = session.getMapper(AdminMapper.class); Admin user = new Admin(1,"磊磊哥","12345678"); int i = mapper.updateAdmin(user); System.out.println(i); }
@Test public void testDeleteAdmin(){ AdminMapper mapper = session.getMapper(AdminMapper.class); int i = mapper.deleteAdmin(2); System.out.println(i); }
@Test public void testGetAdminById(){ AdminMapper mapper = session.getMapper(AdminMapper.class); Admin admin = mapper.findAdminById(1); System.out.println(admin); }
@Test public void testGetAllAdmins(){ AdminMapper mapper = session.getMapper(AdminMapper.class); List<Admin> admins = mapper.findAllAdmins(); for (Admin admin : admins) { System.out.println(admin); } }
@After public void close(){
//提交 session.commit(); session.close(); } }
4. 结构
不需要AdminMapper.xml
TestAdmin里面的东西不变
标签:mapper,--,改查,public,admin,session,mybatis,AdminMapper,id 来源: https://www.cnblogs.com/Master-Sun/p/14306666.html