mybatis接口和实现xml和测试类

UserMapper接口

//查询全部用户
List<User> getUserList();
//根据ID查询用户
User getUserById(int id);
//insert一个用户
int addUser(User user);
//修改用户
int updataUser(User use);
//删除一个用户
int deleteUser(int id);

UserMapper实现配置文件

<select id="getUserList" resultType="com.lingyue.pojo.User">
    select * from mybatis.user
</select>
<select id="getUserById" parameterType="int" resultType="com.lingyue.pojo.User">
    select * from mybatis.user where id = #{id}
</select>
<insert id="addUser" parameterType="com.lingyue.pojo.User">
    insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
<update id="updataUser" parameterType="com.lingyue.pojo.User">
    update mybatis.user set name=#{name},pwd=#{pwd} where id =#{id}
</update>
<delete id="deleteUser" parameterType="int">
    delete from mybatis.user where id = #{id}
</delete>

UserMapperTest类

@Test
public void test() {
    //第一步:获得SqlSession对象
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    //执行SQL
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    List<User> userList = userMapper.getUserList();
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}
@Test
public void getUserById() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper usemapper = sqlSession.getMapper(UserMapper.class);
    User user = usemapper.getUserById(4);
    System.out.println(user);
    sqlSession.close();
}
@Test
public void addUser() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    userMapper.addUser(new User(10,"九九","234567"));
    sqlSession.commit();
    sqlSession.close();
}
@Test
public void updataUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    userMapper.updataUser(new User(4,"哈哈","123789"));
    sqlSession.commit();
    sqlSession.close();
}
@Test
public void deleteUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    userMapper.deleteUser(10);
    sqlSession.commit();
    sqlSession.close();
}

增,删,改需要提交事务!

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值