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的事物的做法,本文的目的是在这个的基 ...
随机推荐
- 内存映射文件详解-----C++实现
先不说内存映射文件是什么.贴个代码先,. #include <iostream> #include <fcntl.h> #include <io.h> #inclu ...
- [支付]微信NATIVE扫码支付JAVA实现
步骤: 1.预订单 2.接受微信返回的url 3.将url转为二维码显示到页面上 4.扫码支付 5.接收微信的异步通知,在这步修改订单的状态 6.收到异步通知的同时给微信返回指定数据,告知对方已成功处 ...
- 织梦dedecms后台添加图片style全部都变成st<x>yle的解决办法
可乐站长在建站的时候,上传缩略图喜欢输入图片路径,不喜欢上传图片,有几次我上传图片路径为:/style/image/**.jpg,然后返回修改后,图片为路径却为:/st<x>yle/ima ...
- myGeneration代码生成器
转自:http://www.cnblogs.com/leitwolf/archive/2007/07/27/833255.html http://blog.csdn.net/happyhippy/ar ...
- [IoC容器Unity] :Unity预览
1.引言 高内聚,低耦合成为一个OO架构设计的一个参考标准.高内聚是一个模块或者一个类中成员跟这个模块或者类的关系尽量高,低耦合是不同模块或者不同类之间关系尽量简单. 拿咱国家举例来说,假如你是中国人 ...
- 如何使用C#去灰度化一幅图像
灰度化一幅图像就是将图像的色彩信息全部丢掉,将24位的位图信息,用8位来表示,灰度图共有256级灰度等级,也就是将24位位图的一点如(255,255,255)转换成255,所以R,G,B三个值所乘的系 ...
- 在VB中利用Nuget包使用SQLite数据库和Linq to SQLite
上午解决了在C#中利用Nuget包使用SQLite数据库和Linq to SQLite,但是最后生成的是C#的cs类文件,对于我这熟悉VB而对C#白痴的来说怎么能行呢? 于是下午接着研究,既然生成的是 ...
- 从gitbook将书籍导入到github中
gitbook自己的导出工具经常出问题,可直接使用git. 从gitbook中clone下书 $ git clone https://git.gitbook.com/username/name_of_ ...
- windows服务控制类
/// <summary> /// 服务调用控制 /// </summary> public class WinServiceController { /// <summ ...
- flex-mp3
Mp3Player.as package ddw.adobe { import flash.events.Event; import flash.events.IOErrorEvent; import ...