MyBatis basic usage

Posted by konetch on Wed, 12 Jan 2022 20:08:11 +0100

1 Introduction to mybatis

1.1 what is MyBatis

  • MyBatis is an excellent persistence layer framework, semi-automatic ORM

  • It supports custom SQL, stored procedures and advanced mapping. MyBatis eliminates almost all JDBC code, setting parameters and obtaining result sets. MyBatis can configure and map primitive types, interfaces and Java POJO s (Plain Old Java Objects) as records in the database through simple XML or annotations

  • MyBatis was originally a part of apache Open source project iBatis, 2010 project Migrated from apache software foundation to google code , and renamed MyBatis. Moved to in November 2013 Github

1.2 why learn MyBatis

  • Easy to learn: itself is small and simple. There is no third-party dependency. The simplest installation is as long as two jar files + several sql mapping files are configured. It is easy to learn and use. You can fully master its design idea and implementation through documents and source code.

  • Flexibility: mybatis does not impose any impact on the existing design of the application or database. sql is written in xml for unified management and optimization. All requirements for operating the database can be met through sql statements.

  • Decouple sql and program code: by providing DAO layer, separate business logic and data access logic, so as to make the system design clearer, easier to maintain and easier to unit test. The separation of sql and code improves maintainability.

  • Provide mapping labels to support the mapping of orm fields between objects and databases

  • Provide object relationship mapping labels to support object relationship construction and maintenance

  • Provide xml tags to support writing dynamic sql

  • Compared with JDBC, it is easy to use. Compared with Hibernate, the first is the low learning cost (method, cache)

2 getting started with mybatis

2.1 development steps of mybatis

 

The MyBatis icon needs to download the plug-in MyBatisX, and lombok also needs to download the plug-in (file -- > settings -- > plugins)

  • Build environment and guide package

  • Write MyBatis core configuration file (configuration.xml)

  • Write code

  • test

2.2 construction environment

Create a new module and import maven

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

2.3 write the core 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>

    <!-- read db.properties Contents of the document -->
    <properties resource="db.properties">
        <!-- If properties With a heel in the middle name Same attributes, subject to the document -->
        <property name="password" value="123456"/>
    </properties>

    <!-- Displays the executed in the console sql sentence -->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!-- If you set an alias for a parameter, you don't have to write the full qualified name -->
    <typeAliases>
        <package name="cn.blb.mybatis01.pojo"/>
    </typeAliases>

    <!-- Multiple environments default Select environment id-->
    <environments default="development">
        <environment id="development">
            <!-- affair - default JDBC -->
            <transactionManager type="JDBC"/>
            <!-- data source -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!-- Mapping is used to register the interface with the implementation class -->
    <mappers>
        <mapper resource="cn/blb/demo02/mapper/mapper.xml"/>
    </mappers>
</configuration>

2.4 db.properties database connection file

driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///person?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=root

2.5 coding

  • Entity class
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Staff {
  private int id;
  private String name;
  private int age;
  private String address;
}
  • Dao interface
public interface StaffDao {

    // Query all
    List<Staff> selectAll();

    // add to
    int insertStall(Staff staff);

    // delete
    int deleteStall(int id);

    // modify
    int updateStall(Staff staff);
}
  • Interface implementation class
<?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">
<!-- namespace So it is realized interface,amount to implements -->
<mapper namespace="cn.blb.demo02.dao.StaffDao">

    <!--
        id = Implemented method name
        resultType = return type
    -->
    <!--Query all-->
    <select id="selectAll" resultType="cn.blb.demo02.pojo.Staff">
        select * from staff;
    </select>

    <!--add to-->
    <insert id="insertStall">
        insert into staff value(#{id},#{name},#{age},#{address})
    </insert>

    <!--delete-->
    <delete id="deleteStall">
        delete from staff where id = #{id}
    </delete>

    <!--modify-->
    <update id="updateStall">
        update staff set name = #{name},age = #{age},address = #{address} where id = #{id}
    </update>

</mapper>
  • Writing test classes
public class test01 {

    SqlSessionFactory sqlSessionFactory;

    @Before
    public void beforeTest() throws IOException {
        // The relative path is the resource under resources
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void selectAll(){
        // Sqlsession is equivalent to a statement object, which is used to operate the database
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // Gets the type of the mapper object interface
        StaffDao staffDao = sqlSession.getMapper(StaffDao.class);
        List<Staff> list = staffDao.selectAll();
        list.forEach(System.out::println);
    }

    @Test
    public void insertStaff(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StaffDao staffDao = sqlSession.getMapper(StaffDao.class);
        Staff staff = new Staff();
        staff.setName("Passerby a");
        staff.setAge(28);
        staff.setAddress("Nanchang");
        int i = staffDao.insertStall(staff);

        // Manually commit transactions - add, delete. Modification is required
        sqlSession.commit();
        System.out.println("i = " + i);
    }

    @Test
    public void deleteStaff(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StaffDao staffDao = sqlSession.getMapper(StaffDao.class);
        int i = staffDao.deleteStall(5);

        // Manually commit transactions - add, delete. Modification is required
        sqlSession.commit();
        System.out.println("i = " + i);
    }

    @Test
    public void updateStall(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StaffDao staffDao = sqlSession.getMapper(StaffDao.class);
        Staff staff = new Staff();
        staff.setId(3);
        staff.setName("Wang Wuwu");
        staff.setAge(25);
        staff.setAddress("Beijing");
        int i = staffDao.updateStall(staff);

        // Manually commit transactions - add, delete. Modification is required
        sqlSession.commit();
        System.out.println("i = " + i);
    }
}

Topics: Java Database Mybatis