1. 程式人生 > >用註解的方式實現增刪改查

用註解的方式實現增刪改查

和上一個實現增刪改查的區別就是將UserMapper.xml變成了現在的UserMapper.java

User11Mapper.java

package com.sxau.rjxy.MyBatis_test3;

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;

import com.sxau.rjxy.MyBatis_test.User;

public interface User11Mapper {
	@Insert("insert into users(name,age)values(#{name},#{age})")
	public int add(User 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(User user);
	
	@Select("select *from users where id=#{id}")
	public User getById(int id);
	
	@Select("select * from users")
	public List<User> getAll();
	
}

conf.xml中註冊時候應該是

<mappers>
		<mapper class="com.sxau.rjxy.MyBatis_test3.User11Mapper" />
</mappers>

測試類

package com.sxau.rjxy.MyBatis_test3;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import com.sxau.rjxy.MyBatis_test.User;
import com.sxau.rjxy.MyBatis_test2.MyBatisUtils;
public class Test1 {
	@Test
	public void testAdd(){
		SqlSessionFactory factory = MyBatisUtils.getFactory();
		SqlSession session = factory.openSession(true);
		User11Mapper mapper = session.getMapper(User11Mapper.class);
		
		int add = mapper.add(new User(-1,"ss",43));
		System.out.println(add);
		session.close();
//		
	}
	
}