MyBatis(3.2.3) - hello world
1. 创建数据表(MySQL):
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`did` int(10) unsigned NOT NULL AUTO_INCREMENT,
`dept_name` varchar(127) DEFAULT NULL,
`address` varchar(127) DEFAULT NULL,
`tel` varchar(16) DEFAULT NULL,
PRIMARY KEY (`did`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2. 新建 Maven 工程,配置 Maven 依赖:
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.14.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
</dependency>
</dependencies>
3. JavaBean:
package com.huey.hello.mybatis.beans; import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor; @Data
@NoArgsConstructor
@AllArgsConstructor
public class Department {
private int did;
private String deptName;
private String address;
private String tel;
}
3. Mapper 接口:
package com.huey.hello.mybatis.mapper; import com.huey.hello.mybatis.beans.Department; public interface DepartmentMapper { public int insertDepartment(Department department); public Department getDepartmentById(int did); }
4. 配置映射文件:
<?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"> <!--注意:此处的命名空间是 DepartmentMapper 的全限定类名-->
<mapper namespace="com.huey.hello.mybatis.mapper.DepartmentMapper"> <!-- ResultMaps 被用来将 SQL SELECT 语句的结果集映射到 JavaBean 的属性中 -->
<resultMap type="Department" id="deptMap">
<!-- 映射主键 -->
<id property="did" column="did" />
<!-- 映射普通字段 -->
<result property="deptName" column="dept_name"/>
<result property="address" column="address"/>
<result property="tel" column="tel"/>
</resultMap> <!-- 添加部门记录 -->
<!-- id 名称需要与 DepartmentMapper 中的方法签名一致 -->
<!-- Department 这一别名在 mybatis-config.xml 中配置 -->
<insert id="insertDepartment" parameterType="Department">
insert into department(did, dept_name, address, tel)
values(#{did}, #{deptName}, #{address}, #{tel})
</insert> <!-- 根据 ID 查询部门记录 -->
<select id="getDepartmentById" parameterType="int" resultMap="deptMap">
select * from department where did=#{did}
</select> </mapper>
5. 配置 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> <!-- 设置别名 -->
<typeAliases>
<typeAlias type="com.huey.hello.mybatis.beans.Department" alias="Department" />
</typeAliases> <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/mybatis" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments> <!-- mapper 对应的 xml 配置文件 -->
<mappers>
<mapper resource="com/huey/hello/mybatis/mapper/DepartmentMapper.xml" />
</mappers> </configuration>
6. 创建 SqlSessionFactory 单例类:
package com.huey.hello.mybatis.utils; 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; public class MyBatisSqlSessionFactory { private static SqlSessionFactory sqlSessionFactory; /**
* 加载 mybatis-config.xml,创建 SqlSessionFactory 实例
* 每个数据库环境应该就只有一个 SqlSessionFactory 对象实例
* 所以使用单例模式只创建一个 SqlSessionFactory 实例
* @return
*/
public synchronized static SqlSessionFactory getSqlSessionFactory() {
if (sqlSessionFactory == null) {
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e.getCause());
}
}
return sqlSessionFactory;
} public static SqlSession openSqlSession() {
return getSqlSessionFactory().openSession();
}
}
7. 业务逻辑:
package com.huey.hello.mybatis.serv; import org.apache.ibatis.session.SqlSession; import com.huey.hello.mybatis.beans.Department;
import com.huey.hello.mybatis.mapper.DepartmentMapper;
import com.huey.hello.mybatis.utils.MyBatisSqlSessionFactory; public class DepartmentService { public int createDepartment(Department department) {
int result = 0;
/**
* SqlSession 对象实例不是线程安全的,并且不被共享。
* 每一个线程应该有它自己的 SqlSession 实例。
* 所以 SqlSession 的作用域最好就是其所在方法的作用域。
* 从 Web 应用程序角度上看,SqlSession 应该存在于 request 级别作用域上。
*/
SqlSession sqlSession = MyBatisSqlSessionFactory.openSqlSession();
try {
DepartmentMapper deptMapper = sqlSession.getMapper(DepartmentMapper.class);
result = deptMapper.insertDepartment(department);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
return result;
} public Department getDepartmentById(int did) {
Department department = null;
SqlSession sqlSession = MyBatisSqlSessionFactory.openSqlSession();
try {
DepartmentMapper deptMapper = sqlSession.getMapper(DepartmentMapper.class);
department = deptMapper.getDepartmentById(did);
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
return department;
} }
8. 单元测试:
package com.huey.hello.mybatis.serv; import org.junit.Test; import com.huey.hello.mybatis.beans.Department; public class DepartmentServiceTest { DepartmentService deptService = new DepartmentService(); @Test
public void testCreateDepartment() {
Department department = new Department(1001, "研发部", "XX 路 YY 号", "010-55551234");
deptService.createDepartment(department);
} @Test
public void testGetDepartmentById() throws Exception {
int did = 1001;
Department department = deptService.getDepartmentById(did);
if (department != null) {
System.out.println(department);
}
} }
MyBatis(3.2.3) - hello world的更多相关文章
- 【分享】标准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的事物的做法,本文的目的是在这个的基 ...
随机推荐
- hdu2248
纷菲幻剑录 之 十年一剑 Time Limit: 10000/4000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) To ...
- 框架学习笔记:Unity3D的MVC框架——StrangeIoC
作为从AS3页游走过来的人,看见StrangeIoC会额外亲切,因为StrangeIoC的设计和RobotLegs几乎一致,作为一款依赖注入/控制反转(IoC)的MVC框架,StrangeIoC除了使 ...
- (转)WordPress的主查询函数-query_posts()
今天说说WordPress 的主查询函数 -query_posts(),因为我正在制作的主题里面多次用到了这个函数 . query_posts()查询函数决定了哪些文章出现在WordPress 主 循 ...
- PHP之路,Day1 - PHP基础
本节内容 1.PHP介绍 2.第一个PHP脚本程序 3.PHP语言标记 4.指令分割符 5.程序注释 6.在程序中使用空白符的处理 7.变量 8.变量的类型 9.数据类型之间相互转换 ...
- 大一下C#五子棋大作业
上学期的作业,从0开始,到会写C#界面,再到设计出AI对战,跟队友一起用了半个学期的时间,现在才过了几个月就感觉有些遗忘了,赶紧来总结一下. 先上文件吧:程序+源代码 编译环境VS2013 百度云的分 ...
- Exchange模式功能
Exchange模式: Outlook中的投票功能: 新建邮件--选项--使用投票按钮
- Codeforces Beta Round #51 B. Smallest number dfs
B. Smallest number Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/55/pro ...
- Codeforces Round #185 (Div. 2) C. The Closest Pair 构造
C. The Closest Pair Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/312/p ...
- C++赋值运算符函数
为类添加赋值运算符函数: 类型定义 class CMyString { public: CMyString(char *pData = NULL); CMyString(const CMyString ...
- SQL SERVER 中identity用法
在数据库中, 常用的一个流水编号通常会使用 identity 栏位来进行设置, 这种编号的好处是一定不会重覆, 而且一定是唯一的, 这对table中的唯一值特性很重要, 通常用来做客户编号, 订单编号 ...