Mybatis学习(五)mybatis环境下以接口的方式进行的增删查改

上一篇刚进行过普通的mybatis的增删查改,当然如果在项目中按这样的方法来操作的话,写的代码会太繁重了。现在我们就将进行接口的方式进行增删查改。

需求分析:

以接口的方式进行增删查改

详细设计:

写出接口:IUserOperation.java

   修改User.xml文件

步骤:

IUserOperation.java

package cn.bj.mybatis.model;

public interface IUserOperation {
	
	    public User selectUser(int id);
	    
	    public void addUser(User user);
	    
	    public void updateUser(User user);
	    
	    public void deleteUser(int id);
}
User.xml




 
  
  
  
  
  	insert into user(username,age) values(#{username},#{age})
  
  
  
  	update user set username=#{username},age=#{age} where id=#{id}
  
  
  
  	delete from user where id = #{id}
  
java的测试类:MybatisTest.java

package cn.bj.mybatis.test;

import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import cn.bj.mybatis.model.IUserOperation;
import cn.bj.mybatis.model.User;

public class MybatisTest {
	public static void main(String[] args){
		SqlSessionFactory sqlSessionFactory = null;
		SqlSession session = null;
		String resource = "Configuration.xml";
		InputStream inputStream;
		try {
			inputStream = Resources.getResourceAsStream(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			session = sqlSessionFactory.openSession();
			System.out.println(session);
			IUserOperation userOperation = (IUserOperation)session.getMapper(IUserOperation.class);
			/**
			 * 增加
			User user = new User();
			user.setAge(40);
			user.setUsername("huawei");
			userOperation.addUser(user);
			session.commit();
			System.out.println(user.getId());
			*/
			
			/**
			 * 查询
			User user = userOperation.selectUser(3);
			System.out.println(user.getUsername());
			*/
			
			/**
			 * 修改
			User user = userOperation.selectUser(3);
			user.setUsername("22222");
			session.commit();
			*/
			
			/**
			 * 删除
			userOperation.deleteUser(3);
			session.commit();
			*/
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(session != null){
				session.close();
			}
		}
		
	}

}
似乎看上去简单了点。也分点层了。




你可能感兴趣的:(Mybatis学习笔记)