MyBtis (a) - acquaintance MyBatis

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/QQ2899349953/article/details/97617037

mybatis Basics

MyBatis is a realization of open source data persistence framework , in fact, it is like netty does for NIO, Mybatis is JDBC package, so:

JDBC disadvantages:

  1. Require frequent establish a database connection, disconnect operation, waste of resources, affect database performance;

    Solution: Connection Pool

  2. Coding SQL statements directly in Java code, when requirements change, you need to modify Java code;

    Resolution: The SQL statement and code separately, SQL statements in a configuration file

  3. Returns a result set JDBC programming problem exists hardcoded

    Solution: The result set is mapped to Java objects

MyBatis advantages:

  1. Compared with the JDBC, reducing the amount of code more than 50%.

  2. MyBatis is the easiest persistence framework, compact and easy to learn.

  3. MyBatis quite flexible, does not impose any impact on the existing application or database design, SQL written in XML, complete separation from the program code, reduce the degree of coupling, to facilitate unified management and optimization, and can be reused.

  4. XML tags provide support the preparation of dynamic SQL statements.

  5. Providing a mapping label, field support ORM object-relational mapping database, the object can be mapped to a tuple in the table, the mapping table may be tuples into objects;

MyBatis framework of disadvantages:

  1. Write SQL statements larger workload, especially in the field more, the association table for a long time, even more so, to write SQL statements to developer skills have certain requirements.

  2. SQL statement depends on the database, resulting in poor portability database, the database can not be replaced.

MyBatis and Hibernate difference:

For mapping layer, Hibernate's configuration does not require an interface and SQL, contrary MyBatis is needed for Hibernate, do not need to write a lot of SQL, you can be completely mapped, while providing a log, cache, cascade (cascade MyBatis powerful than) and other features, easy to use, but at the same time, Hibernate also there is a huge flaw;

MyBatis free to write SQL, support for dynamic SQL, processing lists, dynamically generated table, support for stored procedures, so that you can define flexible query to meet the various needs and performance optimization needs, then these Internet system is very important of;

But MyBatis also flawed, he wants to write SQL and mapping rules, its workload is greater than Hibernate, secondly, it supports tools are also very limited, not that there are like Hibernate many plug-ins can help generate mapping code and relationships, and even use the generated tools, a developer often needs to be further simplified, by hand coding MyBatis, the workload is relatively large, and therefore the performance less demanding systems, preferably using Hibernate, requirements for high performance, fast response, the system is flexible recommended MyBatis;

MyBatis compared with Hibernate main advantages:

MyBatis not shielded SQL, so developers can customize their own SQL, without automatically generated (at the same time disadvantage is that heavy workload, take some learning costs), which can be more precisely defined SQL, to optimize performance, high concurrency in line with the mobile Internet , data require large, high performance, high response;

MyBatis framework Applications:

MyBatis focused on SQL itself, is a sufficiently flexible DAO layer solutions. High performance requirements, or more changes in project requirements, such as the Internet project, MyBatis would be a good choice.

Mybatis entry-level use

1, into mybatis dependency:

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

2, also need to rely on the database:

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

3, introduced above, MyBatis provides a mapping between table and tuple objects, it is necessary to build a table, where a Student:

create table Student(
    SID int(10) primary key,
    Sname varchar(20),
    Ssex varchar(10),
    Age int(10)
);

Here Insert Picture Description
Then add some data in this table inside, so back to test, just fill in a few will be able to:
Here Insert Picture Description

4, create the corresponding Student object:

/**
 * @ClassName Student
 * @Description
 * @Author lzq
 * @Date 2019/7/26 13:53
 * @Version 1.0
 **/
public class Student {
    private int SID;
    private String Sname;
    private String Ssex;
    private int Age;

    public int getSID() {
        return SID;
    }

    public void setSID(int SID) {
        this.SID = SID;
    }

    public String getSname() {
        return Sname;
    }

    public void setSname(String sname) {
        Sname = sname;
    }

    public String getSsex() {
        return Ssex;
    }

    public void setSsex(String ssex) {
        Ssex = ssex;
    }

    public int getSage() {
        return Age;
    }

    public void setSage(int sage) {
        Age = sage;
    }

    @Override
    public String toString() {
        return "[id"+SID+" 名字"+Sname+" 性别"+Ssex+" 年龄"+Age+"]";
    }
}

5, adding the config.xml MyBatis global configuration file (the file name can be customized, mybatis-config.xml as used herein)

Note the use of its own database name, your root user password:

<?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>

    <!--数据源配置-->
    <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/mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    
</configuration>

