SSM framework notes 01: Preliminary MyBatis

First, what is MyBatis

(A) Overview MyBatis
MyBatis support for custom SQL, excellent persistence framework stored procedures and advanced mappings. MyBatis eliminates almost all of the retrieved manually set JDBC code and parameters and the result set. MyBatis uses a simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plan Old Java Objects, ordinary Java Objects) to database records in.

(B) The basic idea of ORM tools
, whether or Hibernate MyBatis, you will find that they have in common:

  1. SessionFactory obtained from a configuration file (usually XML configuration file).
  2. SessionFactory generated by the session object.
  3. Completed in the session additions and deletions to change search and data such as transaction commits.
  4. Closed session after the run out.
  5. Between Java objects and database you have to do mapping configuration file, usually a xml file.

Second, create a database and tables

1. Create a MySQL database the mybatis
Here Insert Picture Description
2, built form user

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

3, insert a number of records

 INSERT INTO `user` VALUES ('1', '李刚', '20', '江阳区嘉裕花园3栋四楼15#');
INSERT INTO `user` VALUES ('2', '王华', '30', '纳溪区大渡镇红鱼村三大队');
INSERT INTO `user` VALUES ('3', '郑小翠', '21', '江阳区老窖花园2栋五楼15号');

Here Insert Picture Description
Using Maven build tool, you do not have to manually download jar package, all the jar packages unified warehouse management, as long as it pom configuration file, run-install ... dependent package will be downloaded, eliminating the need for you to manage time-dependent. (Pom: Project Object Model Project Object Model)

Third, create a Maven project TestMybatis

1, the new Maven project
Here Insert Picture Description
Here Insert Picture Description

  • GroupId project organization is a unique identifier corresponding to the actual Java package structure, the directory structure is the main directory of java.
  • ArtifactId project is a unique identifier, the actual name of the corresponding item, namely the project root directory name.

Here Insert Picture Description
Here Insert Picture Description
2, add an element in the pom.xml file, manage package dependencies jar
Here Insert Picture Description

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>net.qing.mybatis</groupId>
    <artifactId>TestMybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
    
</project>

How to add a jar package dependencies element?
(1) Open MavenRepository network
MavenRepository Network
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description

3, the red box will depend on the elements to the element copies the file's pom.xml

Here Insert Picture Description
Here Insert Picture Description
4, create a package net.hw.mybatis.bean in main / java Lane
Here Insert Picture Description

package net.qing.mybatis.bean;

public class User {

        private int id;
        private String name;
        private int age;
        private String address;

        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 int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    ", address='" + address + '\'' +
                    '}';
        }
    }

5, create mapper subdirectory resources directory, create an entity-relational mapping file inside UserMapper.xml
Here Insert Picture Description

<?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="net.hw.mybatis.mapper.UserMapper">
    <select id="findById" parameterType="int" resultType="User">
        SELECT * FROM user WHERE id = #{id};
    </select>

    <select id="findAll" resultType="User">
        SELECT * FROM user;
    </select>
</mapper>

6, created MyBatis mybatis-config.xml configuration file in the resources directory

<?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>
    <!--配置实体类别名-->
    <typeAliases>
        <typeAlias type="net.hw.mybatis.bean.User" alias="User"/>
    </typeAliases>
 
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test_mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="1"/>
            </dataSource>
        </environment>
    </environments>
 
    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>
</configuration>

(1) mybatis-config.xml is used to establish mybatis sessionFactory used, which is mainly connected to a database that contains the relevant things, as well as the corresponding alias java class, for example, the alias is very important, in particular the mapping class, such as in UserMapper.xml resultType is the corresponding User here. To remain consistent.
(2) mybatis-config.xml inside the class comprising xml configuration file to map.
(3) In UserMapper.xml document which is the definition of a variety of SQL statements, these statements as well as the parameters, and the type to be returned.
7. Creating log4j.properties file in the resources directory

Here Insert Picture Description

Configure logging for testing: optionally with log file
log4j.rootLogger=WARN, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

8, create a package net.hw.mybatis.bean in test / java directory, create a test class TestUserOperation inside
Here Insert Picture Description

package net.qing.mybatis.bean;

import jdk.internal.module.Resources;
import net.qing.mybatis.bean.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

/**
 * Created by howard on 2017/2/10.
 */
public class TestUserOperation<SqlSession> {
    private SqlSession session;

    @Before
    public void init() {
        try {
            // 读取mybatis配置文件
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            // 利用mybatis配置文件构建SQL会话工厂
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
            // 利用SQL会话工厂获取会话
            session = factory.openSession();
            System.out.println("session对象已创建。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testFindById() {
        int id = 1;
        User user = session.selectOne("net.qing.mybatis.mapper.UserMapper.findById", id);
        System.out.println(user);
    }

    @Test
    public void testFindAll() {
        List<User> users= session.selectList("net.qing.mybatis.mapper.UserMapper.findAll");
        for (User user : users) {
            System.out.println(user);
        }
    }

    @After
    public void destroy() {
        session.close();
        System.out.println("session对象已关闭。");
    }
}
9、运行测试程序
Published 30 original articles · won praise 0 · Views 529

Guess you like

Origin blog.csdn.net/weixin_44202489/article/details/104031455