1. Mybatis is introduced:

(1).MyBatis is an excellent Java-based persistence layer framework, which encapsulates JDBC internally, so that developers only need to pay attention to THE SQL statement itself, but do not need to spend energy to deal with loading driver, creating connection, creating statement and other complicated process.

(2). Configure various statements to be executed by means of XML files or annotations, and generate SQL statements to be executed by mapping Java objects and dynamic parameters of SQL in the statement. Finally, the MyBatis framework executes the SQL and maps the result to a Java object and returns it.

(3) Advantages: simplified JDBC, can execute SQL statements, SQL into Java objects

2. Basic MyBatis implementation needs to define entity class, Dao interface, Dao interface Mapper file, MyBatis main configuration file. (1) Entity class: define the attributes of the entity, set the attributes,get methods, override the toString method (2)Dao interface: define the methods to operate the database (3)Mapper file: write SQL statements, and map the Dao interface method (4) Main configuration file: Write database information, Mapper file location

Step: Add myBatis dependency, mysql driver, define DAO interface, define mapper file, define main configuration file, use SQLSession object to execute SQL statement

Public class Customer {// attribute //set get method //toString method}}Copy the code
Public interface CustomerDao {public List<Customer> findAll(); public List<Customer> findLike(String name); public int insert(Customer customer); public int delete(int id); public int update(Customer customer); }Copy the code
// Mapping file <mapper Namespace =" com.yuan.dao.customerDAO "> <select ID ="findAll" resultType=" com.yuan.domain.customer "> select * from customer </select> <select id="findLike" resultType="com.yuan.domain.Customer"> select * from customer where cust_name like #{name} </select> <insert id="insert"> insert into customer(cust_id,cust_name) values(#{cust_id},#{cust_name}) </insert> <update id="update"> update customer cust_name=#{type_name} where cust_id=#{cust_id} </update> <delete id="delete"> delete from customer where cust_id=#{typeId} </delete> </mapper>Copy the code
<environment id="mydev"> <transactionManager type="JDBC"/> mybatis <configuration> <environments default="mydev">  <dataSource type="POOLED"> <! <property name="driver" value=" com.mysql.jdbc.driver "/> <! - connect to the database url string - > < property name = "url" value = "JDBC: mysql: / / localhost: 3306/18 jxnu_boot" / > <! <property name="username" value="root"/> <! /> </dataSource> </environment> </environments> <! -- SQL mapper file location --> <mappers> <! A mapper tag specifies the location of a file. Path information from the classpath. The target/clasess (class path) -- - > < mapper resource = "com/yuan dao/CustomerDao. XML" / > < mapper resource = "com/yuan dao/UserDao. XML" / > </mappers> </configuration>Copy the code

3. The SqlSessionFactoryBuilder is, SqlSessionFactory, SqlSession analysis

SqlSessionFactoryBuilder as you can see from the name, this is a Builder class that creates an SqlSessionFactory

SqlSessionFactory is, as the name implies, the factory used to produce SQLSessions.

The SqlSession contains all the methods used to execute SQL

4. Encapsulate the sqlSession object as a tool class

Public class MyBatisUtils {private static SqlSessionFactory factory = null; static { String config="mybatis.xml"; Try {/ / Resources is responsible for the main distribution value file InputStream in = Resources. The getResourceAsStream (config); // Create an SqlSessionFactory object using SqlSessionFactoryBuild Factory = new SqlSessionFactoryBuilder().build(in); } catch (IOException e) { e.printStackTrace(); Public static SqlSession getSqlSession() {SqlSession SqlSession = null; if( factory ! = null){ sqlSession = factory.openSession(); } return sqlSession; }}Copy the code

5. Dynamic proxy of Mybatis:

Sqlsession.getmapper () uses JDK dynamic proxy to generate a proxy object for the target Mapper interface.

Execute (sqlSession, args). MapperMethod. Execute (sqlSession, args).

/ / test methods public void TestFindAll () throws IOException {SqlSession session. = MyBatisUtils getSqlSession (); CustomerDao dao = session.getMapper(CustomerDao.class); // Dynamic proxy: the session.getMapper() method internally generates a CustomerDao implementation class. List<Customer> customers = dao.findAll(); For (Customer cust: customers){system.out.println (" Customer ="+cust); } session.close(); }Copy the code

6. Query multiple tables

You need to use resultMap to associate the result set mapping

<mapper namespace="com.yuan.dao.UserDao">
    <resultMap id="cust_user" type="com.yuan.domain.Sys_user">
        <result column="cust_name" property="customer.cust_name"/>
    </resultMap>
    <select id="findAll" resultMap="cust_user">
        select sys_user.user_id,customer.cust_id,customer.cust_name,customer.cust_address,sys_user.user_name from sys_user inner join customer on customer.cust_id=sys_user.cust_id
    </select>
</mapper>
Copy the code

What is the difference between #{} and ${}?

(1)Mybatis will replace #{} with? (2)Mybatis can effectively prevent SQL injection and improve system security by using #{}. # is a pre-compilation process, and $is a string replacement

Methods in the Dao interface have only one simple type (Java primitive type and String) with placeholder #{any character}, independent of the method’s parameter name. (2) Multiple parameters – Use @param when Dao interface methods have multiple parameters, need to use the parameters by name. Add @param (” custom parameter name “) before the method parameter and use #{custom parameter name} in the mapper file.

9. ResultType Execute SQL to obtain the type of the ResultSet transformation, using the fully qualified name or alias of the type. Note that if it returns a set, it should be set to the type contained in the set, not the set itself. ResultType and resultMap cannot be used together. The returned type uses the constructor to create the object. Call setXXX to assign a value to the property.