MyBatis学习——配置相关xml实现增删改查

配置mybatis的配置文件。mybatis.xml




	
		
	
	
		
		
		
		
	
	
		
			
			
				
	       	 	
	        	
	        	
			
		
	
	
		
	

mapper.xml的sql语句。




    
	
	
	
	
	
	
	
	
	
	
	
	
		insert into user values(#{uid},#{uname},#{age})
	
	
	
		update user set uname=#{uname} where uid=#{uid}
	
	
	
		delete from user where uid=#{0}
	

测试类:

package cn.liu.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

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.liu.pojo.User;


public class Test {
	public static void main(String[] args) throws IOException{
		//读取xml,转换为流对象
		InputStream is = Resources.getResourceAsStream("mybatis.xml");
		//使用工厂设计模式
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
		//生成一个Sqlsession
		SqlSession session = factory.openSession();
		/*
		HashMap map = new HashMap();
		map.put("uid", 1);
		map.put("age", 21);
		User u = session.selectOne("a.b.selmap", map);
		System.out.println(u);
		
		int page = 2;
		int num = 3;
		HashMap map = new HashMap();
		map.put("page", page);
		map.put("num", num);
		List list = session.selectList("a.b.sellimit", map);
		System.out.println(list.toString());
		
		List list = session.selectList("a.b.selthree");
		List list2 = session.selectList("a.b.seltwo");
		System.out.println(list2.toString());
		
		
		User u = new User();
		u.setAge(28);
		u.setUname("李红");
		u.setUid(10);
		int i = session.insert("a.b.ins",u);
		if(i>0){
			System.out.println("新增成功");
		}else{
			System.out.println("新增失败");
		}
		session.commit();
		
		int i = session.delete("a.b.de",10);
		if(i>0){
			System.out.println("删除成功");
		}else{
			System.out.println("删除失败");
		}
		session.commit();
		
		
		User u = new User();
		u.setAge(28);
		u.setUname("龚红");
		u.setUid(8);
		int i = session.update("a.b.up", u);
		if(i>0){
			System.out.println("更新成功");
		}else{
			System.out.println("更新失败");
		}
		*/
		User one = session.selectOne("a.b.selone",8);
		System.out.println(one.toString());
		session.commit();
		
		
		
		
		session.close();
	}
}

 

你可能感兴趣的:(Java学习,javaEE基础学习)