MyBatis 3
MyBatis 3 学习笔记
1.MyBatis 3编写步骤:
- 根据mybatis-config.xml配置文件创建一个SqlSessionFactory对象。
- sql映射文件,配置了每一个sql,以及sql的封装规则
- 将sql映射文件注册到全局配置文件mybatis-config.xml中
- 写代码:
- 根据全局配置文件得到SqlSessionFactory
- 从SqlSessionFactory中获取SqlSession对象,使用它来做增删改查。一个SqlSession就代表和数据额 库的一次会话,用完要关闭
- 使用sql标识来告诉mybatis执行那个sql。sql都是保存在SQL映射文件中的。
mybatis-config.xml 文件 <!-- 将我们写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 --> <mappers> <mapper resource="EmployeeMapper.xml" /> </mappers> </configuration>
//1.通过配置文件创建一个sqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取SqlSession实例,能直接执行已经映射的SQL语句 SqlSession openSession = sqlSessionFactory.openSession(); //3.参数一:statement唯一标识,参数二:传入sql变量 try { Employee employee = openSession.selectOne("cn.guet.bean.EmployeeMapper.selectEmployee", 1); System.out.println(employee); }catch (Exception e){ e.printStackTrace(); }finally { openSession.close(); }
SQL映射文件: <mapper namespace="cn.guet.bean.EmployeeMapper"> <!-- namespace:名称空间;指定为接口的全类名 id:唯一标识 resultType:返回值类型 #{id}:从传递过来的参数中取出id值 public Employee getEmpById(Integer id); --> <select id="selectEmployee" resultType="cn.guet.bean.Employee"> select id,last_name lastName,email,gender from tb1_employee where id = #{id} </select> </mapper>
2.MyBatis 3 接口式编程中,在进行接口和SQL的动态绑定时,SQL映射文件中的namespace指定为mapper接口的全限定名,映射文件中的id 指定为接口的中方法。动态绑定以后,不用再写mapper的实现类。mybatis会为我们自动创建一个代理对象,代理对象去执行增删改查的方法。
3.接口式编程: 原生 Dao ==> DaoImpl; mybatis: Mapper ==> xxxMapper.xml
4.Configuration,mybatis-config.xml 的配置
- properties标签,用来引入 jdbc文件。
<!--配置数据源信息-->
<properties resource="jdbc.properties"></properties>
- settings设置标签,用来设置各种信息。如下划线转驼峰标识。
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
- typeAliases别名标签。mybatis中的别名处理器。给Java type 一个短一点简单一点的别名,以后xml文件引用式直接用别名。
<!--typeAliases别名处理器,可以为Java类型取别名-->
<typeAliases>
<!--typeAlias为某个Java类型取别名。默认别名是类名小写employee-->
<!--<typeAlias type="cn.guet.bean.Employee" alias="emp"></typeAlias>-->
<!--批量取别名-->
<!--package为某个包下的所有类型批量起别名,name指定报名,为包以及包下面的所有类起默认别名(类名小写)-->
<package name="cn.guet.bean"/>
</typeAliases>
当使用批量起别名,且包里面有类名重复是,可以使用@Alias("xxx")指定别名
@Alias("emp")
public class Employee {
private Integer id;
private String lastName;
- typeHandlers类型处理器标签。Java类型和数据库类型映射的桥梁。
- plugins插件标签。插件可以拦截以下四大对象。
• Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
• ParameterHandler (getParameterObject, setParameters)
• ResultSetHandler (handleResultSets, handleOutputParameters)
• StatementHandler (prepare, parameterize, batch, update, query)

更多精彩