Mybatis入门DEMO

下面将通过以下步骤说明如何使用MyBatis开发一个简单的DEMO:

步骤一:新建表STUDENTS

  字段有: Stu_Id、Stu_Name、Stu_Age、Stu_Birthday

 1 CREATE TABLE `student` (
 2 `Stu_Id`  bigint(20) NOT NULL AUTO_INCREMENT ,
 3 `Stu_Name`  varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL ,
 4 `Stu_Age`  int(4) NULL DEFAULT NULL ,
 5 `Stu_Birthday`  timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ,
 6 PRIMARY KEY (`Stu_Id`)
 7 )
 8 ENGINE=InnoDB
 9 DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
10 AUTO_INCREMENT=1
11 ;

步骤二:新建Maven项目,添加相关的依赖包

 1 <dependencies>
 2   <dependency>
 3     <groupId>org.mybatis</groupId>
 4     <artifactId>mybatis</artifactId>
 5     <version>3.2.2</version>
 6   </dependency>
 7   <dependency>
 8     <groupId>mysql</groupId>
 9     <artifactId>mysql-connector-java</artifactId>
10     <version>5.1.22</version>
11     <scope>runtime</scope>
12   </dependency>
13   <dependency>
14     <groupId>org.slf4j</groupId>
15     <artifactId>slf4j-api</artifactId>
16     <version>1.7.5</version>
17   </dependency>
18   <dependency>
19     <groupId>org.slf4j</groupId>
20     <artifactId>slf4j-log4j12</artifactId>
21     <version>1.7.5</version>
22     <scope>runtime</scope>
23   </dependency>
24   <dependency>
25     <groupId>log4j</groupId>
26     <artifactId>log4j</artifactId>
27     <version>1.2.17</version>
28     <scope>runtime</scope>
29   </dependency>
30   <dependency>
31     <groupId>junit</groupId>
32     <artifactId>junit</artifactId>
33     <version>4.11</version>
34     <scope>test</scope>
35   </dependency>
36 </dependencies>

步骤三:新建mybatis-config.xml 和映射器StudentMapper.xml配置文件

mybatis-config.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 4 <configuration>
 5   <typeAliases>
 6     <typeAlias alias="Student" type="com.MyBatisDemo.domain.Student" />
 7   </typeAliases>
 8   <environments default="development">
 9     <environment id="development">
10       <transactionManager type="JDBC" />
11       <dataSource type="POOLED">
12         <property name="driver" value="com.mysql.jdbc.Driver" />
13         <property name="url" value="jdbc:mysql://localhost:3306/mybatisdemo" />
14         <property name="username" value="root" />
15         <property name="password" value="123123" />
16       </dataSource>
17     </environment>
18   </environments>
19   <mappers>
20     <mapper resource="com/MyBatisDemo/mappers/StudentMapper.xml" />
21   </mappers>
22 </configuration>

StudentMapper.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4 <mapper namespace="com.MyBatisDemo.mappers.StudentMapper">
 5   <resultMap type="Student" id="StudentResult">
 6     <id property="stuId" column="Stu_Id" />
 7     <result property="StuName" column="Stu_Name" />
 8     <result property="StuAge" column="Stu_Age" />
 9     <result property="StuBirthday" column="Stu_Birthday" />
10   </resultMap>
11
12   <select id="findStudentById" parameterType="int" resultType="Student">
13      SELECT Stu_Id, Stu_Name, Stu_Age, Stu_Birthday
14          FROM STUDENT WHERE Stu_Id=#{Id}
15   </select>
16 </mapper>

步骤四:新建建MyBatisSqlSessionFactory单例模式类

 1 package com.MyBatisDemo.util;
 2
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5
 6 import org.apache.ibatis.io.Resources;
 7 import org.apache.ibatis.session.SqlSession;
 8 import org.apache.ibatis.session.SqlSessionFactory;
 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
10
11 public class MyBatisSqlSessionFactory {
12     private static SqlSessionFactory sqlSessionFactory;
13
14     public static SqlSessionFactory getSqlSessionFactory() {
15         if (sqlSessionFactory == null) {
16             InputStream inputStream;
17             try {
18                 inputStream = Resources.getResourceAsStream("mybatis-config.xml");
19                 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
20             } catch (IOException e) {
21                 e.printStackTrace();
22                 throw new RuntimeException(e.getCause());
23             }
24         }
25         return sqlSessionFactory;
26     }
27
28     public static SqlSession openSession() {
29         return getSqlSessionFactory().openSession();
30     }
31 }

步骤五:新建映射器StudentMapper 接口和 StudentService 类

StudentMapper.java

1 package com.MyBatisDemo.mappers;
2
3 import com.MyBatisDemo.domain.Student;
4
5 public interface StudentMapper {
6     Student findStudentById(Integer id);
7 }

