First of all, Mybatis is an excellent ORM framework of persistence layer, which encapsulates the process of OPERATING database of JDBC, making developers only need to pay attention to SQL itself. There is no need to deal with repetitive and tedious steps. Finally, the Java object is mapped to the SQL in the Statement to generate the SQL statement that is executed. Finally, the mysql framework executes the SQL and maps the results to Java objects and returns them.
ORM: Object-relational mapping, simply put, is to establish a mapping relationship between the tables in the database and the objects in Java, allowing us to operate objects to operate the database indirectly.
Semi-orm: When querying associated objects or associated collection objects, you need to write SQL manually to do this.
MyBatis programming steps
- Create a SqlSessionFactory
- Create an SqlSession with SqlSessionFactory
- Perform database operations using sqlSession
- Call session.mit () to commit the transaction
- Call session.close to close the session
How MyBatis works
- Read MyBatis configuration file. (Obtain the operating environment of MyBatis and other information)
- Load the mapping file. (SQL mapping file where SQL statements are configured to operate on the database)
- Construct session Factory: Build session factory SqlSessionFactory with MyBatis environment configuration information
- Create session objects: There is a session factory to create the SqlSession object, which contains all the methods for executing SQL statements
- Executor Executor: Dynamically generates SQL statements to be executed based on SqlSession parameters and maintains the query cache
- Mappedstatement object: Stores information such as IDS and parameters of SQL statements to be mapped
- Input parameter mapping: Parameter types can be set types such as Map, List, or basic data types and POJO types
- Output result mapping: Similar to input.
The advantages of MyBatis
- Based on SQL statement programming, quite flexible. SQL is written in XML to decouple SQL from program code for unified management. Provides XML tags that support writing dynamic SQL statements and can be reused
- Eliminates a lot of JDBC redundant code, no need to manually switch the connection;
- Good compatibility with various databases
- Good integration with Spring;
- Provide mapping labels to support ORM field relational mapping between objects and databases; Provides object-relational mapping labels to support object-relational component maintenance.
Disadvantages of MyBatis framework
- SQL statement writing workload is large, especially when there are many fields, associated tables, for developers to write SQL statement skills have certain requirements.
- SQL statements depend on databases, which leads to poor database portability. Therefore, databases cannot be replaced at will.
MyBatis is different from Hibernate
- MyBatis is a semi-ORM framework, which needs to write ITS own SQL statements, which has high flexibility, but needs to customize multiple SETS of SQL mapping files, and has a large workload
- Hibernate database has good irrelevance, saves code and improves efficiency
The difference between #{} and ${}
- #{} : this is precompiled, and will replace the SQL statement #{} with? Call the set method in PreoaredStatement to assign the value
- : is string replacement, used for tag attribute values and SQL internal, a static text replacement. {} : is a string replacement, used for tag attribute values and SQL internal, is a static text replacement. The: is a string replacement, used for tag attribute values and SQL internal, is a static text replacement. Replace {} with the value of the variable.
Using #{} can effectively prevent SQL injection and improve system security.
What if the attribute name of the entity class does not match the field name in the table
-
Make the alias of the field name consistent with the attribute name of the entity class by defining the alias of the field name in the SQL statement of the query.
-
A one-to-one mapping between field names and entity-class attribute names by class mapping
-
Fuzzy query like how to write
- Add SQL wildcards to Java code
- Concatenating wildcards in SQL statements (but causing SQL injection problems)
Typically, an Xml mapping file will write a Dao interface corresponding to it. So how does the Dao interface work?
The Dao interface is the Mapper interface.
- The fully qualified name of the interface is the value of the namespace of the mapping file
- The interface method name is the ID of the Statement of the Mapper in the mapping file
- The parameters inside the interface methods are the parameters that are passed to SQL
The Mapper interface has no implementation class. When an interface method is called, the interface’s fully qualified name + the method name concatenation string is used as the key value to uniquely locate a MapperStatement. MyBatis (MyBatis, MyBatis, MyBatis, MyBatis, MyBatis (MyBatis, MyBatis) MyBatis (MyBatis, MyBatis) MyBatis (MyBatis) MyBatis (MyBatis) MyBatis (MyBatis) MyBatis (MyBatis) MyBatis (MyBatis) MyBatis (MyBatis) MyBatis (MyBatis) MyBatis (MyBatis) MyBatis (MyBatis) MyBatis So you can’t reload. Mapper interface works by JDK dynamic proxy. MyBatis will use JDK dynamic proxy to generate proxy object for Mapper interface. The proxy object intercepts interface methods, executes SQL represented by MapperStatement, and returns SQL execution results. MyBatis uses the RowBounds object for paging, which is memory paging performed against ResultSet result sets rather than physical paging. Can be written in SQL directly with physical paging parameters to complete physical paging, or use the page to complete the physical page paging plugin basic principle is to use the MyBatis provides the plug-in interface, implement a custom plug-in, within the intercept method of plug-in intercept to execute SQL, then rewrite the SQL, according to the dialect, Add the corresponding physical page statement and physical page parameters. How does Mybati encapsulate the SQL executor as an object and return it? Which forms of mapping use tags to define the mapping between database column names and object attribute names one by one. MyBatis uses reflection to create objects, and at the same time uses reflection to assign values to the attributes of the object one by one, and returns those attributes that cannot find the mapping relationship. Can’t complete assignment How to batch Insert How to obtain automatically generated primary key using JDBC built-in method post-insert query Obtain pre-insert query Obtain primary key How to pass multiple parameters in Mapper Dao layer function use @param annotation Multiple parameters package map MyBatis dynamic SQL MyBatis dynamic SQL can be written in the form of tags in Xml mapping files, MyBatis provides nine kinds of SQL tags trim WHERE set foreach if choose when otherwise bind XML file tag SELECT Insert UPDATE delete resultMap parameterMap SQL include selectKey MyBatis Xml mapping file If namespace is configured, the ID can be repeated. If namespace is not configured, the ID cannot be repeated. MyBatis implements one to one joint query. Configure the nested query of collection node to check one table first, and then query data in another table according to the found ID. Also configure the collection, but the query of the other table uses the select node to configure whether MyBatis supports lazy loading. And how to implement Mybatis to only support lazy loading of association association objects and Collection association collection objects. This can be done by configuring lazyLoadingEnabled. When the target method is called, the interceptor method is entered, for example a.geb ().getName(). The interceptor invoke() method finds that A.geb () is null. A. setb (); a.getName (); a.getname (); a.getb (); a.getname (); This is the basic principle of lazy loading. MyBatis cache level 1 cache: A HashMap local Cache based on PerpetualCache is stored at Session scope. When a Session is flushed or closed, all caches in that Session are cleared, enabling level 1 caching by default. Level 2 caches have the same mechanism as Level 1 caches, with PerpetualCache and HashMap storage by default, but with Mapper(Namespace) storage scope and customizable storage source, such as Ehcache. Level 2 caching is not enabled by default. To enable level 2 caching, use the Level 2 cache attribute class to implement the Serializable interface (which can be used to store the state of objects), which can be configured in its mapping file. Cache update carry on add/delete/change call Clear method set clear attribute MyBatis It is to define the interface arbitrarily in MyBatis and bind the methods in the interface to SQL statements. When using the interface, we can directly call the interface methods to bind through annotations and write SQL statements in XML. It is necessary to specify that the namespace in XML must be the full path name of the interface. The method name of the mapper interface is the same as that of the SQL ID in mapper. XML. The input parameter types of the mapper interface methods are the same as those of the parameterType of each SQL defined in mapper. XML The output parameter type of Mapper interface method is the same as the type of each SQL resultType defined in mapper. XML. Namespace in mapper. XML file is the classpath of Mapper interface. And how to write a plug-in. Only ParameterHandler, ResultSetHandler, StatementHandler, and Executor interfaces can be used as plugins in Mybatis. The interface method interception function is implemented by generating proxy objects for the interface to be intercepted. Each of the four methods of the interface object is invoked, specifically the Invoke () method of InvocationHandler, which, of course, only intercepts those methods that you specify to be intercepted. Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor Precompilation definition SQL precompilation means that the database driver compiles the SQL statement before sending the SQL statement and parameters to the DBMS, so that the DBMS can execute the SQL without reproducing the precompilation function and optimize the execution of the SQL. Most of the precompiled SQL can be run directly, while the precompiled statement objects can be reused. There are three basic Executor executors in MyBatis: SimpleExecutor, ReuseExxecutor, BatchExecutor SimpleExecutor opens a Statement object every time it executes an update or select. Disable ReuseRxecutor immediately after the Statement is used. Run the update or select command to find the Statement object based on the SQL key. To repeat the update with the Statement object BatchExecutor, add all SQL to the batch and wait for the same execution. There are multiple Statement objects. When the attribute name in the entity class is different from the field name in the table, define the alias of the field name in the SQL statement of the query. Use resultMap to map the one-to-one mapping relationship between field names and attribute names of entity classes. The difference between ResultType and resultMap The return type can be resultType or resultMap, where A resultType directly represents the return type, and a resultMap refers to an external resultMap. These two cannot exist at the same time in MyBatis query mapping, in fact, each attribute queried is put in a corresponding Map, the key is the attribute name, the value is the corresponding value. The last If you feel watching a fruitful, the hope can look, by the way, give me some praise, this will be the biggest power, I update thank you for your support Welcome to pay attention to my public number, fox Java burial 】 【 focus on Java and basic computer knowledge, ensure that let you see something, don’t believe you beat me three even a key: thumb up, forward, watching. If you have different opinions or suggestions after reading, welcome to comment together. Thank you for your support and kindness. I’m Tsuka Fox. I love programming as much as you do. Please follow the public account “Java Tomb Fox” for the latest news