Mybatis 注解配置和接口方式增删改查-SQL语句写入到接口类中

 

1、接口类代码

package javastudy;

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;

public interface UserMapper {
	@Select("select * from user where id = #{id}")
	public User selectUser(int id);
	@Select(" select * from user")
	public List selectAll();
	@Insert("insert into user (userName,userPwd) values (#{userName},#{userPwd})")
	public void addUser(User user);
	@Update("update user set userName=#{userName},userPwd=#{userPwd} where id=#{id}")
	public void updateUser(User user);
	@Delete("delete from user where id=#{id}")
	public void deleteUser(int id);

}

 

2、修改userMapper.xml文件




 

说明:这里的配置不能与注解方式冲突,一般全部SQL写在XML或接口类中,当然也可以把一部分SQL写在XML,一部分写在接口类中,但是同一个SQL不能两个地方同时写。

3、mybtis-config.xml文件不用变 

 
     
    
   
 

4、测试类代码

package test;

import java.io.IOException;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import javastudy.User;
import javastudy.UserMapper;
import utility.MyBatisUtils;
public class MyTest {
	@Test
	public void testSelect() throws IOException {
		SqlSession session=MyBatisUtils.openSession();
		UserMapper userMapper=session.getMapper(UserMapper.class);
		User user=userMapper.selectUser(1);
		System.out.println(user);
		session.close();
	}
	@Test
	public void testSelectAll() throws IOException {
		SqlSession session=MyBatisUtils.openSession();
		UserMapper userMapper=session.getMapper(UserMapper.class);
		List list=userMapper.selectAll();
		System.out.println(list);
		session.close();
	}
	@Test
	public void testInsert() throws IOException {
		SqlSession session=MyBatisUtils.openSession();
		UserMapper userMapper=session.getMapper(UserMapper.class);
		User user=new User();
		user.setUserName("tangbin");
		user.setUserPwd("168888");
		userMapper.addUser(user);
		session.commit();
		session.close();
	}
	@Test
	public void testUpdate() throws IOException {
		SqlSession session=MyBatisUtils.openSession();
		UserMapper userMapper=session.getMapper(UserMapper.class);
		User user=new User();
		user.setId(5);
		user.setUserName("王五");
		user.setUserPwd("wangwu123456");
		userMapper.updateUser(user);
		session.commit();
		session.close();
	}
	@Test
	public void testDelete() throws IOException {
		SqlSession session=MyBatisUtils.openSession();
		UserMapper userMapper=session.getMapper(UserMapper.class);
		userMapper.deleteUser(4);
		session.commit();
		session.close();
	}
	
}

 

你可能感兴趣的:(SSM)