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的事物的做法,本文的目的是在这个的基 ...
随机推荐
- UIButton上使用UIEdgeInsetsMake让title跟图片对齐
UIButton上使用UIEdgeInsetsMake让title跟图片对齐 默认情况下,不设置的效果,都使居中现实,button为150*150 使用以下设置后: [self setTitleE ...
- POJ 3259 Wormholes(SPFA判负环)
题目链接:http://poj.org/problem?id=3259 题目大意是给你n个点,m条双向边,w条负权单向边.问你是否有负环(虫洞). 这个就是spfa判负环的模版题,中间的cnt数组就是 ...
- SGU 171 Sarov zones (贪心)
题目 SGU 171 相当好的贪心的题目!!!!! 题目意思就是说有K个赛区招收参赛队员,每个地区招收N[i]个,然后每个地区都有一个Q值,而N[i]的和就是N,表示总有N个参赛队员,每个队员都有 ...
- hashCode()和equals()的用法
使用hashCode()和equals() hashCode()和equals()定义在Object类中,这个类是所有java类的基类,所以所有的java类都继承这两个方法. hashCode()方法 ...
- SQLserver锁和事务隔离级别的比较与使用(转)
SQLserver锁和事务隔离级别的比较与使用(转) http://www.cnblogs.com/chenlulouis/archive/2010/12/06/1898014.html http:/ ...
- 《解剖PetShop》系列转载
1 <解剖PetShop>系列之六 PetShop之表示层设计 http://ityup.com/showtopic-8.html 2 <解剖PetShop>系列之五 ...
- Java二维码登录流程实现(包含短地址生成,含部分代码)
近年来,二维码的使用越来越风生水起,笔者最近手头也遇到了一个需要使用二维码扫码登录网站的活,所以研究了一下这一套机制,并用代码实现了整个流程,接下来就和大家聊聊二维码登录及的那些事儿. 二维码原理 二 ...
- ADO.NET 快速入门(二):执行命令
Commands发出针对数据库的数据存储动作.例如,你可以执行一条命令插入或者删除数据.获取更多从数据库移动数据相关的信息,请参考“Update a Database from a DataSet”. ...
- Codeforces Gym 100513D D. Data Center 前缀和 排序
D. Data Center Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/560/proble ...
- 图形化OpenGL调试器 BuGLe [转]
BuGLe 结合图形化的OpenGL调试与选择的过滤器上的OpenGL命令流.调试器可以查看状态.纹理.framebuffers ,着色器,而过滤器允许日志,错误检查,自由相机控制,视频捕捉等. 主页 ...