mybatis入门-实现基本CRUD操作

mybatis入门-实现基本CRUD操作

    闲着没事,整理整理初学mybatis时候的笔记。另外上传了mybatis的jar包(包括开发jar包以及源代码jar),首先,建立一个java project,创建一个lib文件夹,放入mybatis的jar包跟mysql驱动的jar包,add to build path...。整体效果截图如下:

mybatis入门-实现基本CRUD操作_第1张图片


    然后,建立包目录结构和mybatis的配置文件,如上图所示。下面是User实体类:

package com.steadyjack.model;

public class User {
	private Integer id;
	private String userName;
	private int age;
	private String address;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", age=" + age
				+ ", address=" + address + "]";
	}
}

    建立数据库表:

CREATE Database mybatis
use mybatis
CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

INSERT INTO `tb_user` VALUES ('1', 'jack', '12', 'foshan');
INSERT INTO `tb_user` VALUES ('2', 'sam', '21', 'guagnzhou');
INSERT INTO `tb_user` VALUES ('3', 'jerry', '22', 'sichuang');
INSERT INTO `tb_user` VALUES ('4', 'silly', '23', 'chengdu');
INSERT INTO `tb_user` VALUES ('8', 'july', '24', 'beijing');

    mybatis-config.xml配置文件:

  




	
	
		
	
	
	
		
			
			
				
				
				
				
				
			
		
	
 	
	
		
	

    建立UserDao:

package com.steadyjack.mappers;

import java.util.List;

import com.steadyjack.model.User;

/**
 * 面向接口编程
 * @author android
 *
 */
public interface UserDao {
	
	public User getUserById(Integer id);
	
	public List getUserList(User user);
	
	public void addUser(User user);
	
	public int updateUser(User user);
	
	public int deleteUser(Integer id);
}

    建立UserMapper,其实就是UserDao的实现(从namespace就可以看出来了)

  
  
  
  
    
    
    	
    	  
          
        
    
    
      
    
    
    
    
    	insert into tb_user(userName,age,address) values(#{userName},#{age},#{address})
    
    
    
    	
    	update tb_user set
    	
    		
    			userName=#{userName},
    		
    		
    			address=#{address}
    		
    	
		where id=#{id}    	
    
    
    
    	delete from tb_user where id=#{id}
    
    
  

    最后是UserTest,测试接口中的各个方法:

package com.steadyjack.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
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 org.junit.Test;

import com.steadyjack.mappers.UserDao;
import com.steadyjack.model.User;

public class UserTest {
	
	private static SqlSessionFactory sessionFactory;
	//private static Reader reader;
	private static final String loaction="mybatis-config.xml";
	
	static{
		try {
			//getResourceAsReader 发现底层实现的原理还是InputSteamReader(inputstream来实现的)
			//reader=Resources.getResourceAsReader("mybatis-config.xml");
			//sessionFactory = new SqlSessionFactoryBuilder().build(reader);
			
			InputStream stream=UserTest.class.getClassLoader().getResourceAsStream(loaction);
			sessionFactory=new SqlSessionFactoryBuilder().build(stream);
			
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	public static SqlSessionFactory getSession(){
		return sessionFactory;
	}
	
	@Test
	public void testGet(){
		SqlSession session=sessionFactory.openSession();
		
		UserDao userDao=session.getMapper(UserDao.class);
		User user=userDao.getUserById(4);
		System.out.println(user);
		
	}
	
	@Test
	public void testQueryList(){
		SqlSession session=sessionFactory.openSession();
		
		UserDao userDao=session.getMapper(UserDao.class);
		User user=new User();
		user.setAddress("州");
		List userList=userDao.getUserList(user);
		for (User u : userList) {
			System.out.println(u);
		}
	}
	
	@Test
	public void testAdd(){
		SqlSession session=sessionFactory.openSession();
		
		UserDao userDao=session.getMapper(UserDao.class);
		User user=new User();
		user.setUserName("j");
		user.setAge(12);
		user.setAddress("f");
		
		try {
			userDao.addUser(user);
			session.commit();
			System.out.println("id: "+user.getId());
			
		} catch (Exception e) {
			System.out.println("提交事务发生异常: "+e.getMessage());
		} finally{
			session.close();
		}
	}
	
	@Test
	public void testUpdate(){
		SqlSession session=sessionFactory.openSession();
		
		UserDao userDao=session.getMapper(UserDao.class);
		User user=userDao.getUserById(12);
		System.out.println("原先的User: "+user);
		
		if (user!=null) {
			user.setUserName("steayjack");
			user.setAge(25);
			user.setAddress("上海");
			
			int res=0;
			try {
				res=userDao.updateUser(user);
				session.commit();
				System.out.println("提交成功: "+user.getId()+" -- 操作返回结果: "+res);
			} catch (Exception e) {
				System.out.println("提交事务发生异常:"+e.getMessage());
			} finally{
				session.close();
			}
		}else{
			throw new RuntimeException("没有该用户!");
		}
	}
	
	@Test
	public void testDelete(){
		SqlSession session=sessionFactory.openSession();
		UserDao userDao=session.getMapper(UserDao.class);
		
		try {
			int res=userDao.deleteUser(5);		
			System.out.println("执行结果:"+res);
			session.commit();
		} catch (Exception e) {
			System.out.println("提交事务发生异常: "+e.getMessage());
		} finally{
			session.close();
		}
		
	}
}


    没有涉及到什么关联映射之类的(其实,我在公司中实际的项目是不做实际的数据库关联的!)

    好了,就介绍到这里吧!我觉得这样入门的话,贼简单的!!!!后期会来一个spring springmvc mybatis的整合案例!!!

你可能感兴趣的:(ssh,ssm整合案例)