您的位置:首页 > 其它

Mybatis之使用注解开发CRUD

2017-08-18 09:20 274 查看
上一篇演示了怎样使用XML来操作Mybatis实现CRUD,可是大量的XML配置文件的编写是很烦人的。因此

Mybatis也提供了基于注解的配置方式,以下我们来演示一下使用接口加注解来实现CRUD的的样例。

首先是创建一个接口。

package com.bird.mybatis.bean;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

public interface UserMapper {
@Insert("insert into users(name, age) values(#{name}, #{age})")
public int add(Users user);

@Delete("delete from users where id = #{id}")
public int deleteById(int id);

@Update("update users set name = #{name}, age = #{age} where id = #{id}")
public int update(Users user);

@Select("select * from users where id = #{id}")
public Users getUserById(int id);

@Select("select * from users")
public List<Users> getAllUsers();
}


然后一定不要忘了在conf.xml配置文件里,注冊这个类

<mappers>
<mapper resource="com/bird/mybatis/bean/userMapper.xml" />
<mapper class="com.bird.mybatis.bean.UserMapper"/>
</mappers>


以下就是使用这个类了

@Test
public void testAdd2() {
SqlSession openSession = factory.openSession();
UserMapper mapper = openSession.getMapper(UserMapper.class);
mapper.add(new Users(-1,"娃娃",99));
openSession.commit();
openSession.close();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: