首页 > 代码库 > 初识mybatis之入门案例

初识mybatis之入门案例

我也是自学了一下,在idea中基于maven的mybatis的配置。有什么不对的地方,请指正,谢谢。

 

1.1咋们先来配置测试一下,配置mybatis的图解

技术分享

 

1.2 pom.xml需要mybatis的依赖节点,节点如下:

技术分享
 1 <dependencies>
 2     <dependency>
 3         <groupId>org.mybatis</groupId>
 4         <artifactId>mybatis</artifactId>
 5         <version>3.3.0</version>
 6     </dependency>
 7     <dependency>
 8         <groupId>mysql</groupId>
 9         <artifactId>mysql-connector-java</artifactId>
10         <version>5.1.29</version>
11     </dependency>
12     <dependency>
13         <groupId>junit</groupId>
14         <artifactId>junit</artifactId>
15         <version>4.12   </version>
16         <scope>test</scope>
17     </dependency>
18     <dependency>
19         <groupId>log4j</groupId>
20         <artifactId>log4j</artifactId>
21         <version>1.2.17</version>
22     </dependency>
23     <dependency>
24         <groupId>org.slf4j</groupId>
25         <artifactId>slf4j-api</artifactId>
26         <version>1.7.12</version>
27     </dependency>
28     <dependency>
29         <groupId>org.slf4j</groupId>
30         <artifactId>slf4j-log4j12</artifactId>
31         <version>1.7.12</version>
32     </dependency>
33 </dependencies>
节点

 

