2 mybatis实现增删改查
张创琦 2022.03.08
所有的配置都基于第一个文件。
0 before after 抽取
private SqlSession sqlSession;private String resource = "mybatis.xml";@Beforepublic void before() throws IOException {//1、读取mybatis的配置文件Reader reader = Resources.getResourceAsReader(resource);//2、创建SqlSessionFactory对象, 目的是获取sqlSession--根据图纸创建工厂SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);//3、创建可以执行SQL语句的SqlSession--工厂创建产品sqlSession = sqlSessionFactory.openSession();}@Afterpublic void after(){sqlSession.close();}
1 查询所有结果
<!-- 查询所有结果 --><select id="queryAll" resultType="com.kkb.pojo.Team">select * from team;</select>
2 根据ID查询
<!-- 根据ID查询 --><!-- parameterType="参数的类型",目前只支持一个参数 --><!-- #{id}表示参数 id-自定义, 只需要符合命名规范即可, 没有实际对应意义 --><select id="queryById" parameterType="int" resultType="com.kkb.pojo.Team">select * from team where teamId=#{id} ;</select>
@Testpublic void testFindById() {Team team = sqlSession.selectOne("com.kkb.pojo.Team.queryById", 1001);System.out.println(team);}
3 删除一个球队
<!-- 删除一个球队 --><delete id="del">delete from team where teamId=#{id};</delete>
@Testpublic void testDel(){int num = sqlSession.delete("com.kkb.pojo.Team.del", 1049);sqlSession.commit();System.out.println(num);}
4 删除多个球队
<!-- 删除多个球队-测试ok --><delete id="del2">delete from team where location=#{loc};</delete>
@Testpublic void testDel2(){int num = sqlSession.delete("com.kkb.pojo.Team.del2", "handan");sqlSession.commit();System.out.println(num); // 2}
5 更新球队信息
<!-- 根据球队编号更新信息 --><update id="update" parameterType="com.kkb.pojo.Team">update team set teamName=#{teamName}, location=#{location} where teamId=#{teamId}</update>
@Testpublic void testUpdate(){Team team = sqlSession.selectOne("com.kkb.pojo.Team.queryById", 1054);team.setTeamName("zhangchuangqi的球队");team.setLocation("洛杉矶");int num = sqlSession.update("com.kkb.pojo.Team.update", team);sqlSession.commit();System.out.println(num);}
6 添加一个球队
<!-- 添加一个球队 --><!-- parameterType="com.kkb.pojo.Team" 将对象作为参数.注意 `` 符号的输入#{值} 值必须是实体类中的属性名称,其实就是占位符 ? --><insert id="add" parameterType="com.kkb.pojo.Team">INSERT INTO `team` (`teamName`, `location`, `createTime`)VALUES (#{teamName}, #{location}, #{createTime})</insert>
@Testpublic void testAdd() {Team team = new Team();team.setTeamName("zhang的球队2");team.setLocation("邯郸");team.setCreateTime(new Date());int num = sqlSession.insert("com.kkb.pojo.Team.add", team);sqlSession.commit();System.out.println(num);}
‘
