1.配置文件
<select id="selectUser" resultType="net.xyz.entiy.User">
select * from user where id = #{id}
</select>
2.UserDao层
public int addUser(User user) throws IOException {
SqlSession sqlSession=MybatisUtil.getSession();
int result=sqlSession.insert("net.xyz.entiy.UserMapper.addUser",user);
sqlSession.commit();
sqlSession.close();
return result;
}
3.Test操作
//向数据库中添加一个用户
User user=new User();
user.setUsername("风清扬");
user.setUserage(12);
try {
System.out.println(userDao.addUser(user));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
1.配置文件
<delete id="deleteUser" parameterType="net.xyz.entiy.User">
delete from user where id=#{id}
</delete>
2.UserDao层
public int deleteUser(User user) throws IOException {
SqlSession sqlSession=MybatisUtil.getSession();
int result=sqlSession.insert("net.xyz.entiy.UserMapper.deleteUser",user);
sqlSession.commit();
sqlSession.close();
return result;
}
3.Test
//4.根据用户id删除用户
try {
User user =userDao.selectUserById(4);
System.out.println(userDao.deleteUser(user));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
从数据库中修改一条记录
1.配置文件
<update id="updateUser" parameterType="net.xyz.entiy.User" >
update user set username = #{username},userage=#{userage} where id=#{id}
</update>
2.UserDao层
public int updateUser(User user) throws IOException {
SqlSession sqlSession=MybatisUtil.getSession();
int result=sqlSession.insert("net.xyz.entiy.UserMapper.updateUser",user);
sqlSession.commit();
sqlSession.close();
return result;
}
3.Test操作
User user;
try {
user = userDao.selectUserById(2);
user.setUsername("陆小果");
user.setUserage(123);
System.out.println(userDao.updateUser(user));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
1.配置文件
<select id="selectUser" resultType="net.xyz.entiy.User">
select * from user where id = #{id}
</select>
2.UserDao层
public User selectUserById(int id) throws IOException {
SqlSession sqlSession=MybatisUtil.getSession();
User user=sqlSession.selectOne("net.xyz.entiy.UserMapper.selectUser", id);
sqlSession.close();
return user;
}
3.Test操作
//1.根据用户id查询用户
UserDao userDao=new UserDao();
try {
User user=userDao.selectUserById(2);
System.out.println(user);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
1.配置文件
<select id="selectAllUser" resultType="net.xyz.entiy.User">
select * from user
</select>
2.UserDao层
public List<User> selectAllUser() throws IOException{
SqlSession sqlSession=MybatisUtil.getSession();
List<User> users=sqlSession.selectList("net.xyz.entiy.UserMapper.selectAllUser");
sqlSession.commit();
sqlSession.close();
return users;
}
3.Test操作
try {
List<User> users=userDao.selectAllUser();
for(User user:users) {
System.out.println(user.toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}