MyBatis MyBatis study notes 02_ built environment

Build MyBatis work environment

  • Getting hands-on program development MyBatis
  • Data interaction layer (DAO) conventional writing
  • MyBatis simplify data using dynamic proxy interaction layer (DAO) the wording

Getting set up and test procedures

Development steps: Create a project, dependent on the introduction of Jar package, build log output environment, database connection pool configuration, create a Java object persistence layer, write Mapper configuration files and create a test class.

Database preparation

Create a table corresponding SQL statement is as follows:

-- 创建数据库
CREATE DATABASE mybatis;
-- 使用创建的mybatis数据库
USE mybatis;
-- 创建表user
DROP TABLE IF EXISTS user;
CREATE TABLE user (
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(20) DEFAULT NULL,
    password VARCHAR(20) DEFAULT NULL,
    gender VARCHAR(5) DEFAULT NULL,
    email VARCHAR(50) DEFAULT NULL,
    province VARCHAR(20) DEFAULT NULL,
    city VARCHAR(20) DEFAULT NULL,
    birthday DATE DEFAULT NULL
);
-- 插入测试数据
INSERT INTO 
    user(id,username,password,gender,email,province,city,birthday)
VALUES
    (1,'张三','1111','男','[email protected]','河南省','郑州市','1991-04-23'),
    (2,'李四','2222','男','[email protected]','河北省','邯郸市','1989-10-13'),
    (3,'刘丽','3333','女','[email protected]','江苏省','苏州市','1994-06-09'),
    (4,'李丽','4444','女','[email protected]','四川省','成都市','1992-11-07');

Environmental engineering structures

Use MyBatis core jar package as mybatis-3.4.1-jar, outside, but also to prepare other dependent MyBatis Jar package, and ready to provide a driving connection database, create log output environment, the final, the basic program structure and mybatis jar package as Figure:

Program Structure

Database connection pool configuration file

In mybatis-config.xml configuration file, environment configuration information is disposed in environments label, the label environment allows multiple labels, each label in a separate environment configuration corresponding to a single database environment. transactionManager transaction management tag type configuration, the dataSource tag is arranged in the connection information database, which comprises a plurality of property tags, the driving driver to configure the database, the address database connection url, database user name username and password database password.

Simple mybatis-config.xml configuration file as follows:

<?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>
    <!--数据源配置-->
    <environments default="mysql">
        <!--数据库配置的具体信息-->
        <environment id="mysql">
            <!--配置事务管理类型-->
            <transactionManager type="JDBC"/>
            <!--配置连接池信息-->
            <dataSource type="POOLED">
                <!--配置数据库的驱动、连接地址、用户名和密码-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="MARTIN0319"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

Writing SQL mapping configuration file

In MyBatis, the Java classes and SQL statements with no direct link, almost all SQL statements are configured in a mapper mapping file, in the course of MyBatis operation, reads the configuration of SQL statements, parameter input and output Types of. Next, add a select statement in UserMapper.xml in:

<?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="userTest">
    <select id="findUserById" parameterType="integer" resultType="com.martin.domain.User">
        select 
            id,username,password, gender,email,province,city,birthday
        from 
            user 
        where 
            id = #{id}
    </select>
</mapper>

We have the following properties in the select tag:

  • id: sql statement is parsed mappedStatement encapsulated object for the retrieval of the corresponding sql, requires a unique identifier, id is a unique identifier for the development sql statement;
  • parameterType: specifies the input parameter type, examples of the type specified in the input parameters for the integer type;
  • resultType: specifies the type of output parameters, instances mapped to User specified output Java object;
  • # {}: Indicates a placeholder, if the input parameter is a Java basic data types, then # {} in the value may be any value ;

After writing SQL mapping files, in order to allow mybatis resource file to load the class can resolve UserMapper.xml files, you need to configure the file path UserMapper.xml in mybatis-config.xml in.

<mappers>
    <mapper resource="com/martin/mapper/UserMapper.xml"/>
</mappers>

Write entity class and a test class

Need to write three categories, namely persistent entity classes, database interaction class (get SqlSession) test objects and classes.

Persistent entity classes - User

Entity class member variables in the database tables correspond best to the field. Class property requires the use of setter and getter methods to get and set.

User entity classes:

package com.martin.domain;

import java.util.Date;

public class User {

