标签:
1、建立mybatis配置文件SqlMapConfig.xml(名称不唯一),它是mybatis的全局配置文件:
--配置数据源、事务等mybatis运行环境
--配置映射文件(配置sql语句)
--SqlMapConfig.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> <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://127.0.0.1:3306/test" /> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <!-- 加载映射文件 --> <mappers> <mapper resource="sqlmap/Customer.xml"/> </mappers> </configuration>
--映射文件Customer.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"> <!-- 命名空间:其作用是对sql进行分类管理 --> <mapper namespace="test"> <!-- 配置sql语句 通过select执行数据库查询: id标识映射文件中的sql parameterType为输入参数的类型; resultType为输出参数的Java对象类型 --> <select id="findCustomerById" parameterType="int" resultType="com.tt.po.Customer"> select * from customers where id=#{id} </select> </mapper>
2、创建会话工厂:SqlSessionFactory;
3、通过会话工厂产生SqlSession: new SqlSessionFactoryBuilder().build(inputStream);
--SqlSession内部通过执行器Executor操作数据库
--底层封装对象: mapped statement,对数据库存储封装,包括sql语句、输入参数、输出参数;
public void mybatisTest(){ //mybatis的配置文件 String resource = "SqlMapConfig.xml"; SqlSession sqlSession = null; try { InputStream inputStream = Resources.getResourceAsStream(resource); //通过工厂创建SqlSession SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //创建会话工厂 sqlSession = sqlSessionFactory.openSession(); //通过SqlSession操作数据库 Customer customer = sqlSession.selectOne("test.findCustomerById", 1); System.out.println(customer); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //释放资源,关闭SqlSession sqlSession.close(); } }
4、mybatis工程结构:
标签:
原文地址:http://www.cnblogs.com/tengtao93/p/5105714.html