2.Mybatis实现CRUD
- 编写接口
- 编写mapper对应的sql语句
- 编写测试语句
1.select
选择、查询语句;
- id:对应namespace中所定义的方法名
- resulType:sql语句执行的返回值对应的实体类
- parameterType:执行方法中所需传入的参数类型
2.insert
插入语句:
<insert id="insertUser" parameterType="com.Z.pojo.User">
insert into user (id,username,sex,address) values (#{id},#{username},#{sex},#{address})
</insert>
主要操作与查询类似,需要注意增删改需要提交事务。
@Test
public void testInsert() throws ParseException {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date myDate2 = dateFormat2.parse("1998-08-08 08:08:08");
User user =new User(1,"张三","男","北京市西城区");
mapper.insertUser(user);
//提交事务
sqlSession.commit();
sqlSession.close();
}
3.Update
修改语句:
<update id="updateUser" parameterType="User">
update user set name=#{username} where id=#{id};
</update>
4.Delete
删除语句:
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id};
</delete>
5.Map
用map作为参数传入,不需要知道数据库对象结构。
假设数据库中的字段涉及参数过多,可以考虑使用map键值对进行传参。、
<insert id="insertUserByMap" parameterType="map">
insert into user(id,username,sex,address) values (#{iid},#{iUsername},#{iSex},#{iAddress})
</insert>
public void testInsert2() throws ParseException {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
HashMap<String ,Object> map = new HashMap<String, Object>();
map.put("iid",1);
map.put("iUsername","张三");
map.put("iSex","男");
map.put("iAddress","北京市西城区");
mapper.insertUserByMap(map);
//提交事务
sqlSession.commit();
sqlSession.close();
}
单个参数时考虑直接传值
多个参数时考虑使用map或者注解