共计 1738 个字符,预计需要花费 5 分钟才能阅读完成。
xml 元素
- namespace
xml 中的 namespace 与 dao 接口的包名统一 - id
xml 中的 id 与 dao 接口的办法名统一 - resultType
sql 语句执行的返回值 - parameterType
参数类型
select
- 编写接口
// 查问全副用户
List<User> getUserList();
- 编写 sql 语句
<!--select 查问语句 -->
<select id="getUserList" resultType="com.sunfl.pojo.User">
select * from mybatis.user
</select>
- 测试
@Test
public void test(){
// 取得 SqlSession 对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 形式一:执行 SQL 举荐
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
// 形式二:// List<User> userList = sqlSession.selectList("com.sunfl.dao.UserDao.getUserList");
for (User user : userList) {System.out.println(user);
}
// 敞开 sqlSession
sqlSession.close();}
insert
- 编写接口
// 新增一个用户
int addUser(User user);
- 编写 sql 语句
<insert id="addUser" parameterType="com.sunfl.pojo.User">
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
</insert>
- 测试
@Test
public void addUser(){SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(4, "哈哈哈", "12323"));
sqlSession.commit();
sqlSession.close();}
update
- 编写接口
// 更新一个用户
int updateUser(User user);
- 编写 sql 语句
<update id="updateUser" parameterType="com.sunfl.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
- 测试
@Test
public void updateUser(){SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(4,"嘿嘿","1111"));
sqlSession.commit();
sqlSession.close();}
delete
- 编写接口
// 删除一个用户
int deleteUser(int id);
- 编写 sql 语句
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
</delete>
- 测试
@Test
public void deleteUser(){SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(4);
sqlSession.commit();
sqlSession.close();}
正文完