Mybatis 注解配置和接口方式增删改查-SQL语句SQL命令写入一个专门类中

1、新建Sqlprovider类

package javastudy;

public class Sqlprovider {
    public String selectUser(){
        return "select * from user where id = #{id}";
    }
    public String selectAll(){
        return "select * from user";
    }
    public String addUser(){
        return "insert into user (userName,userPwd) values (#{userName},#{userPwd})";
    }
    public String updateUser(){
        return "update user set userName=#{userName},userPwd=#{userPwd} where id=#{id}";
    }
    public String deleteUser(){
        return "delete from user where id=#{id}";
    }
}

2、接口类代码,修改UserMapper类中的注解

package javastudy;

import java.util.List;

import org.apache.ibatis.annotations.SelectProvider;
public interface UserMapper {
    @SelectProvider(type=Sqlprovider.class,method="selectUser")
    public User selectUser(int id);
    @SelectProvider(type=Sqlprovider.class,method="selectAll")
    public List selectAll();
    @SelectProvider(type=Sqlprovider.class,method="addUser")
    public void addUser(User user);
    @SelectProvider(type=Sqlprovider.class,method="updateUser")
    public void updateUser(User user);
    @SelectProvider(type=Sqlprovider.class,method="deleteUser")
    public void deleteUser(int id);
}

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(5);
		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(6);
		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(5);
		session.commit();
		session.close();
	}
	
}

 

你可能感兴趣的:(SSM)