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的事物的做法,本文的目的是在这个的基 ...
随机推荐
- 11235 - Frequent values
<算法竞赛入门经典-训练指南>P198 记录一下区间的左右边界就可以了 #include <iostream> #include <stack> #include ...
- python的sys.path
python检测不到模块: No module named 是因为模块没有在sys.path中,查看sys.path的方法 import sys sys.path 发现确实没有加载到模块. windo ...
- JS基础DOM篇之二:DOM级别与节点层次?
通过上一篇我们大致了解了什么是DOM,今天我们继续深入了解. 1.DOM级别 在大家阅读DOM标准的时候,可能会看到DOM(0/1/2/3)级的字眼,这就是DOM级别.但实际上,DOM0级 ...
- 解决mysql导入导出数据乱码问题
最近在linux上面用mysqldump导出数据,放在windows系统中导入就会出现中文乱码,然后就会导致出现: Unknown MySQL server host和Can't connect to ...
- 利用AssetsManager实现在线更新脚本文件lua、js、图片等资源(免去平台审核周期)
转自:http://www.himigame.com/iphone-cocos2dx/1354.html 首先说明一个问题: 为什么要在线更新资源和脚本文件!? 对于此问题,那要说的太多了,简单概括, ...
- 解决ccSvcHst.exe CPU占用超50%的问题,及其缘由
无意中发现任务管理器中一个非常奇特的进程,迅速吃掉了我50%的cpu资源,并且是持续性的,于是上google一番查找,终于有了新的发现. 非常多问答产品所有都是清一色的 错误解决方式: 正常情况下,系 ...
- C#用天气预报的WebServices
后台代码: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { WeatherWS ws = new W ...
- [IOS]自定义长触屏事件
写一个Demo来自定义一个长触屏事件,自定义长按手势. 实现步骤: 1.创建一个自定义手势类,命名为LongPressGestureRecognizer,在创建的时候继承UIGestureRecogn ...
- Android之使用AchartEngineActivity引擎绘制柱状图、曲线图
1.简介 AChartEngine(简称ACE)是Google的一个开源图表库(for Android).它功能强大,支持散点图.折线 .关于里面类的具体使用,请下载响应的文档说明(主页上有). 2. ...
- perl 变量详解
http://www.perlmonks.org/?node_id=933450 use strict; use Devel::Peek; my $a; Dump($a); $a=4; Dump($a ...