mybits是支持普通sql查询、存储过程和高级映射的持久层框架
几乎消除了所有的jdbc代码和参数设置以及对结果集检索封装
可用xml或注解二种方式配置
jdbc->dbUtil(自动封装结果集)->mybatis->hibernate(面向对象的操作)
一个简单的mybatis例子(根据id查数据)
1.添加mybatis和mysql的jar包,在数据库中建立一个表如:user表
2.编写mybaits的config.xml
可从文档中copy
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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="123" />
dataSource>
environment>
environments>
configuration>
3.建立表相应的实体类,如:user
4.建立user的映射文件userMapper.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="com.mybits_01.test1.userMapper">
<select id="getUser" parameterType="int"
resultType="com.mybits_01.test1.User">
select * from users where id=#{id}
select>
mapper>
5.在config.xml中注册userMapper.xml文件
<mappers>
<mapper resource="com/mybits_01/test1/userMapper.xml"/>
mappers>
6.插曲:如果没有标签提示,可能没有导入dtd文件,在Eclipse中的window下打开preferences搜索xml在xml下的xml catalog里点击add出现如图:
指定一个public id 如
中的-//mybatis.org//DTD Config 3.0//EN
而location则是dtd文件所在位置就可以了
7.测试
public static void main(String[] args) throws IOException {
String resource = "conf.xml";
InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = factory.openSession();
String statement = "com.mybits_01.test1.userMapper.getUser";
User user = session.selectOne(statement,1);
System.out.println(user);
}