MyBatis的增删改查方法


1.4 开发步骤(推荐)

新建JAVA项目或WEB项目

部署jar包(包括数据库驱动包):使用MyBatis需要先下载jar包

编写主配置文件

创建数据库及表(如已创建,可省略)

创建实体类及SQL映射文件

编写数据库接口及实现

编写测试类及测试

1.5 开发示例

1.5.1  新建项目

新建java项目或web 项目。我的工程目录结构如下图

MyBatis的增删改查方法_第1张图片

1.5.2 导入JAR包

导入mybatis和数据库驱动包、日志包(配置日志配置文件),下载地址(http://pan.baidu.com/s/1kUARvc7)。

1.5.3  创建myBatis-config.xml

(可以参考用户手册)。

 



	
	
		
		
			
			
			
				
				
				
				
			
		

	
	
 	
		
	 


1.5.4  创建数据库及表

drop databaseif exists person;
create database person CHARACTERSET UTF8;
use person;
 
create table person(
    id int primarykey auto_increment,
    name varchar(50),
    age int
);
 
 
insert into 
person
(name,age) values('wxz',18);insert into person (name,age) values('w xz2 ',19);
insert into person (name,age) values(wxz3,20);
select * from person ;
 
   

 
  

1.5.5  创建实体类:Person.java

package cn.wxz.entity;

import java.io.Serializable;

public class Person implements Serializable {


	private static final long serialVersionUID = -2525513725816258556L;
	private Integer id;
	private String name;
	private int age;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Person [age=" + age + ", id=" + id + ", name=" + name + "]";
	}
	
	

}


1.5.6  创建SQL映射文件及修改主配置文件

SQL映射文件:personMapper.xml(可以参考用户手册)

 














	insert into person(name,age) values(#{name},#{age})


			update person set name=#{name} where  age=#{age} 



		delete from person  where age=#{age}



	
	


	

1.5.7  编写数据库操作

包括操作接口及实现,接口略,实现类为:PersonDaoImpl.java


package cn.wxz.dao.impl;

import java.io.IOException;
import java.io.Reader;
import java.util.List;
import java.util.Map;

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.wxz.entity.Person;
import cn.wxz.tool.MyBatisUtil;
public class PersonDaoImpl {
	/*
	 * 1.读取配置文件信息
	 * 2。构建session工厂
	 * 3。创建session
	 * 4.开启事务(可选)
	 * 5。处理数据
	 * 6。提交、回滚事务
	 * 7。关闭session 
	 * 
	 */
	SqlSession session = null;
	
	public int  save(Person person){
	
		int i=0;

		try {
			session=MyBatisUtil.getSession();
			//方法的第一个参数为DeptMapper.xml文件的命名空间+id
			 i=session.insert("cn.wxz.PersonMapper.insertDept",person);
			System.out.println("受影响行数:"+i);
			session.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			session.rollback();
			
		}finally{
				MyBatisUtil.closeSession();
		}	
		return i;
}

	
	
	public int  update(Person person){

		int i=0;

		try {
			session=MyBatisUtil.getSession();
			//方法的第一个参数为DeptMapper.xml文件的命名空间+id
			 i=session.update("cn.wxz.PersonMapper.update",person);
			System.out.println("受影响行数:"+i);
			session.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			session.rollback();
			
		}finally{
				MyBatisUtil.closeSession();
		}	
		return i;
}

	
	
	
	
	public int  delete(Person person){
		SqlSession session = null;
		int i=0;

		try {
			session=MyBatisUtil.getSession();
			//方法的第一个参数为DeptMapper.xml文件的命名空间+id
			 i=session.update("cn.wxz.PersonMapper.delete",person);
			System.out.println("受影响行数:"+i);
			session.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			session.rollback();
			
		}finally{
				MyBatisUtil.closeSession();
		}	
		return i;
}

	
	
	public Person query(int  age){
		
		Person person=null;
		try {
			session=MyBatisUtil.getSession();
			person=(Person)session.selectOne("cn.wxz.PersonMapper.selectOne",age);
			System.out.println("dept:"+person);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			MyBatisUtil.closeSession();
		}
		return person;

}
	
	
	public List selectList(Map map){
		List persons=null;
		try {
			session=MyBatisUtil.getSession();
			persons=session.selectList("cn.wxz.PersonMapper.selectList",map);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			MyBatisUtil.closeSession();
		}
		return persons;
}

	
	
	
	
	public List selectListUseIf(Person person){
		List persons=null;
		try {
			session=MyBatisUtil.getSession();
			persons=session.selectList("cn.wxz.PersonMapper.selectListUseIf",person);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			MyBatisUtil.closeSession();
		}
		return persons;
}


	
	public List selectListUseWhere(Person person){
		List persons=null;
		try {
			session=MyBatisUtil.getSession();
			persons=session.selectList("cn.wxz.PersonMapper.selectListUseIf",person);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			MyBatisUtil.closeSession();
		}
		return persons;
}

	
}


1.5.8  编写测试类

需要导入junit包

package cn.wxz.test;

import static org.junit.Assert.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import cn.wxz.dao.impl.PersonDaoImpl;
import cn.wxz.entity.Person;
public class TestDeptDaoImpl {
	private static PersonDaoImpl personDaoImpl;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		personDaoImpl = new PersonDaoImpl();
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		personDaoImpl = null;
	}

	@Test
	public void test() {
		Person person = new Person();
		person.setName("222");
		person.setAge(25);
		System.out.println("受影响 的行数:"+personDaoImpl.save(person));
	}
	
	@Test
	public void testUpdate() {
		Person person = new Person();
		person.setName("ni shi a  ");
		person.setAge(25);
		System.out.println("受影响 的行数:"+personDaoImpl.update(person));
	}

	@Test
	public void testDelete() {
		Person person = new Person();

		person.setAge(25);
		System.out.println("受影响 的行数:"+personDaoImpl.delete(person));
	}
	
	@Test
	public void testQuery() {
		Person person = new Person();

		person.setAge(25);
	 Person query = personDaoImpl.query(person.getAge());
		System.out.println("受影响 的行数:"+query);
	}
	
	@Test
	public void testSelectList() {
		Map map=new HashMap();
		map.put("deptName", "%真%");
		List persons=personDaoImpl.selectList(map);
		for(Person person:persons){
			System.out.println("person:"+person);
		}
}
	@Test
	public void testSelectListUseIf() {
	Person person2 = new Person();
	person2.setAge(25);
person2.setName("222");
		List persons=personDaoImpl.selectListUseIf(person2);
		for(Person person:persons){ 
			System.out.println("person:"+person);
		}
}
	
	
	@Test
	public void testSelectListUseWhere() {
	Person person2 = new Person();
	person2.setId(13);
	person2.setAge(25);
person2.setName("真棒");
		List persons=personDaoImpl.selectListUseIf(person2);
		for(Person person:persons){
			System.out.println("person:"+person);
		}
}
	
	
	
}


 

