前言
??????? Mybatis使用注解只能实行一些简单的SQL
??????? 它只需要在编写接口时,在接口上加上个注解,就不用在mapper.xml配置文件中编写了
??????? user类结构
public class User {
private int id;
private String name;
private String pwd;
}
查询
接口
查询user表中所有的记录
@Select("select * from user")
List<User> getUsers();
通过查询对应姓名的用户信息
@Select("select * from user where name=#{name}")
User getUserByName(@Param("name") String name);
测试
//查询所有用户
@Test
public void getUsers(){
//1.获取SqlSession对象
SqlSession sqlSession = getSqlSession();
//调用
UserMapper userMapper =sqlSession.getMapper(UserMapper.class);
List<User> userList =userMapper.getUsers();
for (User user : userList) {
System.out.println(user);
}
//关闭
sqlSession.close();
}
//通过姓名查询用户信息
@Test
public void getUserByName(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper =sqlSession.getMapper(UserMapper.class);
User user=mapper.getUserByName("周星星");
System.out.println(user);
sqlSession.close();
}
插入
接口
往user表插入一条新的记录
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")
int addUser(User user);
测试
@Test
public void addUser(){
//1.获取SqlSession对象
SqlSession sqlSession = getSqlSession();
//调用
UserMapper userMapper =sqlSession.getMapper(UserMapper.class);
userMapper.addUser(new User(369,"尚下九","147"));
//提交事务
sqlSession.commit();
//关闭
sqlSession.close();
}
修改
接口
更新用户信息
@Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
int updateUser(User user);
测试
@Test
public void updateUser(){
//1.获取SqlSession对象
SqlSession sqlSession = getSqlSession();
//调用
UserMapper userMapper =sqlSession.getMapper(UserMapper.class);
userMapper.updateUser(new User(369,"三六九","258"));
//提交事务
sqlSession.commit();
//关闭
sqlSession.close();
}
删除
接口
删除一个用户
@Delete("delete from user where id=#{id}")
int deleteById(@Param("id") Integer id);
测试
@Test
public void deleteById(){
//1.获取SqlSession对象
SqlSession sqlSession = getSqlSession();
//调用
UserMapper userMapper =sqlSession.getMapper(UserMapper.class);
userMapper.deleteById(369);
//提交事务
sqlSession.commit();
//关闭
sqlSession.close();
}
@Param注解
基本类型的参数或者String类型,需要加上 引用类型不需要加 如果只有一个基本类型的话,可以忽略,但是建议大家都加上! 我们在SQL中引用的就是我们这里的@Param()中设定的属性名!
|