In layman's language Mybatis series (two) --- Mybatis entry

A, Mybatis environment and to build a simple example

1. Create a new web project, add dependencies: mybatis package, database-driven package (I'm using mysql), the log package (I am using log4j), because I was maven project, then add dependencies on the simple, direct Add to depend 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>
View Code

2. Configure log4j, configuration mybatis

  Establish a log4j.properties configuration file is used to configure log4j in the classpath, and then create a configuration file used to configure configuration.xml Mybatis of (files can be easily named). log4j configuration, I do not say, here mainly talk about the configuration.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>

  <! - Specifies the properties configuration file, configuration inside my database-related -> 
  < properties Resource = "dbConfig.properties" > </ properties >
  
  <!-- 指定Mybatis使用log4j -->
  <settings>
     <setting name="logImpl" value="LOG4J"/>
  </settings>
      
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
          <!--
          If no properties file specified database configuration above, then this can be configured directly here 
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test1"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
         -->
         
         <! - specified above database configuration file, the configuration file which is corresponding to the four attributes -> 
         < Property name = "Driver" value = "$ {Driver}" /> 
         < Property name = "URL" value = "$ {} URL" /> 
         < Property name = "username" value = "$ {username}" /> 
         < Property name = "password" value = "$ {password}" />
         
      </dataSource>
    </environment>
  </environments>
  
  <! - mapping file, mybatis essence, will go into detail later -> 
  < mappers > 
    < Mapper Resource = "COM / dy / DAO / userDao-the mapping.xml" /> 
  </ mappers >
  
</configuration>
View Code

3. Start writing Demo

  First, establish a table test1 mysql database user:

Write a first entity class User: User classes correspond to tables for the User.

User:

package com.dy.entity;

public class User {

    private int id;
    private String name;
    private String password;
    private int age;
    private int deleteFlag;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getDeleteFlag() {
        return deleteFlag;
    }
    public void setDeleteFlag(int deleteFlag) {
        this.deleteFlag = deleteFlag;
    }
    
}
View Code

Then write a UserDao Interface:

UserDao:

Package Penalty for com.dy.dao;

import java.util.List;

import com.dy.entity.User;

public interface UserDao {

    public void insert(User user);
    
    public User findUserById (int userId);
    
    public List<User> findAllUsers();
    
}
View Code

Then write a userDao-mapping.xml (can easily name):

userDao-mapping.xml:

<?xml version="1.0" encoding="UTF-8" ?>   
<!DOCTYPE mapper   
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"  
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> 
<mapper namespace="com.dy.dao.UserDao">

   <select id="findUserById" resultType="com.dy.entity.User" > 
      select * from user where id = #{id}
   </select>

</mapper>
View Code

userDao-mapping.xml equivalent UserDao implemented, but also the success associated with the data entity class User table User.

4. The following write junit test code UserDaoTest:

 UserDaoTest:

public class UserDaoTest {

    @Test
    public  void findUserById () {
        SqlSession sqlSession = getSessionFactory().openSession();  
        UserDao userMapper = sqlSession.getMapper(UserDao.class);  
        User user = userMapper.findUserById(2);  
        Assert.assertNotNull ( "data not found" , the User);
    }
    
    // Mybatis get SqlSession by SqlSessionFactory, before you can interact with the database through SqlSession 
    Private  static SqlSessionFactory getSessionFactory () {  
        SqlSessionFactory sessionFactory = null;  
        String resource = "configuration.xml";  
        try {  
            sessionFactory = new SqlSessionFactoryBuilder().build(Resources  
                    .getResourceAsReader(resource));
        } catch (IOException e) {  
            e.printStackTrace ();  
        }  
        return sessionFactory;  
    }  
    
}
View Code

Well, such a simple mybatis the demo will be able to successfully run it. With this demo, you should also be able to see the initial operating mechanism mybatis, if not clear, it does not matter. From the beginning of the next article, I began to formally explain mybatis.

Added: How to get the primary key value after the insertion of data?

The first: the database set the primary key increment mechanism

    userDao-mapping.xml defined in the file:

<! - inserted into a user data table -> 
    < INSERT ID = "insertUser" the parameterType = "com.ys.po.User" > 
        <! - inserting the key to return to the main user data object
             keyProperty: the query to set the primary key to parameterType assigned to the properties of an object
             select LAST_INSERT_ID (): performing a primary key value id insert operation returns to the query, apply only to the primary key of the self-energizing
             resultType: Specifies the select LAST_INSERT_ID () The result type of
             Sequence AFTER, with respect to the select LAST_INSERT_ID () operation: order
         -->
        <selectKey keyProperty="id" resultType="int" order="AFTER">
            select LAST_INSERT_ID()
        </selectKey>
        insert into user(name,password,age,deleteFlag)
            values(#{name},#{password},#{age},#{deleteFlag})
    </insert>

The second: Non-increment primary key mechanism

<! - inserted into a user data table -> 
    < INSERT ID = "insertUser" the parameterType = "com.ys.po.User" > 
        <! - inserting the key to return to the main user data object
        Process is: firstly () obtained by the primary key value select UUID, and then provided to the id user object, the insert operation is performed
             keyProperty: the query to set the primary key to parameterType assigned to the properties of an object
             select UUID (): get the primary key value id, note that this is a string
             resultType: Specifies the select UUID () The result type of
             Order BEFORE, with respect to the select UUID () operation: order
         -->
        <selectKey keyProperty="id" resultType="String" order="BEFORE">
            select UUID()
        </selectKey>
        insert into user(name,password,age,deleteFlag)
            values(#{name},#{password},#{age},#{deleteFlag})
</insert>

 

deleteFlag

Guess you like

Origin www.cnblogs.com/deityjian/p/11074722.html