Mybatis annotation is simple do not need to write configuration files, suitable for simple data processing, easy to understand, do not dynamically generate SQL can be used. Binding is required, sometimes not as good as configuration files, which are powerful extensions. Select the right way to apply in the right scenario, annotations mainly used in the SQL statement is relatively simple and easy to understand the case of high readability; XML configuration files are simpler and more extensible when generating dynamic SQL

preface

The real power of Mybatis lies in its statement mapping, which is its magic. Because of its exceptional power, the MAPper’s XML file is relatively simple. If you compare it to JDBC code with the same functionality, you’ll immediately see that nearly 95% of the code is saved. Focus on reducing usage costs and allowing users to focus more on SQL code.

Mapping between common annotations and XML

@ CacheNamespace class < cache >

@ CacheNamespaceRef class < cacheRef >

@ Results method < resultMap >

@result < Result > <id>

@ One method < association >

@ the things method < collection >

@select <select>

@Insert <insert>

@Update <update>

@ the Delete method < Delete >

@insertProvider < INSERT > allows the creation of dynamic SQL

@updateProvider <update> allows you to create dynamic SQL

@deleteProvider <delete> allows the creation of dynamic SQL

The @selectProvider <select> allows you to create dynamic SQL

@param parameter N/A If your mapper method requires more than one parameter, this annotation can be applied to the mapper method parameter to give each parameter A name. Otherwise, multiple arguments will be named by their sequential position (excluding any RowBounds arguments) for example. #{param1}, #{param2}, etc. This is tacit recognition. Using @param (” person “), the argument should be named #{person}. Attributes of the @options method mapping statement This annotation provides a broad range of access exchange and configuration Options that are typically present as attributes on mapping statements. Instead of blurring each statement annotation, the Options annotation provides a coherent and clear way to access them

Examples of annotation and XML configuration Examples Several typical and commonly used one-to-one associative query annotation

@Select("select * from authority")
	@Results(id="au",
	value=@Result(column="uid",
				  property="user",
				  one=@One(select="findUserByid",
				  		   fetchType=FetchType.LAZY)))
	List<Authority> findAll();
Copy the code

@select the SQL statement in which the main table to be queried is filled

@Results maps a return result set with id=”au”

Value = @result () indicates the mapping of an attribute

Column is the foreign key name of the counter table

Property Specifies the slave table entity class attribute name of the master table entity class

One stands for one-to-one mapping

FetchType = fetchType.LAZY Indicates LAZY loading, which is invoked only when the structure of the query requires data from the table

Select a query method from a table

Select is another query method from a slave table for associated queries

Uid is the parameter in select

FindUserByid is the method defined in mapper

@Select("select * from user where id = #{id}")
 User findUserByid(int id);
Copy the code

This method can be configured in XML or annotated in this method to configure the way the XML is configured

<resultMap type="com.jt.mybatis.entity.Authority" id="au">
    <association property="user" column="uid" javaType="com.jt.mybatis.entity.User" 					select="findByUserId">
    </association>
</resultMap>

<select id="findAll" resultMap="au">
	 select * from authority
</select>

<select id="findUserByid" resultType="com.jt.mybatis.entity.User">
		select * from user where id= #{id}
</select>
Copy the code

The test method

@Test
	public void testA(){
		AuthorityMapper mapper = session.getMapper(AuthorityMapper.class);
		mapper.findAll().get(0).getUser();
	}
Copy the code

One-to-many associated query

XML configuration mode

    <resultMap type="com.jt.mybatis.entity.User" id="user">
    		<id column="id" property="id" />
    		<collection property="authoritieList" column="id"
    			fetchType="lazy" select="findAuthorityByUid">
    			<id column="id" property="id" />
    		</collection>
    </resultMap>

	<select id="findUserByUserName" resultMap="user">
		select * from user
		where username = #{username}
	</select>
	
	<select id="findAuthorityByUid" resultType="com.jt.mybatis.entity.Authority">
		select * from
		authority where uid = #{uid}
	</select>
Copy the code

Annotation way

	@Select("select * from user where username = #{username}")
	@Results(id="user",
	value=@Result(column="id",
	property="authoritieList",
	many=@Many(fetchType=FetchType.LAZY,
	select="findAuthorityByUid")))
	User findUserByUserName(String username);
	
	@Select("select * from authority where uid = #{uid}")
	List<Authority> findAuthorityByUid(int uid);
Copy the code

Many represents a one-to-many mapping test method

@Test
	public void testB(){
		AuthorityMapper mapper = session.getMapper(AuthorityMapper.class);
		mapper.findUserByUserName("admin").getAuthoritieList();
	}
Copy the code

Dynamic SQL annotation

@SelectProvider(type=AuthorityProvider.class,method="returnSelectSQL") List<Authority> findByIdAndUid(Authority authority); class AuthorityProvider{ public String returnSelectSQL(Authority authority){ SQL sql = new SQL(){{ SELECT("*"); FROM("authority"); if(authority.getId() ! = 0){ WHERE("id = " + authority.getId()); } if(authority.getUid() ! = 0){ WHERE("uid = " + authority.getUid()); }}}; return sql.toString(); }} // Use XXXProvider annotations to dynamically generate SQL statements, //type= authorityProvider. class specifies the specific class for generating dynamic statements. //method="returnSelectSQL" specifies the method for generating dynamic statementsCopy the code

The test method

       @Test
	public void testC(){
		AuthorityMapper mapper = session.getMapper(AuthorityMapper.class);
		Authority authority = new Authority();
		mapper.findByIdAndUid(authority);
		//执行此语句返回的sql语句为DEBUG [main] - ==>  Preparing: SELECT * FROM authority
		authority.setId(1);
		mapper.findByIdAndUid(authority);
		//执行此语句返回的sql语句为DEBUG [main] - ==>  Preparing: SELECT * FROM authority WHERE (id = 1)
		authority.setUid(2);
		mapper.findByIdAndUid(authority);
		//执行此语句返回的sql语句为DEBUG [main] - ==>  Preparing: SELECT * FROM authority WHERE (id = 1 AND uid = 2) 
	}
Copy the code

What is the difference between a resultType and a resultMap?

  • ResultType directly represents the return type, including basic and complex data types.
  • A reference externally defined by a resultMap indicates the mapping result based on the corresponding external ID. It is generally used when the field name and attribute name are inconsistent, or complex joint query is required to freely control the mapping result.

advice

Simple SQL processing can use annotations, while complex SQL uses XML. But the actual work depends on whether or not you are working on a project that normalizes this.

There are only three types in the project:

1. All must be in XML mode.

2. All must be annotated.

3. You can use BOTH XML and annotations.

The advantages and disadvantages

  • XML mode: added XML files, difficult to modify, uncertain conditions (ifelse judgment), easy to error, special escape characters such as greater than or less than.
  • Note: complex SQL is not easy to use, SQL collection is not convenient, management is not convenient, modify need to compile again
This article is part of the “Gold Nuggets For Free!” Activity, click to viewEvent details