简单示例代码目录结构如下:
1 编写实体
public class Blog {
private Integer id;
private String title;
private Integer authorId;
//get/set方法
}
2 创建数据库及实体对应表
3 config.xml配置文件
<?xml version = "1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd" >
<configuration>
<properties resource="cn/yue/mybatis/demo/date/sqlconfig.properties" />
<typeAliases>
<typeAlias alias="Author" type="cn.yue.mybatis.demo.model.Author" />
<typeAlias alias="Blog" type="cn.yue.mybatis.demo.model.Blog" />
<typeAlias alias="Comment" type="cn.yue.mybatis.demo.model.Comment" />
<typeAlias alias="Post" type="cn.yue.mybatis.demo.model.Post" />
<typeAlias alias="Tag" type="cn.yue.mybatis.demo.model.Tag" />
</typeAliases>
<environments default="development">
<environment id="development">
<!-- mybatis有两种事物管理类型jdbc和managed-->
<transactionManager type="JDBC" />
<!-- 缓存了jdbc连接对象,加快程序响应速度 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="cn/yue/mybatis/demo/date/BlogMapper.xml" />
</mappers>
</configuration>
4 mapper.xml文件
<?xml version = "1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.yue.mybatis.demo.date.BlogMapper">
<select id="selectBlog_by_id" parameterType="int" resultType="Blog">
select * from Blog where id =#{id}
</select>
<select id="selectBlog_by_id_map" parameterType="HashMap"
resultType="Blog">
select * from Blog where id = #{id}
</select>
<select id="selectBlog_by_bean" parameterType="Blog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
5 xml配置管理器
public class SqlMapperManager {
private static SqlSessionFactory factory = null;
private static String fileName = "cn/yue/mybatis/demo/date/sqlconfig.xml";
/**
* 初始化方法
*
* @param sqlMapperFileName
*/
public static void initMapper(String sqlMapperFileName) {
fileName = sqlMapperFileName;
}
/**
*
* @return
*/
public static SqlSessionFactory getFactory() {
try {
if (null == factory) {
//根一下代码可以发现
// getResourceAsReader()===>new InputStreamReader(getResourceAsStream(resource));
//getResourceAsStream() ===> classLoaderWrapper.getResourceAsStream(resource, loader);
//getResourceAsStream===>getResourceAsStream(resource, getClassLoaders(classLoader))
//InputStream getResourceAsStream(String resource, ClassLoader[] classLoader) {
// for (ClassLoader cl : classLoader) {
// if (null != cl) {
// try to find the resource as passed
//这一句是关键
// InputStream returnValue = cl.getResourceAsStream(resource);
// now, some class loaders want this leading "/", so we'll add it and try again if we didn't find the resource
// if (null == returnValue) returnValue = cl.getResourceAsStream("/" + resource);
// if (null != returnValue) return returnValue;
// }
// }
// return null;
// }
//getClassLoaders===>return new ClassLoader[]{
// classLoader,
// defaultClassLoader,
// Thread.currentThread().getContextClassLoader(),
// getClass().getClassLoader(),
// systemClassLoader};
// }
Reader reader = Resources.getResourceAsReader(fileName);
//一但factory创建就没有必要保留builder了
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//此处得到的factory 就是xml中配置的blogMapper.xml
//factory的作用范围最好是一个应用的生命周期,所以这里使用单例模式
factory = builder.build(reader);
builder = null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return factory;
}
}
6 测试
/*
* @version 1.0
* @Date 2013-8-8
* @author retacn yue
*
*/
// ~ Package Information
package cn.yue.mybatis.demo.test;
import java.util.HashMap;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.BasicConfigurator;
import cn.yue.mybatis.demo.model.Blog;
import cn.yue.mybatis.demo.service.SqlMapperManager;
/**
* 测试类
*
* @time 下午09:58:26
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class SimpleMapperTest {
public static void main(String[] args) {
BasicConfigurator.configure();
SqlSession session = null;
Blog blog = null;
try {
SqlSessionFactory factory = SqlMapperManager.getFactory();
if (null == factory) {
System.out.println("get SqlSessionFactory failed.");
return;
}
//session是不被共享的且线程不安全的
session = factory.openSession();
HashMap<String, Integer> paramMap = new HashMap<String, Integer>();
paramMap.put("id", 2);
Blog blog2 = new Blog();
blog2.setId(3);
// 按id查询
blog = session.selectOne("selectBlog_by_id", 1);
showBlog(blog);
// 按map条件查询
blog = session.selectOne("selectBlog_by_id_map", paramMap);
showBlog(blog);
// 按对象查询
blog = session.selectOne("selectBlog_by_bean", blog2);
showBlog(blog);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
public static void showBlog(Blog blog) {
if (null != blog) {
System.out.println("ID:" + blog.getId());
System.out.println("Title:" + blog.getTitle());
System.out.println("AuthorID:" + blog.getAuthorId());
} else {
System.out.println("blog is null!");
}
}
}