mybatis 学习笔记(二)
CRUD
- namespace
namespace中的包名要与Dao/Mapper接口包名一致
- select
选择,查询语句:
id:就是对应的namespace中的方法名;
resultType:SQL语句执行的返回值
parameterType:参数类型
- insert
- delete
- update
第一步 :编写接口
第二步:编写对应的mapper中的对应语句
第三步:测试
package com.lilubao.dao;
import com.lilubao.pojo.user;
import java.util.List;
public interface UserMapper {
// 查询全部用户
List<user> getUserList();
//根据id查询用户
user getUserById(int id);
//insert一个用户
int addUser(user user);
int updateUser(user user);
int deleteUser(int id);
} //这是接口
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lilubao.dao.UserMapper">
<select id="getUserList" resultType="com.lilubao.pojo.user">
select *
from mybatis.user
</select>
<select id="getUserById" resultType="com.lilubao.pojo.user" parameterType="int">
select *
from mybatis.user
where id = #{id}
</select>
<insert id="addUser" parameterType="com.lilubao.pojo.user" >
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="com.lilubao.pojo.user">
update mybatis.user
set name=#{name},pwd=#{pwd}
where id=#{id};
</update>
<delete id="deleteUser" parameterType="com.lilubao.pojo.user">
delete from mybatis.user where id= #{id};
</delete>
</mapper> //编写mapper语句
package com.lilubao.dao;
import com.lilubao.pojo.user;
import com.lilubao.utils.mybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
//第一步 获得sqlSession对象
SqlSession sqlSession = mybatisUtils.getSqlSession();
//执行sql
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
List<user> userList = userDao.getUserList();
for (user user : userList) {
System.out.println(user);
}
//关闭sqlSession
sqlSession.close();
}
@Test
public void getUserById(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
UserMapper Mapper = sqlSession.getMapper(UserMapper.class);
user user = Mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
@Test
public void addUser(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
UserMapper Mapper = sqlSession.getMapper(UserMapper.class);
int num = Mapper.addUser(new user(5, "lilubao1", "123456789"));
if(num>0){
System.out.println("插入成功!");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
UserMapper Mapper = sqlSession.getMapper(UserMapper.class);
Mapper.updateUser(new user(5,"lilubao3","1991399142"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(5);
sqlSession.commit();
sqlSession.close();
}
}
最大注意点:增删改需要提交事务
sqlSession.commit();