Home > Java > javaTutorial > body text

Getting Started with MyBatis (1)---Basic Use

黄舟
Release: 2016-12-21 14:21:13
Original
1541 people have browsed it

1. Introduction to MyBatis

1.1. Overview

MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures and advanced mapping.

MyBatis avoids almost all JDBC code and manual setting of parameters and getting result sets.

MyBatis can use simple xml or annotations for configuration and native Maps to map interfaces and Java POJOs (Plain Old Java Objects, ordinary Java objects) into records in the database.

1.2, ORM

The basic idea of ​​ORM tools
Whether you have used hibernate or mybatis, you can find that they have one thing in common:
1. Get sessionfactory.
from the configuration file (usually an XML configuration file) 2. Generate a session by sessionfactory
3. Complete the addition, deletion, modification, and transaction submission of data in the session.
4. Close the session after use.

5. There is a mapping configuration file between the java object and the database, which is usually an xml file.

2. Environment setup

2.1. Required Jar package

To use MyBatis, just put the mybatis-x.x.x.jar file in the classpath.

Getting Started with MyBatis (1)---Basic Use

2.2. Establish database and insert data

MySQL database is used here:

CREATE TABLE `mybatis`.`user` (
  `id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `name` VARCHAR(45) NOT NULL DEFAULT '无名氏' COMMENT '用户名',
  `age` TINYINT(3) NOT NULL DEFAULT 21 COMMENT '用户年龄',
  `birthday` DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00' COMMENT '用户生日',
  `address` VARCHAR(256) NOT NULL DEFAULT '北京' COMMENT '用户地址',  PRIMARY KEY (`id`)  COMMENT '')
COMMENT = '用户表';
Copy after login

insert into user(id,name,age,birthday,address)values(1,'张三',23,'1990- 01-23 20:24:21','Shanghai'),(2,'李思',18,'1986-12-23 12:13:11','Guangzhou'),(3,'

2.3. Establish a Web project and introduce the Jar package into the project

Getting Started with MyBatis (1)---Basic Use

3. Establish configuration files, entity classes, and interfaces

3.1. Establish entity classes

/*** @Title: User.java

* @Package com.pb.mybatis.po

* @Description: TODO (user class)

* @author Liu Nan

* @date 2015-10-26 5 pm: 42:13

* @version V1.0

*/package com.pb.mybatis.po;import java.util.Date;/**
* @ClassName: User

* @Description: TODO (user class)

* @author Liu Nan

* @date 2015-10-26 5:42:13 pm

**/public class User {    
   /**
* id (user ID)*/
   private int id;    /**
* name (user name)*/
   private String name;    /**
*age (user age)*/
   private int age;    /**
* birthday (user’s birthday)*/
   private Date birthday;    /**
* address (user address)*/
   private String address;    /**
    * @return the id    */
   public int getId() {        return id;
   }    /**
    * @param id the id to set    */
   public void setId(int id) {        this.id = id;
   }    /**
    * @return the name    */
   public String getName() {        return name;
   }    /**
    * @param name the name to set    */
   public void setName(String name) {        this.name = name;
   }    /**
    * @return the age    */
   public int getAge() {        return age;
   }    /**
    * @param age the age to set    */
   public void setAge(int age) {        this.age = age;
   }    /**
    * @return the brithday    */
   public Date getBirthday() {        return brithday;
   }    /**
    * @param brithday the brithday to set    */
   public void setBirthday(Date birthday) {        this.birthday = birthday;
   }    /**
    * @return the address    */
   public String getAddress() {        return address;
   }    /**
    * @param address the address to set    */
   public void setAddress(String address) {        this.address = address;
   }
   

}

 

3.2、写实体类接口

 

/*** @Title: UserMapper.java

* @Package com.pb.mybatis.dao

* @Description: TODO (describe what the file does in one sentence)

* @author Liu Nan

* @date 2015- 10-26 5:45:13 pm

* @version V1.0

*/package com.pb.mybatis.dao;import com.pb.mybatis.po.User;/**
* @ClassName: UserMapper

* @Description: TODO (user class data access interface)

* @author Liu Nan

* @date 2015-10-26 5:45:13 pm

**/public interface UserMapper {    /**
*
* @Title: selectUserById

* @Description: TODO (query based on user ID)

* @param id
* @return User*/
   public User selectUserById(int id);

}

 

3.3、与db.properties

 db.properties

#数据库基本配置
#驱动
driver=com.mysql.jdbc.Driver
#连接url
url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8#用户名
username=root
#密码
passWord=root

3.4、建立映射文件与configuration.xml配置

 

 UserMapper.xml

br/> PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis .org/dtd/mybatis-3-mapper.dtd">

configuration.xml

xml version="1.0" encoding="UTF-8"?>br/> PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd /mybatis-3-config.dtd"> < ;property name="username" value="${username}"/> dataSource>

3.5. Simple query based on ID

/*** @Title: Test1.java

* @Package com.pb.mybatis.test

* @Description: TODO (describe what the file does in one sentence)

* @author Liu Nan

* @date 2015- 10-26 5:55:54 pm

* @version V1.0

*/package com.pb.mybatis.test;import java.io.IOException;import java.io.Reader;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 com.pb.mybatis.dao.UserMapper;import com.pb.mybatis.po.User;/**
* @ClassName: Test1

* @Description: TODO (test class)

* @author Liu Nan

* @date 2015-10-26 5:55:54 pm

**/public class Test1 {    //Session工厂
   static SqlSessionFactory sqlSessionFactory=null;    //Session
   static SqlSession session=null;    //字符流
   static Reader reader=null;    
   public static void main(String[] args) {
       
       selectById();
   }    /**
*
* @Title: selectById

* @Description: TODO (Find user based on ID)
void*/
   public static void selectById(){        //加载配置文件
       try {
           reader=Resources.getResourceAsReader("configuration.xml");            //建立SqlSessionFactory
           sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);            //打开Session
           session=sqlSessionFactory.openSession();            //获取用户接口对象
           UserMapper userMapper=session.getMapper(UserMapper.class);            //调用查询方法
           User user=userMapper.selectUserById(1);
           System.out.println(user.getName()+"..."+user.getAge()+"..."+user.getBirthday().toLocaleString()+"..."+user.getAddress());
       } catch (IOException e) {
           e.printStackTrace();
       }
       
   }

}

 

3.6、使用别名

Getting Started with MyBatis (1)---Basic Use

更改mapper.xml中的User类的路径 为别名

Getting Started with MyBatis (1)---Basic Use


br/>  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 

测试类不变

3.7、使用resultMap

在mapper.xml中使用resultMap

 

br/> PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis .org/dtd/mybatis-3-mapper.dtd">

The test class remains unchanged

Four. Implement basic addition, deletion, modification, and query

4.1. Add fuzzy query, add, modify, delete methods in the interface,

/*** @Title: UserMapper.java

* @Package com.pb.mybatis.dao

* @Description: TODO (describe what the file does in one sentence)

* @author Liu Nan

* @date 2015- 10-26 5:45:13 pm

* @version V1.0

*/package com.pb.mybatis.dao;import java.util.Date;import java .util.List;import com.pb.mybatis.po.User;/**
* @ClassName: UserMapper

* @Description: TODO (user class data access interface)

* @author Liu Nan

* @date 2015-10-26 5:45:13 pm

**/public interface UserMapper { /**
*
* @Title: selectUserById

* @Description: TODO (query based on user ID)

* @param id
* @return User*/
public User selectUserById(int id); /**
*
* @Title: selectUserLikeName

* @Description: TODO (fuzzy query based on name)

* @param name
* @return List*/
public List selectUserLikeName(String name);
/**
*
* @Title: addUser

* @Description: TODO (add user)

* @param user void*/
public void addUser(User user); /**
*
* @Title: updateUser

* @Description: TODO (modify user)

* @param user void*/
public void updateUser(User user); /**
*
* @Title: deleteUser

* @Description: TODO (delete user)

* @param id void*/
public void deleteUser(int id);
}

4.2. Add corresponding mapping to mapper.xml

br/> PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis .org/dtd/mybatis-3-mapper.dtd">
insert into user(name,age,birthday,address)
values(#{name},#{age},#{birthday },#{address})
update user set name=#{name},age= #{age},birthday=#{birthday},address=#{address}
where id=#{id}
delete from user
where id=#{id}

4.3, test class

/**

* @Title: Test1.java

* @Package com.pb.mybatis.test

* @Description: TODO (describe what this file does in one sentence)

* @author Liu Nan

* @date 2015-10-26 5:55:54 pm

* @version V1.0

*/package com.pb.mybatis.test;import java.io.IOException;import java.io.Reader;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;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 com.pb.mybatis.dao.UserMapper;import com.pb.mybatis.po.User;/**
* @ClassName: Test1
*
* @Description: TODO (test class)
*
* @author Liu Nan
*
* @date 2015-10-26 5:55:54 PM
*
*
*/public class Test1 {    // Session工厂
   static SqlSessionFactory sqlSessionFactory = null;    // Session
   static SqlSession session = null;    // 字符流
   static Reader reader = null;    public static void main(String[] args) {

       
   }    /**
*
* @Title: selectById
*
* @Description: TODO (Find user based on ID) void*/
   public static void selectById() {        // 加载配置文件
       try {
           reader = Resources.getResourceAsReader("configuration.xml");            // 建立SqlSessionFactory
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);            // 打开Session
           session = sqlSessionFactory.openSession();            // 获取用户接口对象
           UserMapper userMapper = session.getMapper(UserMapper.class);            // 调用查询方法
           User user = userMapper.selectUserById(1);
           System.out.println(user.getName() + "..." + user.getAge() + "..."
                   + user.getBirthday().toLocaleString() + "..."
                   + user.getAddress());
       } catch (IOException e) {
           e.printStackTrace();
       }

   }    /**
*
* @Title: selectLikeName
* *
* @Description: TODO (fuzzy query based on user name) void*/
   public static void selectLikeName() {        // 加载配置文件
       try {
           reader = Resources.getResourceAsReader("configuration.xml");            // 建立SqlSessionFactory
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);            // 打开Session
           session = sqlSessionFactory.openSession();            // 获取用户接口对象
           UserMapper userMapper = session.getMapper(UserMapper.class);            // 调用查询方法
           List users = userMapper.selectUserLikeName("张");            for (User user : users) {
               System.out.println(user.getName() + "..." + user.getAge()                        + "..." + user.getBirthday().toLocaleString() + "..."
                       + user.getAddress());
           }
       } catch (IOException e) {
           e.printStackTrace();
       }

   }    /**
*
* @Title: addUser

* @Description: TODO (add user)
void*/
public static void addUser() {                                                                                                                        Load the configuration file                                                                                                                                   Load the configuration file actory = new SqlSessionFactoryBuilder().build(reader); // Open Session
          session = sqlSessionFactory.openSession();                                                 using using using use using using using ’ s ’ s sqlSessionFactory.openSession()-                                      User user =new User();
User.setName("Hehe" ;
Date date=sdf.parse(d);
                                                                                                                                                                                                                           of Id "+user.getid ()); // Submit the transaction session.commit ();
} Catch (IOEXCEption E) {
e.printstacktrace (); Erated Catch blocks Resources.getResourceAsReader("configuration.xml"); // Build SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); // Get the user interface object
           UserMapper userMapper = session.getMapper(UserMapper.class); / Call the query method
        User user = userMapper.selectUserById(6);               user.setName("I remember what it was called");                 user.setAddress("Magic City Shanghai"); userMapper.updateUser(user) ; ;                // Load configuration file
          try {
                reader = Resources .getResourceAsReader ("Configuration.xml"); // Establish SqlSessionFactory
SQLSessionFactory = New SqlSessionFactoryBuilder (). oni session = sqlSessionFactory.Opension (); // Get the user interface object
usermapper usermapper = Session.getMapper (usermapper.class);
// Delete
usermapper.Deleteuse (6); // Submit transaction session.commit ();e.printStackTrace();



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!