Home Java javaTutorial In-depth explanation of Mybatis series (1)---Getting started with Mybatis

In-depth explanation of Mybatis series (1)---Getting started with Mybatis

Mar 02, 2017 am 10:30 AM

In the past two years, the combination of springmvc + mybatis has been quite popular. As for the original poster, I have never really come into contact with mybatis. I will learn mybatis while I have some free time these days. This time, I plan to do a series of tutorials about mybatis based on my own learning progress, record my learning process, and also explore it for friends who have not yet come into contact with mybatis. This series of tutorials is intended to go from shallow (use) to deep (analyzing mybatis source code implementation), so it may take several days to complete the update. Okay, let’s start this mybatis learning journey. This is the first tutorial. Let’s simply write a demo and get to know mybatis together.​

For convenience, I use maven. As for how to use maven, I will not introduce it. If you have never used Maven, it will not affect your reading.

1. Mybatis environment setup and simple examples

1. Create a new web project and add dependency packages: mybatis package, database driver package (I use mysql), Log package (I use log4j), since I am a maven project, adding dependency packages is simple, just add dependencies directly in pom.xml.

pom.xml:

<dependencies>
      <!-- 添加junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    
    <!-- 添加log4j -->
    <dependency>
        <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
        <version>1.2.16</version>
    </dependency>
    
    <!-- 添加mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
        <version>3.2.6</version>
    </dependency>
    
    <!-- 添加mysql驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.12</version>
    </dependency>
    
  </dependencies>
Copy after login


2. Configure log4j, configure mybatis

Create a configuration file on the classpath for configuring log4j log4j.properties, and then create a configuration file configuration.xml for configuring Mybatis (the file can be named arbitrarily). I won’t say much about the configuration of log4j. Here I will mainly talk about configuration.xml:

configuration.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  
 7   <!-- 指定properties配置文件, 我这里面配置的是数据库相关 --> 
 8   <properties resource="dbConfig.properties"></properties> 
 9   
 10   <!-- 指定Mybatis使用log4j -->
 11   <settings>
 12      <setting name="logImpl" value="LOG4J"/>
 13   </settings>
 14       
 15   <environments default="development">
 16     <environment id="development">
 17       <transactionManager type="JDBC"/>
 18       <dataSource type="POOLED">
 19           <!--
 20           如果上面没有指定数据库配置的properties文件,那么此处可以这样直接配置 
21         <property name="driver" value="com.mysql.jdbc.Driver"/>
22         <property name="url" value="jdbc:mysql://localhost:3306/test1"/>
23         <property name="username" value="root"/>
24         <property name="password" value="root"/>
25          -->
26          
27          <!-- 上面指定了数据库配置文件, 配置文件里面也是对应的这四个属性 -->
28          <property name="driver" value="${driver}"/>
29          <property name="url" value="${url}"/>
30          <property name="username" value="${username}"/>
31          <property name="password" value="${password}"/>
32          
33       </dataSource>
34     </environment>
35   </environments>
36   
37   <!-- 映射文件,mybatis精髓, 后面才会细讲 -->
38   <mappers>
39     <mapper resource="com/dy/dao/userDao-mapping.xml"/>
40   </mappers>
41   
42 </configuration>
Copy after login


3. Start writing Demo

First, create a table user:

in mysql database test1  

Then, start writing java code.

Take a look at my project structure:

First write an entity class User: The User class is used to correspond to the User table .

User:

 1 package com.dy.entity; 
 2  
 3 public class User { 
 4  
 5     private int id; 
 6     private String name; 
 7     private String password; 
 8     private int age; 
 9     private int deleteFlag;
 10     
 11     public int getId() {
 12         return id;
 13     }
 14     public void setId(int id) {
 15         this.id = id;
 16     }
 17     public String getName() {
 18         return name;
 19     }
 20     public void setName(String name) {
 21         this.name = name;
 22     }
 23     public String getPassword() {
 24         return password;
 25     }
 26     public void setPassword(String password) {
 27         this.password = password;
 28     }
 29     public int getAge() {
 30         return age;
 31     }
 32     public void setAge(int age) {
 33         this.age = age;
 34     }
 35     public int getDeleteFlag() {
 36         return deleteFlag;
 37     }
 38     public void setDeleteFlag(int deleteFlag) {
 39         this.deleteFlag = deleteFlag;
 40     }
 41     
 42 }
Copy after login


Write another UserDao interface:

UserDao:

 1 package com.dy.dao; 
 2  
 3 import java.util.List; 
 4  
 5 import com.dy.entity.User; 
 6  
 7 public interface UserDao { 
 8  
 9     public void insert(User user);
 10     
 11     public User findUserById (int userId);
 12     
 13     public List<User> findAllUsers();
 14     
 15 }
Copy after login

Write another userDao-mapping.xml (you can name it whatever you want):

userDao-mapping.xml:

 1 <?xml version="1.0" encoding="UTF-8" ?>   
 2 <!DOCTYPE mapper   
 3 PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"  
 4 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> 
 5 <mapper namespace="com.dy.dao.UserDao"> 
 6  
 7    <select id="findUserById" resultType="com.dy.entity.User" > 
 8       select * from user where id = #{id} 
 9    </select>
 10 
 11 </mapper>
Copy after login


userDao-mapping.xml相当于是UserDao的实现, 同时也将User实体类与数据表User成功关联起来。

4. 下面编写junit测试代码UserDaoTest:

 UserDaoTest:

 1 public class UserDaoTest { 
 2  
 3     @Test 
 4     public void findUserById() { 
 5         SqlSession sqlSession = getSessionFactory().openSession();  
 6         UserDao userMapper = sqlSession.getMapper(UserDao.class);  
 7         User user = userMapper.findUserById(2);  
 8         Assert.assertNotNull("没找到数据", user); 
 9     }
 10     
 11     //Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与数据库进行交互12     private static SqlSessionFactory getSessionFactory() {  
13         SqlSessionFactory sessionFactory = null;  
14         String resource = "configuration.xml";  
15         try {  
16             sessionFactory = new SqlSessionFactoryBuilder().build(Resources  
17                     .getResourceAsReader(resource));
18         } catch (IOException e) {  
19             e.printStackTrace();  
20         }  
21         return sessionFactory;  
22     }  
23     
24 }
Copy after login


好啦,这样一个简单的mybatis 的demo就能成功运行啦。通过这个demo, 应该你就也能初步看出mybatis的运行机制,如果不清楚,也没关系。从下一篇文章开始,才开始正式讲解mybatis。

 以上就是深入浅出Mybatis系列(一)---Mybatis入门 的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles