Mybatis-基于注解的增删改查

【1】注解接口-UserMapper

注意,接口上面没有使用@Repository注解:

public interface UserMapper {
	
	@Insert("insert into t_user(username,age) values(#{name},#{age})")
	public int addUser(User user);
	
	@Delete("delete from t_user where id=#{id}")
	public int deleteUser(int id);
	
	@Update("update t_user set username=#{name},age=#{age} where id=#{id}")
	public int updateUser(User user);
	
	@Select("select * from t_user where id=#{id}")
	public User getUser(int id);
	
	@Select("select * from t_user")
	public List getUsers();

}


注册到mybatis.xml


	
	
	
	//注意,未与userMapper.xml放在同一包下


【2】增删改查实例

实例代码如下:

/*use   annotation*/
	
	@Test
	public void testAdd(){
		
		SqlSession session = MybatisUtils.getFactory().openSession();
		UserMapper mapper = session.getMapper(UserMapper.class);
		int addUser = mapper.addUser(new User("Tom6", 16));
		/*return the effect rows*/
		/*default is not auto commit*/
		session.commit(true);
		session.close();
		
		System.out.println("effect rows.."+addUser);
	}
	@Test
	public void testSelect(){
		/*set auto commit ,which equals to the above*/
		SqlSession session = MybatisUtils.getFactory().openSession(true);
		UserMapper mapper = session.getMapper(UserMapper.class);
		User user = mapper.getUser(7);
		/*return the effect rows*/
		System.out.println("effect rows.."+user);
	}
	@Test
	public void testUpdate(){
		
		SqlSession session = MybatisUtils.getFactory().openSession(true);
		UserMapper mapper = session.getMapper(UserMapper.class);
		int updateUser = mapper.updateUser(new User(7,"Tom62", 162));
		/*return the effect rows*/
		System.out.println("effect rows.."+updateUser);
	}
	@Test
	public void testDelete(){
		
		SqlSession session = MybatisUtils.getFactory().openSession();
		UserMapper mapper = session.getMapper(UserMapper.class);
		int deleteUser = mapper.deleteUser(6);
		/*return the effect rows*/
		/* commit by yourself*/
		session.commit();
		System.out.println("effect rows.."+deleteUser);
		session.close();
	}
	
	@Test
	public void testGetUsers(){
		
		SqlSession session = MybatisUtils.getFactory().openSession();
		UserMapper mapper = session.getMapper(UserMapper.class);
		/*return the List*/
		List users = mapper.getUsers();
		session.commit();
		System.out.println("effect rows.."+users);
		session.close();
	}
	
	

【3】同时使用基于注解和xml注意事项

① userMapper.xml 与namespace

若不一致,如namespace改为com.web.mapper.userMapperr,将会报错

Mybatis-基于注解的增删改查_第1张图片


② userMapper.xml与UserMapper.class不应放在同一包下

Mybatis-基于注解的增删改查_第2张图片

使用注解时,提示找不到类!

你可能感兴趣的:(#,MyBatis)