Note that this xml file on the same level with the Java file resources (the name can be from their own, but must be a configuration file, folder icon is below 4 yellow Henggang) file the following:
Here Insert Picture Description
6, there are two ways to develop MyBatis :
use the configuration or use of annotations;

Use the configuration words:
you need to create a custom interface, but does not need to implement this interface, implemented by Mapper proxy:

Below, create StudentMapper interfaces:

public interface StudentMapper {
    public Student getStudentById(int id);  //根据给定id查找并返回对象
}

Create StudentMapper.xml file, also placed below resources, as shown above, document reads as follows:

<?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="tulun.dao.StudentMapper">
    <select id="getStudentById" parameterType="java.lang.Integer" resultType="tulun.bean.Student">
        select * from student where SID = #{SID}
    </select>
</mapper>

Here Insert Picture Description
statement tab to select the insert, delete, update, select SQL based on business execution.

MyBatis will automatically create proxy object UserDAO interface implementation class according to the rules.

Rules are as follows:

  1. StudentMapper.xml the namespace for the interface of the full class name.
  2. StudentMapper.xml statement in the id of the interface method corresponding to the name.
  3. ParameterType same parameter types, and the corresponding method StudentMapper.xml interfaces in the statement.
  4. StudentMapper.xml resultType in the statement and return value consistent interface corresponding to the type of method.

Now you need to register StudentMapper.xml in the global configuration file mybatis-config.xml in:
that is, add the following sentence in the above mybatis-config.xml inside:

    <mappers>
        <mapper resource="StudentMapper.xml"/>
    </mappers>

Here Insert Picture Description
Test code:

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 tulun.bean.Student;
import tulun.dao.StudentMapper;

import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName Test
 * @Description
 * @Author lzq
 * @Date 2019/7/26 13:53
 * @Version 1.0
 **/
public class Test {
    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        //读取配置文件
        InputStream asStream = Resources.getResourceAsStream(resource);
        //创建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(asStream);
        //创建sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //通过动态代理产生StudentMapper对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student student = mapper.getStudentById(2);  //获取id为2的数据的对象
        System.out.println(student);
    }
}

operation result:

[id2 名字jmj 性别nan 年龄20]

Use annotations words:
basic, like the above, but do not write the SQL statements inside StudentMapper.xml, need only StudentMapper.xml inside it:

<?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="tulun.dao.StudentMapper">
</mapper>

Then write just fine in StudentMapper inside:

public interface StudentMapper {
    @Select("select * from student where SID = #{id}")
    public Student getStudentById(int id);  //根据给定id查找并返回对象
}

Notes SQL statement is followed, the following is the corresponding CRUD methods:

public interface StudentMapper {    
    @Select("select * from student where SID = #{id}")
    public Student getStudentById(int id);

    @Select("select * from student where Sname = #{name} and Age = #{age}")
    public Student getSnameAndSage(@Param("name") String name, @Param("age") int age);

    @Select("select * fom student")
    public Student[] getAllStudent();

    @Insert("insert into student (SID,Sname) values(#{SID},#{Sname})")
    public void addStudent(Student student);

    @Delete("delete from student where Sid = #{id}")
    public void delete(int id);

    @Update("update student set Sname = #{name} where id=#{id}")
    public void setValue(@Param("id") int id,@Param("name") String name);
}

Note: In the relatively large number of parameters, the need to add @Param (parameter name), it's no where to put sql statement which parameters do not know in front of the interface parameter type, so you can specify the parameters of which are given ;

Test code:

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 tulun.bean.Student;
import tulun.dao.StudentMapper;

import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName Test
 * @Description
 * @Author lzq
 * @Date 2019/7/26 13:53
 * @Version 1.0
 **/
public class Test {
    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        //读取配置文件
        InputStream asStream = Resources.getResourceAsStream(resource);
        //创建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(asStream);
        //创建sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //通过动态代理产生StudentMapper对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        //查询id为2的元组
        Student student = mapper.getStudentById(2);
        System.out.println(student);

        //往数据库添加新的元组
        Student student1 = new Student();
        student1.setSID(4);
        student1.setSname("xxx");
        mapper.addStudent(student1);
        
        Student student2 = new Student();
        student1.setSID(9);
        student1.setSname("xxx");
        mapper.addStudent(student2);
        sqlSession.commit();
        sqlSession.commit();

        //返回列表所以元素
        Student[] students = mapper.getAllStudent();
        for (Student s : students) {
            System.out.println(s);
        }
    }
}

operation result:

Here insert the code sheets

Guess you like

Origin blog.csdn.net/QQ2899349953/article/details/97617037