Fast popularization
1. What is mybatis
mybatis is an excellent persistence layer framework that supports plain SQL queries, stored procedures and advanced mapping.
MyBatis eliminates manual settings of almost all JDBC code and parameters and search encapsulation of the result set. MyBatis can use simple XML or annotations for configuration and original mapping, mapping interfaces and Java's POJOs (Plain Old Java Objects) into records in the database.
Mybatis implements interface binding, making it more convenient to use.
Improved object relationship mapping, more efficient
MyBatis uses powerful OGNL-based expressions to eliminate other elements.
2. Functional architecture
3. Execution process
Detailed explanation of the principle:
The MyBatis application creates a SqlSessionFactory based on the XML configuration file. The configuration comes from two places according to the configuration, one is the configuration file and the other is the annotation of Java code, and obtains a SqlSession. SqlSession contains all the methods required to execute sql. You can directly run the mapped sql statements through the SqlSession instance to complete the data addition, deletion, modification and query, transaction submission, etc., and close SqlSession after use.
Let's take a look at the key points of this article. Mybatis simple annotations
Key annotation words:
@Insert: Insert sql, the syntax is exactly the same as xml insert sql
@Select: Query sql, and the syntax is exactly the same as XML select sql
@Update: Update sql, and the syntax of xml update sql is exactly the same
@Delete: Delete sql, and the syntax is exactly the same as xml delete sql
@Param: Enter the ginseng
@Results: Result collection
@Result : Results
1. Domain model:
public class UserDO {private Long id;private String userName;private Date gmtCreate;private Date gmtModified;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public Date getGmtCreate() {return gmtCreate;}public void setGmtCreate(Date gmtCreate) {this.gmtCreate = gmtCreate;}public Date getGmtModified() {return gmtModified;}public void setGmtModified(Date gmtModified) {this.gmtModified = gmtModified;}}2. Interface definition:
public interface UserDAO {@Insert("INSERT INTO t_user(gmt_create, gmt_modified, user_name) values(now(), now(), #{userName})")public int insert(@Param("userName") String userName); @Select("SELECT * FROM t_user WHERE id = #{id}")public UserDO selectByUserId(@Param("id") Long id) ;@Update("UPDATE t_user SET gmt_modified = now(), user_name = #{userName} WHERE id = #{id}")public int udpateById(@Param("userName") String userName, @Param("id") Long id) ;@Delete("DELETE FROM t_user WHERE id = #{id}")public int udpateById(@Param("id") Long id) ; }3. mybatis xml config:
<!-- mybatis annotation--><bean id="sqlSessionFactory"><property name="dataSource" ref="mysqlBASE" /> <!--Here you only need to configure your own data source--></bean> <bean id="userDAO"><property name="mapperInterface" value="com.yuanmeng.userDAO" /> <!--mybatis interface--> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> <!--sqlSession Factory--> </bean>
In this way, we complete the demo of mybatis using annotations. Doesn’t it feel very simple?
If you are familiar with mybatis xml, in most cases, we need to map the field names of the database tables to class DO. Mybatis annotation also provides mapping functions, and the syntax is similar.
@Select("SELECT * FROM tsp_template WHERE id = #{id}")@Results(value = { @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR) }) public UserDO selectById(@Param("id") Long id);Of course, the above is just that SQL cannot be simple anymore. Think about it if we have this requirement, we update user information and hope to update the specified attribute value. In other words, we generate SQL dynamically like XML. Then we cannot simply and roughly use the @update annotation. Fortunately, the powerful mybatis also provides dynamic SQL assembly.
Dynamic SQL
The corresponding relationship is as follows
@Insert: @InsertProvider
@Select: @SelectProvider
@Update: @UpdateProvider
@Delete: @DeleteProvider
The four provider annotation identifiers use dynamic SQL and use syntax format:
@UpdateProvider(type = UserProvider.class, method = "updateSQL")
How to construct dynamic SQL
public class UserProvider {/*** udpate* @param UserDO userDO* @return*/public String updateSQL(final UserDO userDO) {return new SQL() {{UPDATE("t_user");SET("gmt_modified = now()");if (userDO.getUserName() != null) {SET("user_name = #{userName}");}WHERE("id = #{id}}");}}.toString();}}The knowledge points mentioned in this article are relatively basic. If you need to have an in-depth understanding, please refer to the official website document or read the source code.
Summarize:
1. How to choose xml and annotations? It varies from person to person. Everyone has their own habits of coding. xml and annotations have their own advantages and disadvantages. The disadvantages of xml: When the model attributes are changed, it needs to be changed from DO to DAO to xml. It will be a pain to think about it~ xml also has advantages. SQL fragment reuse is convenient and the syntax is approachable. Unlike annotations, you have to construct a dynamic statement and create a class. Moreover, when a segment of SQL is referenced multiple places, the code appears redundant. At this time, xml must be used to extract and use it together. I complained about mybatis annotation, wouldn’t that annotation be useless? no , mybatis is suitable for scenarios where model attributes are often changed, because it can be combined with reflection and dynamically constructed SQL (purely nonsense, personal ideas, should be realized, and it will be done another day). It can be said that the advantages of mybatis annotation make up for the shortcomings of xml well. The two complement each other ~
The above is a quick start to the Mybatis development annotations introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!