概述
在Java中,对数据库操作的框架很多,上节概述Hibernate的简单使用,这里简单整理Mybatis的使用。Mybatis也是简单的数据库操作框架,通过IOC方式,获取操作类对象,进行数据的操作。本文参考多个博客内容进行总结汇总,整理而成。
Mybatis
功能架构分为三层:
- API接口层:提供给外部使用的接口API,开发人员通过这些本地API来操纵数据库。接口层一接收到调用请求就会调用数据处理层来完成具体的数据处理。
- 数据处理层:负责具体的SQL查找、SQL解析、SQL执行和执行结果映射处理等。它主要的目的是根据调用的请求完成一次数据库操作。
- 基础支撑层:负责最基础的功能支撑,包括连接管理、事务管理、配置加载和缓存处理,这些都是共用的东西,将他们抽取出来作为最基础的组件。为上层的数据处理层提供最基础的支撑。
ORM包
mybatis-3.1.2.jar 和 mysql-connector-java-5.1.10
XML配置
添加mybatis-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> <settings> <!-- changes from the defaults for testing --> <setting name="cacheEnabled" value="false" /> <setting name="useGeneratedKeys" value="true" /> <setting name="defaultExecutorType" value="REUSE" /> </settings> <typeAliases> <typeAlias alias="User" type="justin.maven.com.User"/> </typeAliases> <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://192.168.1.101:3306/testdb?characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments>
<!--映射文件,配置好路径--> <mappers> <mapper resource="UserMapper.xml" /> </mappers> </configuration>
添加UserMapper.xml映射文件:配置总的ID要和代码内容保持一致
<?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="justin.maven.com.UserMapper"> <!-- 这里namespace必须是UserMapper接口的路径” --> <insert id="insertUser" parameterType="User"> insert into user(name,age) values(#{name},#{age}) <!-- 这里sql结尾不能加分号,否则报“ORA-00911”的错误 --> </insert> <!-- 这里的id必须和UserMapper接口中的接口方法名相同 --> <select id="getUser" resultType="User" parameterType="java.lang.String"> select * from user where name=#{name} </select> </mapper>
代码编写
添加User实体
package justin.maven.com; public class User { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public User(String name, Integer age) { super(); this.name = name; this.age = age; } public User() { super(); } }
添加UserMapper类,记得和UserMapper.xml某些ID保持一致
package justin.maven.com; public interface UserMapper { public void insertUser(User user); public User getUser(String name); }
添加MyBatisUtil类,初始化调用Mapper
package justin.maven.com; import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { private final static SqlSessionFactory sqlSessionFactory; static { String resource = "mybatis-config.xml"; Reader reader = null; try { reader = Resources.getResourceAsReader(resource); } catch (IOException e) { System.out.println(e.getMessage()); } sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } }
添加测试类,调用访问数据库
package justin.maven.com; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; public class TestMyBatis { static SqlSessionFactory sqlSessionFactory=null; static { sqlSessionFactory=MyBatisUtil.getSqlSessionFactory(); } public static void testAdd() { SqlSession sqlSession=sqlSessionFactory.openSession(); try { UserMapper userMapper=(UserMapper)sqlSession.getMapper(UserMapper.class); User user = new User("lisi", new Integer(25)); userMapper.insertUser(user); sqlSession.commit();// 这里一定要提交,不然数据进不去数据库中 } finally { sqlSession.close(); } } public static void getUser(){ SqlSession sqlSession = sqlSessionFactory.openSession(); try { UserMapper userMapper = (UserMapper)sqlSession.getMapper(UserMapper.class); User user = userMapper.getUser("zhangsan"); System.out.println("name: " + user.getName() + "|age: " + user.getAge()); } finally { sqlSession.close(); } } public static void smain() { testAdd(); getUser(); } }
测试数据库脚本
CREATE DATABASE mybatis_test; CREATE TABLE user ( age INTEGER NOT NULL, name VARCHAR(64) NOT NULL DEFAULT '' ); insert user values(18,'zhanjindong'); insert user values(20,'zhangsan');
Eclipse 下Mybatis Xml的智能提示配置
1、下载 http://mybatis.org/dtd/mybatis-3-config.dtd对应的dtd文件放到本地;
2、在Eclipse中,Window——Preference——xml——xml catalog,进行add添加刚刚下载的dtd文件;
Key Type: Public ID
Key: -//mybatis.org//DTD Config 3.0//EN (根据自己的实际情况配置)
3、以Xml Edit的方式打开需要编写UserMapper.xml文件,即可使用智能提示功能;
参考博客
1、MyBatis使用示例 http://www.cnblogs.com/magialmoon/archive/2013/10/30/3397828.html
2、Java框架篇---Mybatis 入门 http://www.cnblogs.com/oumyye/p/4668721.html