JAVA就业套餐课:https://edu.csdn.net/combo/detail/1230
一:简介
MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。Mybatis通过xml或注解的方式将要执行的各种statement(statement、preparedStatemnt、CallableStatement)配置起来,并通过Java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回。
二:原理
三:环境搭建
1:开发jar包:
2.因为用到了sql数据库,所以导入sql jbr包
3.配置文件mybatisConfig.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="db.properties"/><environments default="development"> <environment id="development"> <transactionManager type="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="org/mybatis/example/dao/DeptMapper.xml"/> </mappers> </configuration>
因为采用的是外部文件 方式,所以,需要建立db.properties文件,文件内容如下:
driver=com.microsoft.sqlserver.jdbc.SQLServerDriverurl=jdbc:sqlserver://localhost:1433;DatabaseName=mydbusername=sapassword=1
4.Dept实体类
package org.mybatis.example.dao;public class Dept { private int deptno; private String dname; private String ioc; public Dept() { } public int getDeptno() { return deptno; } public void setDeptno(int deptno) { this.deptno = deptno; } public String getDname() { return dname; } public void setDname(String dname) { this.dname = dname; } public String getIoc() { return ioc; } public void setIoc(String ioc) { this.ioc = ioc; } }
5.创建Dept的映射文件DeptMapper.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="org.mybatis.example.dao.DeptMapper"> <select id="selectOne" parameterType="int" resultType="org.mybatis.example.dao.Dept"> select * from dept where deptno=#{id} </select> </mapper>
6.测试类Test.java
public class Test { public static void main(String[] args) throws IOException { String resource="mybatisConfig.xml"; Reader reader=Resources.getResourceAsReader(resource); SqlSessionFactory sqlMapper=new SqlSessionFactoryBuilder().build(reader); SqlSession session=sqlMapper.openSession(); try { Dept dept=session.selectOne("org.mybatis.example.dao.DeptMapper.selectOne",2); System.out.println(dept.getDname()); } catch (Exception e) { e.printStackTrace(); }finally{ session.close(); } }}
总体文件结构