2.基本的CRUD操作

2.1           准备工作(继续使用前面的库表和代码)

2.2           别名与自定义别名

2.2.1  内置别名

对常用的 java 类型,已经内置了一些别名支持。这些别名都是不区分大小写的。(详细参看用户手机)

2.2.2  自定义别名

在myBatis的主配置文件给cn.itcast.entity.Dept类创建别名Dept,后继的DeptMapper.xml配置文件中可以使用别名

<typeAliases>

      <typeAliastype="cn.itcast.entity.Dept"alias="Dept"/>

typeAliases>

2.3  MyBatisUtil工具类

 

package cn.wxz.tool;

import java.io.IOException;
import java.io.Reader;

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

public class MyBatisUtil {

	   
	private static final ThreadLocal threadLocal = new ThreadLocal();
    private static SqlSessionFactory sessionFactory;
	
    private static String CONFIG_FILE_LOCATION = "myBatis-config.xml";

	static {
    	try {
    		buildSessionFactory();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private MyBatisUtil() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the SessionFactory if needed.
     *
     *  @return Session
     *  @throws Exception
     */
    public static SqlSession getSession() throws Exception {
        SqlSession session = (SqlSession) threadLocal.get();

		if (session == null) {
			if (sessionFactory == null) {
				buildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  build  session factory
     *
     */
	public static void buildSessionFactory() {
		Reader reader=null;
		try {
			reader=Resources.getResourceAsReader(CONFIG_FILE_LOCATION);
			sessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}finally{
			try {
				reader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
     *  Close the single  session instance.
     *
     */
    public static void closeSession(){
        SqlSession session = (SqlSession) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public static SqlSessionFactory getSessionFactory() {
		return sessionFactory;
	}
}




你可能感兴趣的:(mybatis)