StudentService.java

 1 package com.MyBatisDemo.service;
 2 import org.apache.ibatis.session.SqlSession;
 3 import org.slf4j.Logger;
 4 import org.slf4j.LoggerFactory;
 5
 6 import com.MyBatisDemo.domain.Student;
 7 import com.MyBatisDemo.mappers.StudentMapper;
 8 import com.MyBatisDemo.util.MyBatisSqlSessionFactory;
 9
10 public class StudentService {
11     private Logger logger = LoggerFactory.getLogger(getClass());
12
13     public Student findStudentById(Integer studId)
14     {
15         SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
16         try
17         {
18             StudentMapper studentMapper =
19                 sqlSession.getMapper(StudentMapper.class);
20             return studentMapper.findStudentById(studId);
21         }
22         finally
23         {
24             sqlSession.close();
25         }
26     }
27 }

步骤六:新建一个JUnit 测试类来测试 StudentService

 1 package com.MyBatisDemo;
 2
 3 import org.junit.AfterClass;
 4 import org.junit.BeforeClass;
 5 import org.junit.Test;
 6
 7 import com.MyBatisDemo.domain.Student;
 8 import com.MyBatisDemo.service.StudentService;
 9 public class StudentServiceTest
10 {
11     private static StudentService studentService;
12     @BeforeClass
13     public static void setup()
14     {
15         studentService = new StudentService();
16     }
17     @AfterClass
18     public static void teardown()
19     {
20         studentService = null;
21     }
22
23     @Test
24     public void testFindStudentById()
25     {
26         Student student = studentService.findStudentById(1);
27         //Assert.assertNotNull(student);
28         System.out.println(student);
29     }
30 }

首先配置了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语句。

时间: 2024-07-30 10:11:34

Mybatis入门DEMO的相关文章

最基础的mybatis入门demo

demo结构 数据库情况 (不会转sql语句 骚瑞) 数据库连接信息 jdbc.properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mysql_demo jdbc.username=root jdbc.password=root javabean Student.class package entity; public class Student { private Integer i

Mybatis 3.2.7 简单入门Demo

对最新版本 Mybatis 3.2.7 做了一个demo,做个记录 需要的基本jar: mybatis-3.2.7.jar mysql-connector-java-5.1.27.jar 首先配置xml文件 mybatis-config.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config

mybaits入门demo配置文件详解(二)

第一篇文章: mybaits开发环境准备及入门demo(一) 一.配置文件mybatis-config.xml 官方是这么说的:MyBatis 的配置文件包含了影响 MyBatis 行为甚深的设置(settings)和属性(properties)信息 在MyBatis 的配置文件中 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//myba

mybaits入门demo映射文件详解(三)

第二篇文章:  mybaits入门demo配置文件详解(二) Mapper XML 文件 MyBatis 的真正强大在于它的映射语句,也是它的魔力所在.由于它的异常强大,映射器的 XML 文件就显得相对简单.如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉了将近 95% 的代码.MyBatis 就是针对 SQL 构建的,并且比普通的方法做的更好. SQL 映射文件有很少的几个顶级元素(按照它们应该被定义的顺序): cache – 给定命名空间的缓存配置. cache-ref –

SpringBoot 入门 Demo

SpringBoot   入门 Demo Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者. 特点 1. 创建独立的Spring应用程序 2. 嵌入的Tomcat,无需部署WAR文件 3. 简化Maven配置

MyBatis1:MyBatis入门

MyBatis是什么 MyBatis是什么,MyBatis的jar包中有它的官方文档,文档是这么描述MyBatis的: MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of para

MyBatis入门基础(一)

一:对原生态JDBC问题的总结 新项目要使用mybatis作为持久层框架,由于本人之前一直使用的Hibernate,对mybatis的用法实在欠缺,最近几天计划把mybatis学习一哈,特将学习笔记记录于此,方便大家参考,也方便自己查阅. 话不多说,先看看原始的JDBC程序代码,看看这样的代码存在什么问题. package com.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.P

MyBatis的demo

把以前写的关于mybatis的demo放在这边,以便查看. 目录结构: 1 package com.test.mybatis.util; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 6 import org.apache.ibatis.io.Resources; 7 import org.apache.ibatis.session.SqlSession; 8 import org.apache.ibatis.se

mybatis入门学习之(1)+简单例子测试

Mybatis 入门之(1)环境配置+简单例子测试 什么是MyBatis? 它是支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索.MyBatis 使用简单的XML或注解用于配置和原始映射,将接口和POJOs(Plan Old Java Objects,普通的 Java对象)映射成数据库中的记录. 其实简单一点说mybatis就是一直访问数据库的技术,它是现在比较流行的一个持久层框架,如果你对JDBC熟悉那就更容易