Getting started with mybatis

Getting started with mybatis

Creating tables and inserting data in mysql

SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
--  Table structure for `users`
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `username` varchar(45) NOT NULL,
  `password` varchar(45) NOT NULL,
  `enabled` tinyint(4) NOT NULL DEFAULT '1',
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `users`
-- ----------------------------
BEGIN;
INSERT INTO `users` VALUES ('alex', '123456', '1'), ('mkyong', '123456', '1'), ('user', '654321', '1');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

Building a common maven java project in eclipse

Choosing maven project for convenient management

Choose a common java project

Next, enter the relevant name, and the final project structure is as follows:

The names are different, the structure is the same.

Add jar dependency of project

<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.example</groupId>
    <artifactId>mybatis01</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>mybatis01</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
    </dependencies>
</project>

Using mybatis to query data

Add mybatis configuration file conf.xml


The contents are 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>
    <typeAliases>
        <typeAlias type="com.example.mybatis01.domain.User" alias="user" />
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&amp;useSSL=true" />
                <property name="username" value="root" />
                <property name="password" value="123456@#" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- register userMapper.xml Documents, userMapper.xml Be located com.example.mybatis01.mapping This bag, so resource finish writing sth. com/example/mybatis01/mapping/userMapper.xml -->
        <mapper resource="com/example/mybatis01/mapping/userMapper.xml" />
    </mappers>

</configuration>

The typeAlias node takes an alias for the entity class for later reference. The environment node is the information related to the database connection. The mapper node indicates the address of the mapping file. The contents of the above file are as follows:
User.java

package com.example.mybatis01.domain;

public class User {
    private String username;
    private String password;
    private boolean enabled;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public boolean isEnabled() {
        return enabled;
    }
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
    @Override
    public String toString() {
        return "User [username=" + username + ", password=" + password + ", enabled=" + enabled + "]";
    }

}

UserMapper.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.example.mybatis01.mapping.UserMapper">
    <insert id="insert" parameterType="user">
        insert into users(username,
        password,enabled) values(#{username}, #{password},#{enabled})
    </insert>
    <select id="selectUser" parameterType="String" resultType="user">
        SELECT * FROM users WHERE username = #{username}
    </select>
    <select id="selectAll" resultType="user">
        SELECT * FROM users
    </select>
</mapper>

Then write an App.java main class to test the data accessed by mybatis,

package com.example.mybatis01;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.example.mybatis01.domain.User;

/**
 * Hello world!
 *
 */
public class App {
    public static void main(String[] args) {
        //Profile of mybatis
        String resource = "conf.xml";
        //Use the classloader to load the configuration file of mybatis (it also loads the associated mapping file)
        InputStream is = App.class.getClassLoader().getResourceAsStream(resource);
        //Build the factory of sqlSession
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        //Create sqlSession that can execute sql in the mapping file
        SqlSession session = sessionFactory.openSession();
        /**
         * The identity string of the mapping sql,
         * com.example.mybatis01.mapping.UserMapper Is the value of the namespace attribute of the mapper tag in the userMapper.xml file,
         * selectUser Is the id attribute value of the select tag. You can find the SQL to execute through the id attribute value of the select tag
         */
        String statement = "com.example.mybatis01.mapping.UserMapper.selectUser";//Mapping the identity string of sql
        //Execute the query to return the sql of a unique user object
        User user = session.selectOne(statement, "alex");
        System.out.println(user);

        System.out.println(session.selectList("com.example.mybatis01.mapping.UserMapper.selectAll"));

    }
}

The structure of the final project is as follows:

Run the main method and print the result as follows:

Tags: Mybatis xml Maven Apache

Posted on Mon, 04 May 2020 07:39:37 -0400 by tony_l