Mybatis (一)
1 DAO层框架
- 框架:是一种整体的解决方案。
1.1 JDBC的步骤

1.2 Hibernate执行的步骤

1.3 MyBaits

2 Mybatis简介
- Mybatis是支持定制化SQL、存储过程以及高级映射的优秀的持久层框架。
- Mybatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。
- Mybatis可以使用简单的XML或者注解用于配置和原始映射,将接口和Java的POJO映射成数据库中的记录。
3 为什么需要Mybatis?
- Mybatis是一个半自动的持久层框架。
- JDBC
- SQL夹在Java代码中,耦合度高导致硬编码内伤。
- 维护不易且实际开发需求中SQL是有变化的,频繁修改的情况多见。
- Hibernate和JPA
- 长难复杂的SQL,对于Hibernate而言处理并不容易。
- 内部自动生成的SQL,不容易做优化处理。
- 基于全映射的全自动框架,大量字段的POJO进行部分映射的时候比较困难,导致数据库性能下降。
- 对于开发人员而言,核心SQL还是需要自己优化的。
- SQL和Java代码分开,功能边界清晰,一个专注业务,一个专注数据。
4 下载Mybatis
5 Mybatis之HelloWorld
5.1 编写SQL脚本
DROP DATABASE mybatis;
CREATE DATABASE mybatis;
USE mybatis;
DROP TABLE employee;
CREATE TABLE employee(
id INT PRIMARY KEY AUTO_INCREMENT,
last_name ),
gender ),
email )
);
INSERT INTO employee (last_name,gender,email) VALUES ('许威威','男','1975356467@qq.com');
5.2 创建javabean
- Employee.java
package com.xuweiwei.mybatis.pojo;
public class Employee {
private Integer id;
private String lastName;
private String gender;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
5.3 在src下加入log4j.properties文件
og4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout
5.4 在src下新建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>
<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="root"/>
</dataSource>
</environment>
</environments>
<mappers>
</mappers>
</configuration>
5.5 新建EmployeeMapper.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.xuweiwei.mybatis.pojo.Employee">
<select id="selectEmployeeById" resultType="com.xuweiwei.mybatis.pojo.Employee">
select id,last_name lastName,gender,email from employee where id = #{id}
</select>
</mapper>
5.6 将EmployeeMapper.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>
<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="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/xuweiwei/mybatis/mapper/EmployeeMapper.xml"/>
</mappers>
</configuration>
5.7 测试
package com.xuweiwei.mybatis.test;
import com.xuweiwei.mybatis.pojo.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class MybatisTest {
@Test
public void test() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
Employee employee = (Employee) session.selectOne("com.xuweiwei.mybatis.pojo.Employee.selectEmployeeById", 1);
System.out.println(employee);
} finally {
session.close();
}
}
}
6 接口编程
6.1 编写EmployeeMapper.java
package com.xuweiwei.mybatis.mapper;
import com.xuweiwei.mybatis.pojo.Employee;
public interface EmployeeMapper {
public Employee getEmployeeById(Integer id);
}
6.2 修改EmployeeMapper.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.xuweiwei.mybatis.mapper.EmployeeMapper">
<select id="getEmployeeById" resultType="com.xuweiwei.mybatis.pojo.Employee">
select id,last_name lastName,gender,email from employee where id = #{id}
</select>
</mapper>
6.3 测试
package com.xuweiwei.mybatis.test;
import com.xuweiwei.mybatis.mapper.EmployeeMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class MybatisTest {
@Test
public void test() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
System.out.println(employeeMapper.getEmployeeById(1));
} finally {
session.close();
}
}
}
7 SqlSession
- SqlSession的实例不是线程安全的,因此不能共享。
- SqlSession每次使用完之后必须正确的关闭。
8 全局配置文件
- 在全局配置文件中可以通过settings设置是否开启驼峰规则映射。
- Employee.java
package com.xuweiwei.mybatis.pojo;
public class Employee {
private Integer id;
private String lastName;
private String gender;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", gender='" + gender + '\'' +
", email='" + email + '\'' +
'}';
}
}
- 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>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<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="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/xuweiwei/mybatis/mapper/EmployeeMapper.xml"/>
</mappers>
</configuration>
- log4j.properties
og4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout
- EmployeeMapper.java
package com.xuweiwei.mybatis.mapper;
import com.xuweiwei.mybatis.pojo.Employee;
public interface EmployeeMapper {
public Employee getEmployeeById(Integer id);
}
- EmployeeMapper.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.xuweiwei.mybatis.mapper.EmployeeMapper">
<select id="getEmployeeById" resultType="com.xuweiwei.mybatis.pojo.Employee">
select id,last_name ,gender,email from employee where id = #{id}
</select>
</mapper>
- 测试
package com.xuweiwei.mybatis.test;
import com.xuweiwei.mybatis.mapper.EmployeeMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class MybatisTest {
@Test
public void test() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
System.out.println(employeeMapper.getEmployeeById(1));
} finally {
session.close();
}
}
}
Mybatis (一)的更多相关文章
- 【分享】标准springMVC+mybatis项目maven搭建最精简教程
文章由来:公司有个实习同学需要做毕业设计,不会搭建环境,我就代劳了,顺便分享给刚入门的小伙伴,我是自学的JAVA,所以我懂的.... (大图直接观看显示很模糊,请在图片上点击右键然后在新窗口打开看) ...
- Java MyBatis 插入数据库返回主键
最近在搞一个电商系统中由于业务需求,需要在插入一条产品信息后返回产品Id,刚开始遇到一些坑,这里做下笔记,以防今后忘记. 类似下面这段代码一样获取插入后的主键 User user = new User ...
- [原创]mybatis中整合ehcache缓存框架的使用
mybatis整合ehcache缓存框架的使用 mybaits的二级缓存是mapper范围级别,除了在SqlMapConfig.xml设置二级缓存的总开关,还要在具体的mapper.xml中开启二级缓 ...
- 【SSM框架】Spring + Springmvc + Mybatis 基本框架搭建集成教程
本文将讲解SSM框架的基本搭建集成,并有一个简单demo案例 说明:1.本文暂未使用maven集成,jar包需要手动导入. 2.本文为基础教程,大神切勿见笑. 3.如果对您学习有帮助,欢迎各种转载,注 ...
- mybatis plugins实现项目【全局】读写分离
在之前的文章中讲述过数据库主从同步和通过注解来为部分方法切换数据源实现读写分离 注解实现读写分离: http://www.cnblogs.com/xiaochangwei/p/4961807.html ...
- MyBatis基础入门--知识点总结
对原生态jdbc程序的问题总结 下面是一个传统的jdbc连接oracle数据库的标准代码: public static void main(String[] args) throws Exceptio ...
- Mybatis XML配置
Mybatis常用带有禁用缓存的XML配置 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ...
- MyBatis源码分析(一)开篇
源码学习的好处不用多说,Mybatis源码量少.逻辑简单,将写个系列文章来学习. SqlSession Mybatis的使用入口位于org.apache.ibatis.session包中的SqlSes ...
- (整理)MyBatis入门教程(一)
本文转载: http://www.cnblogs.com/hellokitty1/p/5216025.html#3591383 本人文笔不行,根据上面博客内容引导,自己整理了一些东西 首先给大家推荐几 ...
- MyBatis6:MyBatis集成Spring事物管理(下篇)
前言 前一篇文章<MyBatis5:MyBatis集成Spring事物管理(上篇)>复习了MyBatis的基本使用以及使用Spring管理MyBatis的事物的做法,本文的目的是在这个的基 ...
随机推荐
- wifipineapple插件:codeInject的使用
如果在中间人攻击的时候, 能在用户的网页中插入任意代码, 可以说已经完成一半了 wifipineapple有个codeInject插件, 可以让连上这个网络所有设备浏览网页的时候, 在网页中插入任意h ...
- assert断言
https://www.cnblogs.com/ggzss/archive/2011/08/18/2145017.html assert是一个宏定义,其作用是如果它的条件返回错误,则终止程序执行,原型 ...
- Nginx日常维护操作(3)
一.简明nginx常用命令 1. 启动 Nginx /sbin/nginx service nginx start 2. 停止 Nginx /sbin/nginx -s stop /sbi ...
- Django----->Ajax
一,前情回顾(Json) Json的定义: JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式.它基于 ECMAScript (w3c制定的 ...
- Linux下zeromq.js安装
本文章主要阐述在离线环境下安装zeromq.js的方法和步骤.zeromq.js下载地址: https://www.npmjs.com/package/zeromq或者 https://github. ...
- deeplearning.ai 人工智能行业大师访谈 Ruslan Salakhutdinov 听课笔记
Ruslan Salakhutdinov一方面是苹果的研究主管,另一方面是CMU的教授. 1. Ruslan说自己进入深度学习完全是运气,他在多伦多大学读硕士,然后休学了一年,他在金融领域工作,那时候 ...
- 学习SpirngMVC之如何获取请求参数
学习SpringMVC——如何获取请求参数 @RequestParam,你一定见过:@PathVariable,你肯定也知道:@QueryParam,你怎么会不晓得?!还有你熟悉的他(@Cooki ...
- 51 NOD 1238 最小公倍数之和 V3
原题链接 最近被51NOD的数论题各种刷……(NOI快到了我在干什么啊! 然后发现这题在网上找不到题解……那么既然A了就来骗一波访问量吧…… (然而并不怎么会用什么公式编辑器,写得丑也凑合着看吧…… ...
- 数位DP入门:(bzoj1833+3209)
//我是来看文章创建时间的= = 膜拜了一下蔡大神.... 人生第一道自己写的数位DP...好吧以前是看题解然后也不知道为什么就过了的>_< 虽然说现在还是只会裸题= = 数位DP介绍: ...
- [bzoj1774] [Usaco2009 Dec]Toll 过路费
Floyd神用法...设dis[i][j]表示i点到j点的最短路(只算边权),map[i][j]表示i到j最小费用 将n个点先按照点权排一下序...这样就可以比较方便的求出路径上最大点权了... 因为 ...