2 mybatis实现增删改查

张创琦 2022.03.08

所有的配置都基于第一个文件。

0 before after 抽取

  1. private SqlSession sqlSession;
  2. private String resource = "mybatis.xml";
  3. @Before
  4. public void before() throws IOException {
  5. //1、读取mybatis的配置文件
  6. Reader reader = Resources.getResourceAsReader(resource);
  7. //2、创建SqlSessionFactory对象, 目的是获取sqlSession--根据图纸创建工厂
  8. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  9. //3、创建可以执行SQL语句的SqlSession--工厂创建产品
  10. sqlSession = sqlSessionFactory.openSession();
  11. }
  12. @After
  13. public void after(){
  14. sqlSession.close();
  15. }

1 查询所有结果

  1. <!-- 查询所有结果 -->
  2. <select id="queryAll" resultType="com.kkb.pojo.Team">
  3. select * from team;
  4. </select>

2 根据ID查询

  1. <!-- 根据ID查询 -->
  2. <!-- parameterType="参数的类型",目前只支持一个参数 -->
  3. <!-- #{id}表示参数 id-自定义, 只需要符合命名规范即可, 没有实际对应意义 -->
  4. <select id="queryById" parameterType="int" resultType="com.kkb.pojo.Team">
  5. select * from team where teamId=#{id} ;
  6. </select>
  1. @Test
  2. public void testFindById() {
  3. Team team = sqlSession.selectOne("com.kkb.pojo.Team.queryById", 1001);
  4. System.out.println(team);
  5. }

3 删除一个球队

  1. <!-- 删除一个球队 -->
  2. <delete id="del">
  3. delete from team where teamId=#{id};
  4. </delete>
  1. @Test
  2. public void testDel(){
  3. int num = sqlSession.delete("com.kkb.pojo.Team.del", 1049);
  4. sqlSession.commit();
  5. System.out.println(num);
  6. }

4 删除多个球队

  1. <!-- 删除多个球队-测试ok -->
  2. <delete id="del2">
  3. delete from team where location=#{loc};
  4. </delete>
  1. @Test
  2. public void testDel2(){
  3. int num = sqlSession.delete("com.kkb.pojo.Team.del2", "handan");
  4. sqlSession.commit();
  5. System.out.println(num); // 2
  6. }

5 更新球队信息

  1. <!-- 根据球队编号更新信息 -->
  2. <update id="update" parameterType="com.kkb.pojo.Team">
  3. update team set teamName=#{teamName}, location=#{location} where teamId=#{teamId}
  4. </update>
  1. @Test
  2. public void testUpdate(){
  3. Team team = sqlSession.selectOne("com.kkb.pojo.Team.queryById", 1054);
  4. team.setTeamName("zhangchuangqi的球队");
  5. team.setLocation("洛杉矶");
  6. int num = sqlSession.update("com.kkb.pojo.Team.update", team);
  7. sqlSession.commit();
  8. System.out.println(num);
  9. }

6 添加一个球队

  1. <!-- 添加一个球队 -->
  2. <!-- parameterType="com.kkb.pojo.Team" 将对象作为参数.
  3. 注意 `` 符号的输入
  4. #{值} 值必须是实体类中的属性名称,其实就是占位符 ? -->
  5. <insert id="add" parameterType="com.kkb.pojo.Team">
  6. INSERT INTO `team` (`teamName`, `location`, `createTime`)
  7. VALUES (#{teamName}, #{location}, #{createTime})
  8. </insert>
  1. @Test
  2. public void testAdd() {
  3. Team team = new Team();
  4. team.setTeamName("zhang的球队2");
  5. team.setLocation("邯郸");
  6. team.setCreateTime(new Date());
  7. int num = sqlSession.insert("com.kkb.pojo.Team.add", team);
  8. sqlSession.commit();
  9. System.out.println(num);
  10. }