【Mybatis】MyBatis快速入门(一)
Mybatis简介
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
中文官网地址:http://www.mybatis.org/mybatis-3/zh/index.html
GitHub地址:https://github.com/mybatis/mybatis-3/tree/master/src/site
MyBatis入门
1、准备一个数据库,本例使用的是mysql数据库,建一张员工表(Employee),并且插入一条数据,sql如下:
-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`last_name` varchar(255) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of employee
-- ----------------------------
BEGIN;
INSERT INTO `employee` VALUES (1, 'test', '', 'test@163.com');
COMMIT;
2、新建一个Maven工程,引入mybatis依赖以及连接mysql数据库依赖
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency> <!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
3、添加Mybatis全局配置文件mybatis-config.xml,放在src/main/resources目录下,内容如下:
<?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/test_mybatis?allowPublicKeyRetrieval=true" />
<property name="username" value="admin" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 添加映射文件到Mybatis的全局配置文件中 -->
<mapper resource="mapper/EmployeeMapper.xml" />
</mappers>
</configuration>
4、添加映射文件EmployeeMapper.xml到src/main/resources/mapping目录下,内容如下:
<?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">
<!--
namespace:名称空间
id:唯一标识
resultType:返回值类型
#{id}:从传过来的参数中取出id值
-->
<mapper namespace="com.hd.test.mapper.EmployeeMapper">
<select id="getEmployeeById"
resultType="com.hd.test.pojo.Employee">
select id, last_name lastName, gender, email from employee where id =
#{id}
</select>
</mapper>
5、定义一个Java类Employee.java
package com.hd.test.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 + "]";
} }
8、一定一个测试Mybatis的Java类TestMybatis.java
package com.hd.test.mybatis; import java.io.IOException;
import java.io.InputStream; 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 com.hd.test.pojo.Employee; public class TestMybatis { @Test
public void test() throws IOException {
// 1、根据mybatis全局配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
// 使用MyBatis提供的Resources类加载mybatis的配置文件,获取输入流
InputStream inputStream = Resources.getResourceAsStream(resource);
// 构建sqlSession的工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 2、从SqlSession工厂中,获取sqlsession,用来执行sql
SqlSession session = sqlSessionFactory.openSession();
try {
// 查询selectOne
// @param statement Unique identifier matching the statement to use. 一个唯一标识
// @param parameter A parameter object to pass to the statement. 参数
Employee employee = (Employee) session.selectOne("com.hd.test.mapper.EmployeeMapper.getEmployeeById", 1);
// 输出信息
System.out.println(employee);
} finally {
// 关闭session
session.close();
}
} }
8、junit测试方法,输出结果:
接口式编程
1、在上例的基础上编写一个Java接口EmployeeMapper
package com.hd.test.mapper; import com.hd.test.pojo.Employee; public interface EmployeeMapper { public Employee getEmployeeById(Integer id); }
注意,sql配置文件要与接口一一对应
2、编辑测试方法内容如下:
@Test
public void test() throws IOException {
// 1、根据mybatis全局配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
// 使用MyBatis提供的Resources类加载mybatis的配置文件,获取输入流
InputStream inputStream = Resources.getResourceAsStream(resource);
// 构建sqlSession的工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 2、从SqlSession工厂中,获取sqlsession,用来执行sql
SqlSession session = sqlSessionFactory.openSession();
try {
// 3、获取接口的实现对象
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmployeeById(1);
// 输出信息
System.out.println(mapper);
System.out.println(employee);
} finally {
// 关闭session
session.close();
}
}
3、junit测试方法,输出结果:
【Mybatis】MyBatis快速入门(一)的更多相关文章
- mybatis框架快速入门
通过快速入门示例,我们发现使用mybatis 是非常容易的一件事情,因为只需要编写 Dao 接口并且按照 mybatis要求编写两个配置文件,就可以实现功能.远比我们之前的jdbc方便多了.(我们使用 ...
- MyBatis(1)——快速入门
MyBatis 简介 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为 ...
- (转) MyBatis(1)——快速入门
MyBatis 简介 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为 ...
- mybatis的快速入门
说明: 在这个部分,会写个简单的入门案例. 然后,会重新写一个,更加严格的程序案例. 一:案例一 1.最终的目录结构 2.新建一个普通的Java项目,并新建lib 在项目名上右键,不是src. 3.导 ...
- spring3.0+mybatis+spring快速入门
一.首先奉上项目目录结构: 说明: dao,mapping,model包下的所有内容可以使用Generator工具自助生成. 具体用法,可以网上学习一下,比较简单,主要做以下工作: 1.提供相关的数据 ...
- MyBatis框架——快速入门
主流的ORM框架(帮助开发者实现数据持久化工作的框架): 1.MyBatis: 半自动化ORM框架,半自动:指框架只完成一部分功能,剩下的工作仍需开发者手动完成. MyBatis 框架没有实现 POJ ...
- Mybatis框架 的快速入门
MyBatis 简介 什么是 MyBatis? MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架.MyBatis 消除 了几乎所有的 JDBC 代码和参数的手工设置以及结果 ...
- MyBatis学习总结(一)——MyBatis快速入门
一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以 ...
- MyBatis快速入门
一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以 ...
- MyBatis学习总结(一)——MyBatis快速入门(转载)
本文转载自http://www.cnblogs.com/jpf-java/p/6013537.html MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了 ...
随机推荐
- centos7如何使用yum命令
参照https://www.cnblogs.com/zhongguiyao/p/9029922.html 参照https://blog.csdn.net/shuaigexiaobo/article/d ...
- ffmpeg 编译
下载FFmpeg git clone https://git.ffmpeg.org/ffmpeg.git 配置编译FFmpeg ./configure --prefix=host --enable-s ...
- ie和dom事件流的区别
1.事件流的区别 IE采用冒泡型事件 Netscape使用捕获型事件 DOM使用先捕获后冒泡型事件 示例: 复制代码代码如下: <body> <div> <button& ...
- SpringMVC 启动流程
首先看一下Web应用部署初始化过程 (Web Application Deployement),官方文档说明: Web Application Deployment When a web applic ...
- xlrd 和xlwt 对Excel的操作
xlrd与xlwt库的异同点对比 相同点 都支持对Excel文件格式为xls的文件进行操作 不同点 xlrd只支持对Excel文件格式为xls文件的读取 xlwt只支持对Excel文件格式为xls文件 ...
- DRF框架简介(第一天)
1.drf框架全称 djangorestframework 1.如何安装drf框架: pip3 install djangorestframework #drf框架其实就是一个app称之为drf #d ...
- Eclipse 安装中文简体语言包
Installing the language packs Open the install wizard with 'Help' > 'Install new software...' Add ...
- Java入门到精通第4版汇总
- mysql数据库中指定值在所有表中所有字段中的替换
MySQL数据库: 指定值在数据库中所有表所有字段值的替换(存储过程): 1.写一个存储过程,查指定数据库中所有的表名: CREATE PROCEDURE init_replace(in orig_s ...
- install oracle 12c on redhat
---恢复内容开始--- 1. 确定VM的硬盘空间是否够 df- h, 硬盘空间free disk 15G 比较稳妥 2. 确定好网络,需要remote connect ifconfig 3. ...