查
1,编写接口方法
public interface userMapper {
//根据ID查询用户
User getUserByID(int id);
}
2,编写Mapper中sql语句
<select id="getUserByID" resultType="com.Google.pojo.User" parameterType="int">
select * from user where id= #{id}
</select>
3,实现
public void getUserByID(){
SqlSession sqlSession = sqlSessionFactory.getsqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
User userByID = mapper.getUserByID(1);
System.out.println(userByID);
sqlSession.close();
}
增
1.编写接口中的方法
int addUser (User user);
2.编写Mapper中的sql语句
<!--增加用户-->
<insert id="addUser" parameterType="com.Google.pojo.User">
insert into user (id,name,pwd) value (#{id},#{name},#{pwd})
</insert>
3.实现
public void addUser (){
SqlSession sqlSession = sqlSessionFactory.getsqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
int nums = mapper.addUser(new User(4, "秋君", "123123"));
if(nums>0){
sqlSession.commit();//提交事务(增删改都需要提交事务)
}
}
删
1.编写接口中的方法
int deleteUser (int id);
2.编写Mapper中的sql语句
<!--删除用户-->
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete>
3.实现
public void deleteUser(){
SqlSession sqlSession = sqlSessionFactory.getsqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
int nums = mapper.deleteUser(4);
if(nums>0){
sqlSession.commit();
}
sqlSession.close();
}
改
1.编写接口中的方法
int updateUser (User user);
2.编写Mapper中的sql语句
<!--修改用户-->
<update id="updateUser" parameterType="com.Google.pojo.User">
update user
set name=#{name},pwd=#{pwd}
where id=#{id};
</update>
3.实现
public void updateUser(){
SqlSession sqlSession = sqlSessionFactory.getsqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
int nums = mapper.updateUser(new User(4, "小罗", "123123123"));
if(nums>0){
sqlSession.commit();
}
}
注意,增删改需要提交事务(commit)