1.3创建数据库脚本:(MySQL数据库、数据库叫mybatis

 

技术分享
 1 /*
 2 SQLyog v10.2 
 3 MySQL - 5.7.12-log : Database - mybatis
 4 *********************************************************************
 5 */
 6 /*!40101 SET NAMES utf8 */;
 7 /*!40101 SET SQL_MODE=‘‘*/;
 8 /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
 9 /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=‘NO_AUTO_VALUE_ON_ZERO‘ */;
10 /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
11 /*Table structure for table `person` */
12 CREATE TABLE `person` (
13 `ID` int(11) DEFAULT NULL,
14 `USERNAME` varchar(30) DEFAULT NULL,
15 `AGE` int(11) DEFAULT NULL,
16 `MOBiLEPHONE` varchar(30) DEFAULT NULL
17 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
18 /*Data for the table `person` */
19 insert  into `person`(`ID`,`USERNAME`,`AGE`,`MOBiLEPHONE`) values (1,神奇,18,1361165680);
20 /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
21 /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
22 /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
数据库脚本

 

 

1.4 MybatisUtil 创建工具类

 

技术分享
 1 package utils;
 2 import org.apache.ibatis.io.Resources;
 3 import org.apache.ibatis.session.SqlSession;
 4 import org.apache.ibatis.session.SqlSessionFactory;
 5 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 6 import java.io.IOException;
 7 import java.io.Reader;
 8 /**
 9  * Created by 123 on 2017/06/29.
10  */
11 public class MybatisUtil {
12     private final  static SqlSessionFactory sqlSessionFactory;
13 
14     static {
15         String resource="mybatis-config.xml";
16         Reader reader =null;
17         try {
18             reader = Resources.getResourceAsReader(resource);
19         } catch (IOException e) {
20             e.printStackTrace();
21         }
22         sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
23     }
24 
25     /**
26      * 获取SqlSessionFactory
27      * @return SqlSessionFactory
28      */
29     public static SqlSessionFactory getSqlSessionFactory(){
30         return sqlSessionFactory;
31     }
32 
33     /**
34      * 获取SqlSession
35      * @return SqlSession
36      */
37     public static SqlSession getSqlSession(){
38         return sqlSessionFactory.openSession();
39     }
40     /**
41      * 关闭SqlSession
42      */
43     public  static void closeSession(SqlSession sqlSession){
44         if (sqlSession!=null)
45             sqlSession.close();
46     }
47 }
工具类

 

 

1.5Person实体类

技术分享

技术分享
 1 package model;
 2 
 3 /**
 4  * Created by 123 on 2017/06/29.                
 5  */
 6 public class Person {
 7     private int id;
 8     private String userName ;
 9     private int age ;
10     private String mobilePhone ;
11 
12     public Person() {
13         this.id = id;
14         this.userName = userName;
15         this.age = age;
16         this.mobilePhone = mobilePhone;
17     }
18 
19     public int getId() {
20 
21         return id;
22     }
23 
24     public void setId(int id) {
25         this.id = id;
26     }
27 
28     public String getUserName() {
29         return userName;
30     }
31 
32     public void setUserName(String userName) {
33         this.userName = userName;
34     }
35 
36     public int getAge() {
37         return age;
38     }
39 
40     public void setAge(int age) {
41         this.age = age;
42     }
43 
44     public String getMobilePhone() {
45         return mobilePhone;
46     }
47 
48     public void setMobilePhone(String mobilePhone) {
49         this.mobilePhone = mobilePhone;
50     }
51 }
实体类

 

1.6 Person.xml 实体类查询配置文件

技术分享

 

技术分享
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 <mapper namespace="com">
 4     <insert id="insertPerson" parameterType="Person" >
 5         INSERT INTO PERSON(ID,USERNAME,AGE,MOBILEPHONE)VALUES (#{id},#{userName},#{age},#{mobilePhone})
 6     </insert>
 7 
 8     <select id="queryById" parameterType="int" resultType="Person">   //可省略
 9         SELECT * FROM PERSON WHERE ID=#{id}
10     </select>
11 
12     <update id="updatePerson">
13         UPDATE PERSON SET USERNAME=#{userName},AGE=#{age},MOBILEPHONE=#{mobilePhone} WHERE ID=#{id}
14     </update>
15 </mapper>
小配置文件

 

 

 

 

1.7 config.properties 连接数据字段配置文件

技术分享

技术分享
1 driver=com.mysql.jdbc.Driver
2 url=jdbc:mysql://localhost:3306/mybatis
3 username=sa
4 password=123
连接字段(配置文件)

 

 

1.8 mybatis-config.xml 连接数据库配置文件  (由于截图没有截完整,所以缺少一部分,请不要误解,下面有完整配置文件)

技术分享

技术分享
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <properties resource="config.properties"/>
 7     <typeAliases>
 8         <typeAlias type="model.Person" alias="Person"/>
 9     </typeAliases>
10     <environments default="development">
11         <environment id="development">
12             <transactionManager type="JDBC"/>
13             <dataSource type="POOLED">
14                 <property name="driver" value="${driver}"/>
15                 <property name="url" value="${url}"/>
16                 <property name="username" value="${username}"/>
17                 <property name="password" value="${password}"/>
18             </dataSource>
19         </environment>
20     </environments>
21     <mappers>
22         <mapper resource="mapper/Person.xml"/>
23     </mappers>
24 </configuration>
连接数据库配置文件(和上面是有关联的)

 

 

1.9 log4.properties 日志配置文件

技术分享

 

技术分享
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 <mapper namespace="com">
 4     <insert id="insertPerson" parameterType="Person" >
 5         INSERT INTO PERSON(ID,USERNAME,AGE,MOBILEPHONE)VALUES (#{id},#{userName},#{age},#{mobilePhone})
 6     </insert>
 7 
 8     <select id="queryById" parameterType="int" resultType="Person">
 9         SELECT * FROM PERSON WHERE ID=#{id}
10     </select>
11 
12     <update id="updatePerson">
13         UPDATE PERSON SET USERNAME=#{userName},AGE=#{age},MOBILEPHONE=#{mobilePhone} WHERE ID=#{id}
14     </update>
15 </mapper>
记录日志配置文件

 

2.0 PersonTest 测试类 (测试方法有两个,一个是插入数据方法,另外一个是查询对象名称方法,所以分两次截图了)

技术分享

技术分享

技术分享
 1 import model.Person;
 2 import org.apache.ibatis.session.SqlSession;
 3 import org.junit.Test;
 4 import utils.MybatisUtil;
 5 /**
 6  * Created by 123 on 2017/06/29.
 7  */
 8 public class PersonTest {
 9     SqlSession sqlSession ;
10         @Test
11        public  void  insertPerson(){
12             sqlSession = MybatisUtil.getSqlSession();
13             Person person=new Person();
14             person.setId(1);
15             person.setAge(18);
16             person.setMobilePhone("1361165680");
17             person.setUserName("神奇");
18             try {
19                 sqlSession.insert("insertPerson",person);
20                 sqlSession.commit();
21             } catch (Exception e) {
22                 e.printStackTrace();
23             } finally {
24                 MybatisUtil.closeSession(sqlSession);
25             }
26         }
27 
28 
29         @Test
30        public  void queryById(){
31             sqlSession=MybatisUtil.getSqlSession();
32 
33             try {
34                 Person person =sqlSession.selectOne("queryById",1);
35                 sqlSession.commit();
36                 System.out.println(person.getUserName());
37             } catch (Exception e) {
38                 e.printStackTrace();
39             } finally {
40                 MybatisUtil.closeSession(sqlSession);
41             }
42         }
43 }
测试类

 

2.1最后成功插入数据,截图如下:

技术分享

 

有什么问题咋们可以讨论一下,配置mybatis基础案例也接近尾声了,咋们下次再见吧。

 

初识mybatis之入门案例