tags: Mybatis


Interpret configuration files and mapping files

The mapping file

The mapper. XML file is configured with many SQL statements. Each SQL statement is encapsulated as an MappedStatement object when executed

The actual location of the Statement is namespace+StatementId

Configuration file ##

The alias

TypeAliases alias:

Custom aliases:


	<! -- Define alias -->
	<typeAliases>
		<! Alias: alias, type: type of alias mapping -->
		<! -- <typeAlias type="cn.itcast.mybatis.po.User" alias="user"/> -->
		<! -- Batch alias definition specifies the package path, automatically scans the poJOs below the package, and defines the alias. The default alias is the class name (lowercase or uppercase) -->
		<package name="cn.itcast.mybatis.po"/>
		
	</typeAliases>
Copy the code

Mapper load


	<mappers>
		<! -- Reference mapper's mapping file with resource -->
		<mapper resource="sqlmap/User.xml" />
		<! -- <mapper resource="mapper/UserMapper.xml" /> -->
		<! Mapper. XML and mapper. Java must be the same name and in the same directory.
		<! -- <mapper class="cn.itcast.mybatis.mapper.UserMapper"/> -->
		<! Mapper. XML and mapper. Java must be the same name and in the same directory.
		<package name="cn.itcast.mybatis.mapper"/>
	</mappers>
Copy the code

Mybatis solves JDBC programming problems

1. Frequent creation and release of database links waste system resources and thus affect system performance. This problem can be solved by using database link pools.

  • Solution: Configure a data link pool in sqlmapconfig. XML and use the connection pool to manage database links.

2, THE Sql statement written in the code causes the code is not easy to maintain, the actual application of Sql changes may be large, Sql changes need to change the Java code.

  • Solution: Separate the Sql statement configuration from the Java code in xxxxmapper.xml.

3. It is difficult to pass parameters to SQL statements, because SQL statements where conditions are not necessarily, may be more or less, placeholders need to correspond with parameters one by one.

  • Mybatis automatically maps Java objects to SQL statements. ParameterType in statement defines input parameter types.

4, the result set parsing is troublesome, SQL changes lead to parsing code changes, and before parsing need to traverse, if the database records can be encapsulated into POJO object parsing is more convenient.

  • Solution: Mybatis automatically maps SQL execution results to Java objects. ResultType in statement defines the type of output results.

A placeholder

In Mybatis, there are two placeholders

  • #{} parses the parameter data passed in
  • ${} concatenates the parameters passed in as is in SQL

Primary key generation policy

If we are in Hibernate, when we insert data, we can choose the UUID policy…

So how to do in Mybatis?

UUID


	<! Mysql > create primary key for uUID
	<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
		<selectKey keyProperty="id" order="BEFORE" resultType="string">
			select uuid()
		</selectKey>
		
		INSERT INTO USER(id,username,birthday,sex,address) VALUES(#{id},#{username},#{birthday},#{sex},#{address})
	</insert> 
Copy the code

The primary key to return to

If we normally insert data, if we want to know what the primary key of the data we just inserted is, we can do the following

Requirements:

  • After the User object is inserted into the database, the primary key of the new record is returned through the User object, through which the primary key value is obtained.

Solution:

  • Obtain the auto-increment primary key value of the newly inserted record by 1285822. After the INSERT statement, execute select 1285822 to obtain the auto-increment primary key value.

mysql:

	<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
		<selectKey keyProperty="id" order="AFTER" resultType="int">
			select 1285822
		</selectKey>
		INSERT INTO USER(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
	</insert>
Copy the code

oracle:

Implementation idea:

  • Query the sequence to get the primary key, set the primary key to the user object, and insert the User object into the database.

	<! Nextval () from dual Set the maximum value of the sequence to the id attribute of the user object -->
	<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
		<selectKey keyProperty="id" order="BEFORE" resultType="int">Nextval () from dual</selectKey>INSERT INTO USER (id, username, birthday, sex, address) VALUES (sequence. Nextval (), # {username}, # {birthday}, # {sex}, # {address})</insert> 
Copy the code

Mapper agent mode

Mapper proxy means: programmers only need to write DAO interface, dao interface implementation object automatically generated by MyBatis proxy object.

DaoImpl = DaoImpl = DaoImpl = DaoImpl = DaoImpl = DaoImpl = DaoImpl = DaoImpl = DaoImpl

1 there are duplicate codes in the implementation class of DAO, and the code template of the whole Mybatis operation is repeated (first create SQLSession, call SQLSESSION method, close SQLSession).

2. There is hard coding in the DAO implementation class. The ID of statement is hard coded when the SQLSession method is called.


Previous duplicates and hard coding are as follows:


public class StudentDao {

    public void add(Student student) throws Exception {
        // Get the connection object
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        try{
            // Map file namespace. The ID of the SQL fragment can call the SQL in the corresponding mapping file
            sqlSession.insert("StudentID.add", student);
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{ MybatisUtil.closeSqlSession(); }}public static void main(String[] args) throws Exception {
        StudentDao studentDao = new StudentDao();
        Student student = new Student(3."zhong3".10000D); studentDao.add(student); }}Copy the code

Mapper development specification

If Mybatis wants to help us automatically generate Mapper agents, we need to follow the following specifications:

1. In mapper. XML, namespace is specified as the fully qualified name of the Mapper interface

  • The purpose of this step is to associate mapper. XML with mapper. Java.

2. The statement ID in mapper. XML is the name of mapper. Java

ParameterType of statement in mapper. XML is the same as that of method input parameters in mapper. Java

4. The resultType of statement in mapper. XML is the same as the return value of the method in mapper. Java.

The statement is the id specified in the mapper. XML namespace + SQL

Mapper agent return value problem

Mapper interface method return value:

  • If it is a single object returned, the return value is of type POJO, and the generated proxy object gets the record internally via selectOne
  • If the return value type is a collection object, the generated proxy object internally retrieves the record through a selectList.

conclusion

  • The SQL statement invoked in the program is composed of the command space of the mapping file + the ID of the SQL fragment. It generates a Statement object internally.
  • You can specify the package name when using an alias, or when loading a mapping file using the general configuration file.
  • Primary keys, if returned, use the selectKey tag. The UUID can also be returned. In Oracle, sequences are used to return auto-growing primary keys.
  • Since the DaoImpl written earlier is quite hard coded. You can use a Mapper agent to simplify development
    • The namespace should be the same as the full class name of the JavaBean
    • The ID of the SQL fragment statement must be the same as the method name of the Dao interface
    • The parameters and return values of the method must be the same as the received parameter types and return types of the SQL fragment.
  • There are two kinds of placeholders, one is to parse the passed in parameter data, and one is to output the passed in data as is.

If you find this article helpful, give the author a little encouragement