Basic Use of MyBatis

Keywords: Mybatis xml SQL Database

MyBatis is a lightweight ORM library. MyBatis can store POJO classes into databases or convert data from databases into POJO classes. Unlike Hibernate and other libraries, MyBatis recommends using the way of writing SQL statements in XML configuration to convert data, which greatly improves flexibility. Here is a simple example to illustrate the use of MyBatis.

1. Adding class libraries

There are very few class libraries needed to use MyBatis. One is the core library of MyBatis and the other is the database driver library. Here we use mybatis-3.4.4.jar and mysql-connector-java-5.1.38.jar.

2 Create database tables

We need to create a database table for a city. The fields of the table include id, city name, country, province, accuracy and latitude. The table structure is as follows:

3. Configure MyBatis configuration file

In the SRC directory of the project, or in other directories, create a config.xml configuration file, which describes the basic configuration of accessing the database and the mapping file of POJO class operations. The configuration is 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 alias="City" type="com.app.heweather.City"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/weather_db"/>
                <property name="username" value="root"/>
                <property name="password" value="111111"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="city.xml"/>
    </mappers>
</configuration>

The basic information of database access is described in the Environment tag, and the XML description file for specific POJO object operation is specified in the mapper tag, which corresponds to the city.xml file.

4. Configure city.xml file

<?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.app.heweather.CityMapper">

    <insert id="insertAllCity" parameterType="com.app.heweather.City" useGeneratedKeys="false">
        insert into tb_city (id, city, cntv, province, lat, lon) values
       <foreach collection="list" item="item" index="index" separator=",">
             (#{item.id}, #{item.city}, #{item.cntv}, #{item.province}, #{item.latitude}, #{item.longitude})
       </foreach>
    </insert>
</mapper>

This file represents the operation of all databases, namespace represents the namespace of the method, id represents the name of the method, parameterType represents the type of the parameter, and inside the insert tag is the sql execution statement. Here, a foreach tag is used to indicate the batch insertion, followed by instructions. This configuration is all ok, so how should we use it in the code, and then look at the following.

5. Building SQLSession Class

All our SQL execution actions are executed in SQL Session, so building SQL Session is what we need to do.

public class BasicOperator {

    protected static SqlSessionFactory factory;
    protected static Reader reader;

    static{
        try{
            reader = Resources.getResourceAsReader("config.xml");
            factory = new SqlSessionFactoryBuilder().build(reader);
        }catch (Exception e){
            e.printStackTrace();
        }


    }
}
public class CityOperator extends BasicOperator{
    private static CityOperator co = new CityOperator();

    public CityOperator(){

    }

    public static CityOperator getInstance(){
        return co;
    }

    public void insertAllCity(List<City> allCities){
        SqlSession session = factory.openSession();
        int count;
        try{
           count = session.insert("com.app.heweather.CityMapper.insertAllCity", allCities);
           System.out.println(count);
           session.commit();
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }

}

The code is also clear. First, we use the SQLSessionFactory Build class to construct an SQLSessionFactory class. Then we use the openSession method of the SQLSessionFactory class to create an SQLSession. We call the insert method of the SQLSession to insert the data. The first parameter of the insert is the method name we just defined in city.xml. We use the namespace + method name. Write, and the second parameter is the type of List

6. Call

public class WeatherToDb {

    public static void main(String[] args) throws Exception{
        URL url = new URL("https://cdn.heweather.com/china-city-list.json");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        InputStream ins = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
        StringBuffer buffer = new StringBuffer();
        String lines = null;
        while((lines = reader.readLine()) != null){
            buffer.append(lines);
        }
        reader.close();
        String result = buffer.toString();
        Gson gson = new Gson();
        List<City> cities = gson.fromJson(result,new TypeToken<List<City>>(){}.getType());
        CityOperator.getInstance().insertAllCity(cities);
    }
}

The results are as follows:

Posted by gogul on Wed, 26 Jun 2019 11:42:45 -0700