首先mybatis配置文件中注册mapper.class,实质用反射机制实现
底层用的动态代理注解需要在接口上实现,脱离mapper.xml
1.查询方法
mapper的编写
/**
* Gets user.
*
* @return the user
*/
@Select("SELECT * FROM USER")
List<User> getUser();
/**
* Add user map int.
*
* @param map the map
* @return the int
*/
@Insert("insert into ljqdb.user (username, password) VALUES (#{name},#{pass})")
int addUserMap(Map<String,Object> map);
/**
* Delete user int.
*
* @param id the id
* @return the int
*/
@Delete(" delete from ljqdb.user where id = #{id}")
int deleteUser(int id);
/**
* Up user int.
*
* @param user the user
* @return the int
*/
@Update("update ljqdb.user set username=#{username},password=#{password} where id = #{id}")
int upUser(User user);
测试类的编写
public class UserTest {
/**
* Up user.
*/
@Test
public void upUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(3, "我爱你", "123");
mapper.upUser(user);
sqlSession.commit();
sqlSession.close();
}
/**
* Del user.
*/
@Test
public void delUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int id = 6;
mapper.deleteUser(id);
sqlSession.commit();
sqlSession.close();
}
/**
* Add.
*/
@Test
public void add(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//创建map接收
Map<String, Object> map = new HashMap<>();
map.put("name", "麻子黄");
map.put("pass", "xiao");
mapper.addUserMap(map);
//提交事务
sqlSession.commit();
//关闭sqlSession实例
sqlSession.close();
}
/**
* Get user.
*/
@Test
public void getUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> user = mapper.getUser();
for (User user1 : user) {
System.out.println(user1);
}
sqlSession.close();
}
}