Mybatis入门DEMO
下面将通过以下步骤说明如何使用MyBatis开发一个简单的DEMO:
步骤一:新建表STUDENTS
字段有: Stu_Id、Stu_Name、Stu_Age、Stu_Birthday
CREATE TABLE `student` (
`Stu_Id` bigint(20) NOT NULL AUTO_INCREMENT ,
`Stu_Name` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL ,
`Stu_Age` int(4) NULL DEFAULT NULL ,
`Stu_Birthday` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ,
PRIMARY KEY (`Stu_Id`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
AUTO_INCREMENT=1
;
步骤二:新建Maven项目,添加相关的依赖包
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
<scope>runtime</scope>
</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>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
步骤三:新建mybatis-config.xml 和映射器StudentMapper.xml配置文件
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 alias="Student" type="com.MyBatisDemo.domain.Student" />
</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:3306/mybatisdemo" />
<property name="username" value="root" />
<property name="password" value="123123" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/MyBatisDemo/mappers/StudentMapper.xml" />
</mappers>
</configuration>
StudentMapper.xml
<?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">
<mapper namespace="com.MyBatisDemo.mappers.StudentMapper">
<resultMap type="Student" id="StudentResult">
<id property="stuId" column="Stu_Id" />
<result property="StuName" column="Stu_Name" />
<result property="StuAge" column="Stu_Age" />
<result property="StuBirthday" column="Stu_Birthday" />
</resultMap> <select id="findStudentById" parameterType="int" resultType="Student">
SELECT Stu_Id, Stu_Name, Stu_Age, Stu_Birthday
FROM STUDENT WHERE Stu_Id=#{Id}
</select>
</mapper>
步骤四:新建建MyBatisSqlSessionFactory单例模式类
package com.MyBatisDemo.util; 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; public static SqlSessionFactory getSqlSessionFactory() {
if (sqlSessionFactory == null) {
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
}
return sqlSessionFactory;
} public static SqlSession openSession() {
return getSqlSessionFactory().openSession();
}
}
步骤五:新建映射器StudentMapper 接口和 StudentService 类
StudentMapper.java
package com.MyBatisDemo.mappers;
import com.MyBatisDemo.domain.Student;
public interface StudentMapper {
Student findStudentById(Integer id);
}
StudentService.java
package com.MyBatisDemo.service;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.MyBatisDemo.domain.Student;
import com.MyBatisDemo.mappers.StudentMapper;
import com.MyBatisDemo.util.MyBatisSqlSessionFactory; public class StudentService {
private Logger logger = LoggerFactory.getLogger(getClass()); public Student findStudentById(Integer studId)
{
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
try
{
StudentMapper studentMapper =
sqlSession.getMapper(StudentMapper.class);
return studentMapper.findStudentById(studId);
}
finally
{
sqlSession.close();
}
}
}
步骤六:新建一个JUnit 测试类来测试 StudentService
package com.MyBatisDemo; import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test; import com.MyBatisDemo.domain.Student;
import com.MyBatisDemo.service.StudentService;
public class StudentServiceTest
{
private static StudentService studentService;
@BeforeClass
public static void setup()
{
studentService = new StudentService();
}
@AfterClass
public static void teardown()
{
studentService = null;
} @Test
public void testFindStudentById()
{
Student student = studentService.findStudentById(1);
//Assert.assertNotNull(student);
System.out.println(student);
}
}
首先配置了MyBatis最主要的配置文件mybatis-config.xml,里面包含了JDBC连接参数;
配置了映射器Mapper XML配置文件文件,里面包含了SQL语句的映射。
使用mybatis-config.xml内的信息创建了SqlSessionFactory对象。每个数据库环境应该就一个SqlSessionFactory对象实例,所以使用了单例模式只创建一个SqlSessionFactory实例。
创建了一个映射器Mapper接口StudentMapper,其定义的方法签名和在StudentMapper.xml中定义的完全一样(即映射器Mapper接口中的方法名跟StudentMapper.xml中的id的值相同)。注意StudentMapper.xml中namespace的值被设置成com.MyBatisDemo.mappers.StudentMapper,是StudentMapper接口的完全限定名。这使我们可以使用接口来调用映射的SQL语句。
Mybatis入门DEMO的更多相关文章
- Mybatis入门Demo(单表的增删改查)
1.Mybatis 什么是Mybatis: mybatis是一个持久层框架,用java编写的 它封装了jdbc操作的很多细节,使开发者只需要关注sql语句本身,而无需关注注册驱动.创建连接等繁杂过程 ...
- 最基础的mybatis入门demo
demo结构 数据库情况 (不会转sql语句 骚瑞) 数据库连接信息 jdbc.properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:m ...
- MyBatis 入门Demo
新建数据库my_db,新建表student_tb id为主键,不自动递增. 不必插入数据. 下载MyBatis https://github.com/mybatis/mybatis-3/release ...
- Mybatis入门和简单Demo
一.Mybatis的诞生 回顾下传统的数据库开发,JDBC和Hibernate是使用最普遍的技术,但这两种ORM框架都存在一定的局限性: JDBC:最原生的技术,简单易学,执行速度快,效率高,适合大数 ...
- 【SSH系列】初识spring+入门demo
学习过了hibernate,也就是冬天,经过一个冬天的冬眠,当春风吹绿大地,万物复苏,我们迎来了spring,在前面的一系列博文中,小编介绍hibernate的相关知识,接下来的博文中,小编将继续介绍 ...
- netty入门demo(一)
目录 前言 正文 代码部分 服务端 客服端 测试结果一: 解决粘包,拆包的问题 总结 前言 最近做一个项目: 大概需求: 多个温度传感器不断向java服务发送温度数据,该传感器采用socket发送数据 ...
- SpringBoot 入门 Demo
SpringBoot 入门 Demo Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从 ...
- 写给新手看的 MyBatis 入门
目录 MyBatis 使用前的准备 什么是 MyBatis 使用Maven 进行 MyBatis 开发环境搭建 MyBatis 入门 项目整体结构一览 MyBatis 的简单生命周期 1.获取 Sql ...
- springboot + mybatisPlus 入门实例 入门demo
springboot + mybatisPlus 入门实例 入门demo 使用mybatisPlus的优势 集成mybatisplus后,简单的CRUD就不用写了,如果没有特别的sql,就可以不用ma ...
随机推荐
- javascript判断数组中是否包含某个元素
//判断数组array中是否包含元素obj的函数,包含则返回true,不包含则返回false function array_contain(array, obj){ for (var i = 0; i ...
- 理解Docker(7):Docker 存储 - AUFS
(1)Docker 安装及基本用法 (2)Docker 镜像 (3)Docker 容器的隔离性 - 使用 Linux namespace 隔离容器的运行环境 (4)Docker 容器的隔离性 - 使用 ...
- Selenium-java-XML启动用例类-简单1
最简单启动用例方法 1 先建立xml xml代码如下 <?xml version="1.0" encoding="UTF-8"?> <suit ...
- Android 6.0 运行时权限处理完全解析
一.概述 随着Android 6.0发布以及普及,我们开发者所要应对的主要就是新版本SDK带来的一些变化,首先关注的就是权限机制的变化.对于6.0的几个主要的变化,查看查看官网的这篇文章http:// ...
- 如何配置Linux系统的网络IP地址
一台安装了Linux系统的电脑如果想要联网,首先要做的就是进行网络配置.今天小编就以CentOS6.4系统为例为大家介绍整个网络配置的过程,虽然只是以CentOS6.4系统为例,但是其它的Linux系 ...
- MVC Nhibernate 示例
首先,非常感谢提出问题的朋友们,使得本人又去深入研究了NHibernate的<Session-Per-Request 模式>. 前言: 谈到NHibernate大伙并不陌生,搞Java ...
- Kinect for Windows SDK开发入门(十九):Kinect Fusion
Kinect for Windows SDK1.7中引入了Kinect Fusion功能.在1.8的SDK中对该功能进行了改进和强化,Kinect Fusion能够使得我们使用Kinect f ...
- ElasticSearch第四步-查询详解
ElasticSearch系列学习 ElasticSearch第一步-环境配置 ElasticSearch第二步-CRUD之Sense ElasticSearch第三步-中文分词 ElasticSea ...
- JS组件系列——又一款MVVM组件:Vue(一:30分钟搞定前端增删改查)
前言:关于Vue框架,好几个月之前就听说过,了解一项新技术之后,总是处于观望状态,一直在犹豫要不要系统学习下.正好最近有点空,就去官网了解了下,看上去还不错的一个组件,就抽空研究了下.最近园子里vue ...
- Codeforces Round #384(div 2)
A 题意:有n个机场处于一直线上,可两两到达,每个机场只可能属于两家公司中的一家(用0,1表示),现在要从a机场到b机场,可任意次转机.若机场i与机场j从属同一公司,则费用为0,否则费用为1.问最小费 ...