新建JAVA项目或WEB项目
部署jar包(包括数据库驱动包):使用MyBatis需要先下载jar包
编写主配置文件
创建数据库及表(如已创建,可省略)
创建实体类及SQL映射文件
编写数据库接口及实现
编写测试类及测试
新建java项目或web 项目。我的工程目录结构如下图
导入mybatis和数据库驱动包、日志包(配置日志配置文件),下载地址(http://pan.baidu.com/s/1kUARvc7)。
(可以参考用户手册)。
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);
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 + "]";
}
}
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}
包括操作接口及实现,接口略,实现类为: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;
}
}
需要导入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);
}
}
}
对常用的 java 类型,已经内置了一些别名支持。这些别名都是不区分大小写的。(详细参看用户手机)
在myBatis的主配置文件给cn.itcast.entity.Dept类创建别名Dept,后继的DeptMapper.xml配置文件中可以使用别名
<typeAliases>
<typeAliastype="cn.itcast.entity.Dept"alias="Dept"/>
typeAliases>
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;
}
}