Getting started with mybatis

Getting started with mybatis

Creating tables and inserting data in mysql


-- ----------------------------
--  Table structure for `users`
-- ----------------------------
CREATE TABLE `users` (
  `username` varchar(45) NOT NULL,
  `password` varchar(45) NOT NULL,
  `enabled` tinyint(4) NOT NULL DEFAULT '1',
  PRIMARY KEY (`username`)

-- ----------------------------
--  Records of `users`
-- ----------------------------
INSERT INTO `users` VALUES ('alex', '123456', '1'), ('mkyong', '123456', '1'), ('user', '654321', '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="" xmlns:xsi=""





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 "-// Config 3.0//EN" "">
        <typeAlias type="com.example.mybatis01.domain.User" alias="user" />
    <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@#" />
        <!-- 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" />


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:

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;
    public String toString() {
        return "User [username=" + username + ", password=" + password + ", enabled=" + enabled + "]";



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper  PUBLIC "-// Mapper 3.0//EN"  
<mapper namespace="com.example.mybatis01.mapping.UserMapper">
    <insert id="insert" parameterType="user">
        insert into users(username,
        password,enabled) values(#{username}, #{password},#{enabled})
    <select id="selectUser" parameterType="String" resultType="user">
        SELECT * FROM users WHERE username = #{username}
    <select id="selectAll" resultType="user">
        SELECT * FROM users

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

package com.example.mybatis01;


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");



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