samwellwang

samwellwang

coder
twitter

MyBatis Learning

During the pandemic, to enrich myself (laugh, learn about M in SSM)

2020-02-10

During the pandemic, to enrich myself (laugh, learn about M in SSM)

MyBatis Introduction#

According to the README on the open-source repository on GitHub:
The MyBatis SQL mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using an XML descriptor or annotations. Simplicity is the biggest advantage of the MyBatis data mapper over object-relational mapping tools.
MyBatis SQL is a mapping framework that simplifies the use of relational databases when writing object-oriented applications. MyBatis combines objects with SQL statements or stored procedures using XML or annotations. The biggest advantage of MyBatis over object-relational mapping tools is its simplicity.
So, to put it simply, MyBatis is a tool that makes it convenient for us to use databases in programs, similar to something our company currently uses called DE. Both are ORM persistence layer frameworks that encapsulate JDBC. I understand there is another one called Hibernate. The main difference between them is that MyBatis uses native SQL, while Hibernate has its own set of statements called HQL. Compared to what our company has, it resembles Hibernate more, but is done poorly. Custom query statements are one thing, but it doesn't even have a modulus function. I remember needing to write an interface to query the age and gender from an ID number, which didn't match what was actually stored in the database. Determining gender really puzzled me. I didn't expect to solve it with just a '%', but at least provide something like MOD(). In the end, I had to use decode to enumerate 0-9, custom defining odd (male) and even (female) numbers. Given that our company's tool is too... well, it's good to learn about this thing.

Getting to Know MyBatis#

Of course, learning a new framework starts with setting it up. For now, everything I've encountered is to simply add a dependency to the project through Maven, which will automatically load the jar package.

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
     <version>3.2.8</version>
 </dependency>

Show me your code!#

Next comes the most exciting coding part.
First, we need to write a simple entity class for Car POJO.

package com.MyBatis;
 
public class Car {
    private int id;
    private String name;
    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;
    }
     
}

Then, add a mapper interface to map the entity class to the database using annotations.

package com.Mybatis.mapper;
  
import java.util.List;
 
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
 
import com.how2java.Mybatis.Car;
  
public interface CarMapper {
  
    @Insert(" insert into car ( name ) values (#{name}) ") 
    public int add(Car Car); 
        
    @Delete(" delete from car where id= #{id} ") 
    public void delete(int id); 
        
    @Select("select * from car where id= #{id} ") 
    public Car get(int id); 
      
    @Update("update car set name=#{name} where id=#{id} ") 
    public int update(Car Car);  
        
    @Select(" select * from car ") 
    public List<Car> list(); 
}

Add MyBatis's main configuration file 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>
    <typeAliases>
      <package />
    </typeAliases>
    <environments default="development">
        <environment>
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
            <property />
            <property />
            <property />
            <property />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/Mybatis/pojo/Car.xml"/>
        <mapper/> 
    </mappers>
</configuration>

Write a test class for testing CURD operations.

package com.how2java;
   
import java.io.IOException;
import java.io.InputStream;
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.Mybatis.mapper.CarMapper;
import com.how2java.pojo.Car;
   
public class TestMybatis {
   
    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        CarMapper mapper = session.getMapper(CarMapper.class);
  
//        add(mapper);
//        delete(mapper);
//        get(mapper);
//        update(mapper);
        listAll(mapper);
              
        session.commit();
        session.close();
   
    }
  
    private static void update(CarMapper mapper) {
        Car c= mapper.get(8);
        c.setName("Modified Car Name");
        mapper.update(c);
        listAll(mapper);
    }
  
    private static void get(CarMapper mapper) {
        Car c= mapper.get(8);
        System.out.println(c.getName());
    }
  
    private static void delete(CarMapper mapper) {
        mapper.delete(2);
        listAll(mapper);
    }
  
    private static void add(CarMapper mapper) {
        Car c = new Car();
        c.setName("Newly Added Car");
        mapper.add(c);
        listAll(mapper);
    }
   
    private static void listAll(CarMapper mapper) {
        List<Car> cs = mapper.list();
        for (Car c : cs) {
            System.out.println(c.getName());
        }
    }
}

Well, the basic CURD is basically done. Actually, you can also use an XML configuration file to do the middle layer between the database and entity objects, but that's too cumbersome. I guess no one uses that in formal development; everyone probably uses annotations. I'll ask other friends tomorrow.

Thanks to how2j webmaster!

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.