    private Integer id;
    private String username;
    private String password;
    private String gender;
    private String email;
    private String province;
    private String city;
    private Date birthday;
    /*
    setter、getter和toString方法略
    */
}

Database interaction class (get SqlSession objects)

Database interaction class, the resource file to load the class reads the configuration file database connection pool, then SqlSessionFactory database connection and data mapping rules Mapper to create a SqlSession objects can interact with the database.

Interactive database tools - DataConnection.java

package com.martin.datasource;

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 DataConnection {

    private static String RESOURCE = "mybatis-config.xml";
    private static SqlSessionFactory SESSIONFACTORY;
    private static SqlSession SESSION;
    
    public static SqlSession getSqlSession() throws IOException {
        InputStream  input = Resources.getResourceAsStream(RESOURCE);
        SESSIONFACTORY = new SqlSessionFactoryBuilder().build(input);
        SESSION = SESSIONFACTORY.openSession();
        return SESSION;
    }
}

In DataConnection class, Resource resource loading class loader mybatis-config.xml configuration file to obtain the session factory SqlSessionFactory object after calling SqlSessionFactory of openSession method to get SqlSession object.

Write test classes - UserTest

Write test class that needs to be removed from the database id of the user information 1:

package com.martin.test;

import java.io.IOException;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.martin.datasource.DataConnection;
import com.martin.domain.User;

public class UserTest {
    // 测试查找指定id的用户信息
    @Test
    public void testFindUserById() throws IOException {
        SqlSession session  = DataConnection.getSqlSession();
        User user = session.selectOne("userTest.findUserById", 1);
        System.out.println(user);
        // 提交事务和关闭session
        session.commit();
        session.close();
    }
}

In testFindUserById method:

  1. An object class by obtaining SqlSession DataConnection class;
  2. selectOne method calls SqlSession class, this method with two arguments
    1. The first parameter is the namespace UserMapper.xml SQL mapping file corresponding to the ID adding sql statement;
    2. The second parameter is a parameter corresponding to the value of the parameter map file sql statement;

In this case, the console, showing the type of SQL statements and parameters performed, and query information for the user id to 1 print out.

Operating data entry procedures

Above to achieve a single data acquisition, how to query multiple data and implementation of the data additions and deletions to the operation.

Fuzzy query - selectList

User tables in the database fuzzy query by matching a word in the name of the user to query:

First configure a SQL statement mapping UserMapper.xml configuration file:

<select id="findUserByUsername" parameterType="string" resultType="com.martin.domain.User">
    select 
        id,username,password, gender,email,province,city,birthday 
    from 
        user 
    where 
        username like '%${value}%'
</select>

Which still represents id mapping file is parsed and converted into SQL id Statement of, parameterType specified SQL input parameter of type String, and specifies the result type is resultType JavaBean named User.

