使用MyBatis框架步骤

1、新建web product 名称为mybatisDemo


2、在lib目录下放入3个jar包
log4j-1.2.16.jar
mybatis-3.2.2.jar
mysql-connector-java-5.1.0-bin.jar


3、创建resources的源文件夹
database.properties
log4j.properties
mybatis-config.xml


4、编写MyBatis核心配置文件(mybatis-config.xml)

PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">






















5、DAO层-接口(表名Mapper.java)
package com.ma.dao;


public interface UserMapper {
int selectUserCount();
}


6、DAO层-SQL映射文件(表名Mapper.xml)

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">





7、创建util包编写MyBatisUtil.java
package com.ma.util;


import java.io.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;
public class MyBatisUtil {
private static SqlSessionFactory factory;

static{//在静态代码块下,factory只会被创建一次
System.out.println("static factory===============");
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}

public static SqlSession createSqlSession(){
return factory.openSession(false);//true 为自动提交事务
}

public static void closeSqlSession(SqlSession sqlSession){
if(null != sqlSession) 
sqlSession.close();
}
}


8、创建测试类
package com.ma.dao;


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 org.apache.log4j.Logger;
import org.junit.Test;


import com.ma.util.MyBatisUtil;


public class TestUserMapper {
private Logger logger = Logger.getLogger(TestUserMapper.class);


@Test
public void testSelectUserCount2() {
int count = 0;
SqlSession sqlSession = null;
try {
sqlSession=MyBatisUtil.createSqlSession();
count=sqlSession.getMapper(UserMapper.class).selectUserCount();
logger.debug("testSelectUserCount:"+count);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
}
}

你可能感兴趣的:(使用MyBatis框架步骤)