MyBatis entry example (Idea)

Development Environment: Idea2018
databases: mysql 8.0.16
Objective: To learn Mybatis

  1. Database ready
    for this example uses a database mysql 8.0.16, the username root, password 123456
    to create the database and set up a test form:
/*创建数据库*/
CREATE DATABASE tms default character set utf8;

/*创建数据表单*/
CREATE TABLE `t_members` (
    ->   `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
    ->   `nickname` varchar(255) DEFAULT NULL COMMENT '昵称',
    ->   `password` char(32) NOT NULL DEFAULT '' COMMENT '密码',
    ->   `realname` varchar(36) NOT NULL DEFAULT '' COMMENT '真实姓名',
    ->   `gender` enum('MALE','FEMALE','NONE') NOT NULL DEFAULT 'NONE' COMMENT '姓名',
    ->   `rank` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '会员等级',
    ->   `email` char(50) NOT NULL DEFAULT '' COMMENT '邮箱',
    ->   `mobile` varchar(15) NOT NULL DEFAULT '' COMMENT '手机号',
    ->   `safequestion` varchar(255) NOT NULL DEFAULT '0' COMMENT '安全问题',
    ->   `safeanswer` char(30) NOT NULL DEFAULT '' COMMENT '安全答案',
    ->   `createdTime` datetime DEFAULT NULL COMMENT '创建时间',
    ->   PRIMARY KEY (`id`)
    -> ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='会员表';
    
/*插入测试数据*/
INSERT INTO `t_members` VALUES ('2', 'tom', '123456', 'Tom Hanks', 'MALE', '1', '[email protected]', '13588888888', '1+1=?', '3', 'now()');
INSERT INTO `t_members` VALUES ('3', 'andy', '123789', 'Andy Zhou', 'FEMALE', '1', '[email protected]', '13699999999', '2+2=?', '5', now());

  1. Project Creation
    File -> New Project, select Maven, check Create from architype, select the maven-archetype-quickstart, click on the Next button to
    Select the type of project
    enter GroupId and ArtifactId, continue to Next
    GroupId and project name
    and then continue Next, until Finish.

  2. The first show at the overall structure when the project is completed, then the process of creating a variety of documents. The lack of new project folders and Package, add their own just fine.
    the whole frame

  3. First, add a new project after the necessary dependencies to pom.xml

<?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>com.gbs</groupId>
  <artifactId>Members</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>Members</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.8</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.11</version>
    </dependency>

  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

  1. Creating the Entity Classes Member
package com.gbs.dao.entity;

import java.io.Serializable;
import java.util.Date;

public class Member implements Serializable {
    private static final long serialVersionUID = 6948864912341044105L;
    private Integer id;
    private String nickname;
    private String password;
    private String realname;
    private String gender;
    private String email;
    private String mobile;
    private Integer rank=0;
    private String safequestion;
    private String safeanswer;
    private Date createdTime;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRealname() {
        return realname;
    }

    public void setRealname(String realname) {
        this.realname = realname;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public Integer getRank() {
        return rank;
    }

    public void setRank(Integer rank) {
        this.rank = rank;
    }

    public String getSafequestion() {
        return safequestion;
    }

    public void setSafequestion(String safequestion) {
        this.safequestion = safequestion;
    }

    public String getSafeanswer() {
        return safeanswer;
    }

    public void setSafeanswer(String safeanswer) {
        this.safeanswer = safeanswer;
    }

    public Date getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }

    @Override
    public String toString() {
        return "Member{" +
                "id=" + id +
                ", nickname='" + nickname + '\'' +
                ", password='" + password + '\'' +
                ", realname='" + realname + '\'' +
                ", gender='" + gender + '\'' +
                ", email='" + email + '\'' +
                ", mobile='" + mobile + '\'' +
                ", rank=" + rank +
                ", safequestion='" + safequestion + '\'' +
                ", safeanswer='" + safeanswer + '\'' +
                ", createdTime=" + createdTime.toString() +
                '}';
    }
}

  1. Dao layer interface MemberDao
package com.gbs.dao;

import com.gbs.dao.entity.Member;
import java.util.List;

public interface MemberDao {
    List<Member> findPageObjects();
}
  1. Create a map file MemberMapper.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.gbs.dao.MemberDao">

    <select id="findPageObjects" resultType="com.gbs.dao.entity.Member">
        select * from t_members
    </select>
</mapper>
  1. Write jdbc.properties
jdbc.DriverClassName=com.mysql.cj.jdbc.Driver
jdbc.url =jdbc:mysql://localhost:3306/tms?serverTimezone=UTC&useSSL=false
jdbc.username=root
jdbc.password=123456
  1. Write mybatis-config.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>
    <properties resource="jdbc.properties">
    </properties>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.DriverClassName}" />
                <property name="url"
                          value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/MemberMapper.xml" />
    </mappers>

</configuration>
  1. Subject code has been completed, the first to write test code TestMybatis
package com.gbs;

import com.gbs.dao.MemberDao;
import com.gbs.dao.entity.Member;

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.Test;
import java.io.IOException;
import java.util.List;

public class TestMybatis {
    /**查询测试方法*/
    @Test
    public void testFindPageObjects() throws IOException {
        //定义配置文件的路径
        String resource="mybatis-config.xml";
        //通过SqlSessionFactoryBuilder创建SqlSessionFactory
        SqlSessionFactory factory=new SqlSessionFactoryBuilder()
                .build(Resources.getResourceAsStream(resource));
        //通过SqlSessionFactory创建SqlSession
        SqlSession session=factory.openSession();
        //执行dao对象
        MemberDao dao=session.getMapper(MemberDao.class);
        //得到结果集
        List<Member> list=dao.findPageObjects();
        //输出结果集
        System.out.println(list);
        //关闭连接
        session.close();
    }
}

Published an original article · won praise 0 · Views 5

Guess you like

Origin blog.csdn.net/taylor_gao/article/details/104566221