MyBatis Initial use (Idea's MAVEN project, super verbose)

Source: Internet
Author: User
Tags create database log4j
Create a Maven Project

1. Select New item on the menu

File | New | Project

2. Select the LeftMaven


Since we are just creating a normal project, click here Next .

3. Enter GroupId andArtifactId

    • In my project,

GroupId Filling Com.homejim.mybatis

Artifactid Filling Hellomybatis

Click Next .

4.Finish

With the above steps, a common Maven project is created.

MAVEN Configuration

In order to mybatis run on the project, the following configuration is required.

Pom.xml

1. Configure the JDK version and encoding method

<plugins>    <plugin>        <groupId>org.apache.maven.plugins</groupId>        <artifactId>maven-compiler-plugin</artifactId>        <version>2.3.2</version>        <configuration>            <source>1.8</source>            <target>1.8</target>            <encoding>UTF-8</encoding>        </configuration>    </plugin></plugins>

After setting, the code is UTF-8 and the JDK version is 1.8

2. Set the resource file path

MavenThe default is a resource file that will only be packaged resource . If our files are not placed resource , we need to be notified by configuration Maven .

 <resources>    <resource>        <directory>src/main/java</directory>        <includes>            <include>**/*.properties</include>            <include>**/*.xml</include>        </includes>        <filtering>false</filtering>    </resource></resources>

2. Adding MyBatis Dependencies

    <!--mybatis-->    <dependency>        <groupId>org.mybatis</groupId>        <artifactId>mybatis</artifactId>        <version>3.4.5</version>    </dependency>

The version of this project mybatis is 3.4.5 .

3. Adding database-driven dependencies

<!--数据库 mysql 驱动--><dependency>    <groupId>mysql</groupId>    <artifactId>mysql-connector-java</artifactId>    <version>5.1.45</version></dependency>

This project uses a mysql database.

4. Add Log dependencies

<!-- 实现slf4j接口并整合 --><dependency>    <groupId>org.slf4j</groupId>    <artifactId>slf4j-api</artifactId>    <version>1.7.25</version></dependency><dependency>    <groupId>org.slf4j</groupId>    <artifactId>slf4j-log4j12</artifactId>    <version>1.7.25</version></dependency><dependency>    <groupId>org.apache.logging.log4j</groupId>    <artifactId>log4j-core</artifactId>    <version>2.10.0</version></dependency>

The log is added to allow you to output sql statements when testing.

5. Add Test dependencies

<!--junit 测试--><dependency>    <groupId>junit</groupId>    <artifactId>junit</artifactId>    <version>4.12</version>    <scope>test</scope></dependency>

Added junit is more convenient for testing.

6. Import Dependencies

Right-click Pom.xml | Maven | Reimport

Create a database

1. Create a database

CREATE DATABASE IF NOT EXISTS `mybatis` DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

Specifies that the encoding isUTF8

2. Create a database table

Create a student table.

DROP TABLE IF EXISTS `student`;CREATE TABLE `student` (  `student_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '编号',  `name` VARCHAR(20) DEFAULT NULL COMMENT '姓名',  `phone` VARCHAR(20) DEFAULT NULL COMMENT '电话',  `email` VARCHAR(50) DEFAULT NULL COMMENT '邮箱',  `sex` TINYINT(4) DEFAULT NULL COMMENT '性别',  `locked` TINYINT(4) DEFAULT NULL COMMENT '状态(0:正常,1:锁定)',  `gmt_created` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '存入数据库的时间',  `gmt_modified` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改的时间',  PRIMARY KEY (`student_id`)) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='学生表';

3. Inserting test data

Insert some test data.

INSERT INTO `student`(`name`, phone, email, sex, locked)VALUES('小明', 13821378270, 'xiaoming@mybatis.cn', 1, 0),('小丽', 13821378271,  'xiaoli@mybatis.cn', 0, 0),('小刚', 13821378272, 'xiaogang@mybatis.cn', 1, 0),('小花', 13821378273, 'xiaohua@mybatis.cn', 0, 0),('小强', 13821378274, 'xiaoqiang@mybatis.cn', 1, 0),('小红', 13821378275, 'xiaohong@mybatis.cn', 0, 0);
Configuring an XML file for MyBatis configuration MyBatis

The XML configuration file (config XML) contains the core settings for the MyBatis system.

1. Replication Framework

Copy the most basic configuration from the official website:

<?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="development">    <environment id="development">      <transactionManager type="JDBC"/>      <dataSource type="POOLED">        <property name="driver" value="${driver}"/>        <property name="url" value="${url}"/>        <property name="username" value="${username}"/>        <property name="password" value="${password}"/>      </dataSource>    </environment>  </environments>  <mappers>    <mapper resource="org/mybatis/example/BlogMapper.xml"/>  </mappers></configuration>

2. Configure Environments

environmentsCorresponds to database-related properties. We can configure multiple environments, but each sqlsessionfactory instance can only choose one. In this project, we can only configure one. Database was just created by US mybatis .

<environments default="development">    <environment id="development">        <transactionManager type="JDBC">            <property name="" value=""/>        </transactionManager>        <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="你自己的密码"/>        </dataSource>    </environment></environments>

3. Configure settings

In this project, the main purpose is to configure the log output. pom.xmlis configured in log4j , so the log implementation value here is LOG4J .

<settings>    <setting name="logImpl" value="LOG4J" /></settings>

4. Configure Typealiases

A type alias is a short name set for the Java type. It is only relevant to the XML configuration, and it only exists to reduce the redundancy of the fully qualified name of the class.

If we configure this

<--项目中不是这样配置的--><typeAliases>  <typeAlias alias="Student" type="com.homejim.mybatis.entity.Student"/></typeAliases>

Then in the mybatis , Student can be used in any com.homejim.mybatis.entity.Student place of use.

But generally entity there are many, so the configuration is too cumbersome to mybatis support the specified package name, using the class's first letter lowercase class qualified name as an alias.

In this project, the following configuration

<typeAliases>    <package name="com.homejim.mybatis.entity"/></typeAliases>

5. Configure Mappers

In the same vein, it can be configured individually, or it can be identified by a scan package.

<mappers>    <package name="com.homejim.mybatis.mapper"/></mappers>

This configuration scans all the files in the specified package .xml , which contain mybatis the SQL statement and the mapping configuration file. Follow-up will be created.

Create an entity class and corresponding Mapper.xml

1. Create an entity class

Entity class, the attribute needs to correspond to field one by one in the database table and has corresponding getter and setter .

package com.homejim.mybatis.entity;import java.util.Date;public class Student {    private Integer studentId;    private String name;    private String phone;    private String email;    private Byte sex;    private Byte locked;    private Date gmtCreated;    private Date gmtModified;    /**     * 以下部分为setter和getter, 省略     */}

2. Create Mapper interface and Mapper.xml

StudentMapper.java

package com.homejim.mybatis.mapper;import com.homejim.mybatis.entity.Student;import java.util.List;public interface StudentMapper {    /**     *     * @return     */    List<Student> selectAll();}

StudentMapper.xml

<?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= "Com.homejim.mybatis.mapper.StudentMapper" > <resultmap id= "baseresultmap" type= " Com.homejim.mybatis.entity.Student "> <id column=" student_id "jdbctype=" INTEGER "property=" StudentID "/> &lt ; result column= "name" jdbctype= "varchar" property= "name"/> <result column= "phone" jdbctype= "varchar" property= " Phone "/> <result column=" email "jdbctype=" VARCHAR "property=" email "/> <result column=" Sex "jdbctype=" T Inyint "property=" Sex "/> <result column=" locked "jdbctype=" TINYINT "property=" locked "/> <result column = "gmt_created" jdbctype= "TIMESTAMP" property= "gmtcreated"/> <result column= "gmt_modified" jdbctype= "TIMESTAMP "property=" gmtmodified "/> </resultMap> <sql id=" Base_column_list "> student_id, Name, phone, email, s EX, Locked, gmt_created, gmt_modified </sql> <select id= "SelectAll" resultmap= "Baseresultmap" > select <inc Lude refid= "Base_column_list"/> from student </select></mapper>

The result mappings and statements are configured sql sql id with the Mappe same method names in R.

Test
  public class Studentmappertest {private static sqlsessionfactory sqlsessionfactory; @BeforeClass public static void Init () {try {reader reader = Resources.getresourceasreader ("MyBatis            -config.xml ");        Sqlsessionfactory = new Sqlsessionfactorybuilder (). build (reader);        } catch (IOException e) {e.printstacktrace ();        }} @Test public void Testselectlist () {sqlsession sqlsession = null;            try {sqlsession = Sqlsessionfactory.opensession ();            list<student> students = sqlsession.selectlist ("SelectAll");            for (int i = 0; i < students.size (); i++) {System.out.println (Students.get (i));        }} catch (Exception e) {e.printstacktrace ();            } finally {if (sqlsession! = null) {sqlsession.close (); }        }    }}
    1. Resourcesread through the tool class mybatis-config.xml , deposit Reader ;
    2. SqlSessionFactoryBuilderUse the created object obtained in the previous step reader SqlSessionFactory ;
    3. sqlSessionFactoryobtained by object SqlSession ;
    4. SqlSessionThe object uses selectList the method to find the corresponding “selectAll” statement and executes the SQL query.
    5. The bottom layer is JDBC obtained by querying ResultSet , and on each record, resultMap the mapping results are mapped to Student medium and returned List .
    6. Finally remember to close SqlSession .

The results obtained are as follows

With SQL output, and SQL execution

Source

Please visit my Github homepage for more.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.