select tag "{} $" symbol indicates the splice SQL statement to the SQL. Received parameter modification content without any splicing in the SQL statement, the "$ {}" can only use the parameters of the representative value. "$ {}" Can be used [ "%" # {value} " %" ] in place, this time value in parentheses may be any characters.

Write testFindUserByUsername method UserTest class to obtain information about the user name contains "Lee" in:

@Test
public void testFindUserByUsername() throws IOException {
    SqlSession session  = DataConnection.getSqlSession();
    List<User> userList = session.selectList("userTest.findUserByUsername", "李");
    for (User user : userList) {
        System.out.println(user);
    }
     // 提交事务和关闭session
    session.commit();
    session.close();
}

Because the query is vague, the results obtained may be more than a query, the SqlSession the plurality of objects may be acquired by selectList method, the results of the query for List type methods.

In this case, the console, showing the type of SQL statements and parameters performed a String parameter value Lee, shows the number of queries to the result is 2, and the user queries the user name with "Lee" in print out the information.

Increase the user - insert

Increasing operation, the use of the new statement, it is necessary to add the label insert sql statement, no return value, due to the need to insert a User object type, so in this case the fully qualified name of the User class parameterType value.

<insert id="insertUser" parameterType="com.martin.domain.User">
    insert into
        user(username,password,gender,birthday,email,province,city) 
    values 
        (#{username},#{password},#{gender},#{birthday,jdbcType=DATE},#{email},#{province},#{city})
</insert>

When inserting birthday Date property values, add a parameter to declare jdbcType Java JDBC type of the parameter in line with the type, convenient when loading SQL statement to set the parameters, can be correctly mapped to the database format.

Add testInsertUser method, inserting data into a User table:

@Test
public void testInsertUser() throws IOException, ParseException {
    SqlSession session  = DataConnection.getSqlSession();
    User user = new User();
    user.setUsername("孟祥杰");
    user.setPassword("5555");
    user.setGender("男");
    user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("1991-03-19"));
    user.setProvince("江苏省");
    user.setCity("沭阳县");
    session.insert("userTest.insertUser",user);
    // 提交事务
    session.commit();
    session.close();
}

Acquired primary key of the entity is inserted

For some operations, the need to return to the new operation corresponding primary key information of an entity, in MySQL increment primary key before executing the insert statement, MySQL automatically generates an auto-increment primary key, after performing insert operations, by the MySQL SELECT LAST_INSERT_ () to get the primary key of the newly inserted record.

So mapping file to configure the following:

<insert id="insertUser" parameterType="com.martin.domain.User">
    <selectKey keyProperty="id" order="AFTER" resultType="integer">
        SELECT LAST_INSERT_ID()
    </selectKey>
    insert into
        user(username,password,gender,birthday,email,province,city) 
    values 
        (#{username},#{password},#{gender},#{birthday,jdbcType=DATE},#{email},#{province},#{city})
</insert>

Insert selectKey insert tag label, the label is placed in the SELECT INSERT_LAST_ID () to query the last increment primary key. This parameter indicates the order function with respect to the insert SQL statements are executed, it is (before) before or after it (after).

Another way to get auto-increment primary key, is to add attributes in the insert tab "userGeneratedKeys" and "keyProperty" represent attribute names using auto-increment primary keys and Java objects. Configuration is as follows:

<insert id="insertUser" parameterType="com.martin.domain.User" useGeneratedKeys="true" keyProperty="id">
    insert into
        user(username,password,gender,birthday,email,province,city) 
    values 
        (#{username},#{password},#{gender},#{birthday,jdbcType=DATE},#{email},#{province},#{city})
</insert>

After the above settings for, after the insert statement executed MyBatis, growth will be self-id id attribute value is assigned User inserted object, and can be obtained by the method get User id to the logical layer.

At this time, the console insert statement executed and types of parameters inserted and value of each parameter is displayed, and print out the increment id.

Modify and delete entities

For delete and modify, delete and update to use the same label UserMapper.xml configuration file to the preparation of related SQL configuration:

<!-- 修改用户 -->
<update id="updateUser" parameterType="com.martin.domain.User">
    update 
        user 
    set
        username=#{username},
        password=#{password},
        gender=#{gender},
        birthday=#{birthday,jdbcType=DATE},
        email=#{email},
        province=#{province},
        city=#{city} 
    where 
        id=#{id}
</update>

<!-- 删除用户 -->
<delete id="deleteUser" parameterType="com.martin.domain.User">
    delete from 
        user 
    where 
        id=#{id}
</delete>

Delete, and modify configurations are wrapped in delete and update labels for the incoming parameter type is specified by parameterType. Here modify, and delete the configuration information specified user id. Methods and testDeleteUser testUpdateUser new test class UserTest in:

// 修改用户信息
@Test
public void testUpdateUser() throws IOException, ParseException {
    SqlSession session  = DataConnection.getSqlSession();
    // 获取ID为7的用户
    User user = session.selectOne("userTest.findUserById",5);
    // 修改用户的信息
    user.setEmail("[email protected]");
    // 调用update方法保存修改后的用户信息
    session.update("userTest.updateUser", user);
    // 提交事务和关闭session
    session.commit();
    session.close();
}

After performing testUpdateUser method, as shown in FIG console output:

After we can see testUpdateUser method was changed as the number of 1, which means that successful id say 5 to modify the user's email [email protected].

// 删除用户信息
@Test
public void testDeleteUser() throws IOException {
    SqlSession session  = DataConnection.getSqlSession();
    // 获取ID为5的用户
    User user = session.selectOne("userTest.findUserById",5);
    // 调用delete删除用户
    session.delete("userTest.deleteUser", user);
    // 提交事务和关闭session
    session.commit();
    session.close();
}

After performing testDeleteUser method, as shown in FIG console output:

You can see, the number of execution after the delete method, was changed to 1, that is successfully deleted id 5 of the user's data.

Guess you like

Origin www.cnblogs.com/martin0319/p/12319282.html