步骤
1.注解在接口上实现;例如:
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")
public int addUser(User user);
2.需要在核心配置文件中进行绑定(由于使用注解可不需要UserMapper.xml配置文件,故我们对接口类进行绑定)
<mappers>
<mapper class="com.feng.dao.UserMapper"/>
</mappers>
3.测试(增删改都需要提交事务,可开启自动提交)
自动提交(在工具类中将其设置为true;默认为false)
public static SqlSession getSession(){
return sqlSessionFactory.openSession(true);
}
@Test
public void test2(){
SqlSession session = MybatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int i = mapper.addUser(new User(6, "xiaoqi", "123456"));
session.close();
}
C
//增
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{password})")
public int addUser(User user);
R
//删
@Delete("delete from user where id = #{id}")
public int delUser(@Param("id") int id);
U
//改
@Update("update user set name = #{name},pwd = #{pwd} where id = #{id}")
public int updateUser(Map<String,Object> map);
D
@Select("select * from user where id = #{id}")
public User getUserById(@Param("id") int id);
后续测试方法相同
关于@Param注解:
1.基本数据类型和String类型,需加上;
2.引用类型不需要加
3.如果只有一个基本类型的话,可以不加,但建议加上
4.我们SQL中引用的就说@Param("")中的设定的属性名