Mybatis Learn Notes

#Mybatis
###First example
#####Step 1: Add Mybatis 3.4.5 coordinates, mysql, junit, logj to the pom.xml file
Step 2: Write the User entity class.
Step 3: Write the SqlMapConfig.xml configuration file (in resources)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- To configure mybatis Environment -->
<environments default="mysql">
<!-- To configure mysql Environment -->
<environment id="mysql">
<!-- Configure the type of transaction -->
<transactionManager type="JDBC"></transactionManager>
<!-- Configure information to connect to the database: Use data sources(Connection Pool) -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/review"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- inform mybatis Mapping Configuration Location -->
<mappers>
<mapper resource="com/itheima/dao/IUserDao.xml"/>
</mappers>
</configuration>

Step 4: Write the persistence layer interface IuserDao
Step 5: Write a mapping file for the persistent layer interface IUserDao.xml

  • Create location: Must be in the same package as the persistence layer interface.
  • Name: The file name must be named after the persistence layer interface name with an extension of.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zichuan.dao.IUserDao">
<!-- Configure Query All Operations -->
<select id="findAll" resultType="com.zichuan.domain.User">
select * from user
</select>
</mapper>

Step 6: Write a test class

//1. Read the configuration file
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2. Create a builder object for SqlSessionFactory
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//3. Use builder to create factory object SqlSessionFactory
SqlSessionFactory factory = builder.build(in);
//4. Use SqlSessionFactory to produce SqlSession objects
SqlSession session = factory.openSession();
//5. Use SqlSession to create proxy objects for dao interfaces
IUserDao userDao = session.getMapper(IUserDao.class);
//6. Query all methods using proxy objects
List<User> users = userDao.findAll();
for(User user : users) {
System.out.println(user);
}
//7. Release Resources
session.close();
in.close();

annotation

  1. Add annotations to persistence layer interfaces
@Select("select * from user")
List<User> findAll();
  1. Modify SqlMapConfig.xml (Note: Remove mapping configuration for XML (IUserDao.xml)).
<!-- inform mybatis Mapping Configuration Location -->
<mappers>
<mapper class="com.zichuan.dao.IUserDao"/>
</mappers>

Detailed description of ## other queries
Query by id

<select id="findById" resultType="com.zichuan.domain.User" parameterType="int">
select * from user where id = #{uid}
</select>

resultType property: Used to specify the type of result set.
parameterType property: Used to specify the type of incoming parameter.
The #{} character is used in sql statements: it represents a placeholder, which is equivalent to what you learned in the original jdbc section?Are used to replace actual data when executing a statement.The specific data is determined by the contents in #{}.
Writing of content in #{}: Since the data type is the basic type, you can write it here as you like.

#######Test Class Framework

private InputStream in ;
private SqlSessionFactory factory;
private SqlSession session;
private IUserDao userDao;
@Before//Execute before test method execution
public void init()throws Exception {
//1. Read the configuration file
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2. Create Builder Object
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//3. Create SqlSession Factory Object
factory = builder.build(in);
//4. Create SqlSession object
session = factory.openSession();
//5. Create Dao's proxy object
userDao = session.getMapper(IUserDao.class);
}
@After//Execute after test method execution is complete
public void destroy() throws Exception{
session.commit();
//7. Release Resources
session.close();
in.close();
}
@Test
public void testFindOne() {
//6. Perform operations
User user = userDao.findById(41);
System.out.println(user);
}

Save User

<!-- Save User-->
<insert id="saveUser" parameterType="com.zichuan.domain.User">
insert into user(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#{address})
</insert>
#{user.username} It first looks for the user object, then finds the username attribute in the user object, and calls the getUsername() method to get the value out.However, we specify the entity class name on the parameterType property, so we can omit user. and write username directly.

When adding or deleting changes, you must control the submission of transactions. You can use session.commit();Implement transaction commit

Return value of new user id

<insert id="saveUser" parameterType="USER"> 
<!-- Get Inserted at Configuration Save id --> 
<selectKey keyColumn="id" keyProperty="id" resultType="int"> 
select last_insert_id(); 
</selectKey> 
insert into user(username,birthday,sex,address) 
values(#{username},#{birthday},#{sex},#{address}) 
</insert>

Update Method

<!-- Update User --> 
<update id="updateUser" parameterType="com.itheima.domain.User"> 
update user set username=#{username},birthday=#{birthday},sex=#{sex}, 
address=#{address} where id=#{id} 
</update>

Delete Method

<!-- delete user --> 
<delete id="deleteUser" parameterType="java.lang.Integer"> 
delete from user where id = #{uid} 
</delete>

Fuzzy Query

<!-- Fuzzy Query by Name --> 
<select id="findByName" resultType="com.itheima.domain.User" parameterType="String"> 
select * from user where username like #{username} 
</select>
List<User> users = userDao.findByName("%king%");

We didn't include% in the configuration file as a condition for the fuzzy query, so the identity of the fuzzy query needs to be given when a string argument is passed in.The #{username} in the configuration file is also just a placeholder, so the SQL statement appears as'?'

select * from user where username like '%${value}%'

We changed the original #{} placeholder above to v a l u e . notes meaning as fruit use Model paste check Inquiry Of this species write method , that Are you? {value}.Note that if you use this notation for fuzzy queries, then Value.Note that if you use this notation for fuzzy queries, the {value} notation is fixed and cannot be written under any other name.

List<User> users = userDao.findByName("king");

Differences between #{} and ${}

PreparedStatements can be set to placeholders through #{}, java type and jdbc type conversion can be done automatically, #{} can effectively prevent sql injection. #{}You can accept simple type values or pojo attribute values.If a parameterType transfers a single simple type value, the #{} brackets may be a value or other name.
surface show Pinyin meet s q l strand through too {} means splicing sql strings through Represents that spliced sql strings can be spliced into sql without jdbc type conversion by {} can with meet collect simple single class type value or p o j o genus nature value , as fruit p a r a m e t e r T y p e pass transport single individual simple single class type value , {} Simple type values or pojo attribute values can be received if a parameterType transfers a single simple type value, Simple type values or pojo attribute values can be received, and if a parameterType transfers a single simple type value, {} brackets can only contain value

Query uses aggregate functions

<!-- Total number of records queried --> 
<select id="findTotal" resultType="int"> 
select count(*) from user;
</select>

#####resultType Configuration Result Type

  • Entity class properties and column names of database tables are no longer consistent
  • Use Alias Query
<select id="findAll" resultType="com.itheima.domain.User"> 
select id as userId,username as userName,birthday as userBirthday, 
sex as userSex,address as userAddress from user 
</select>

#####resultMap result type
The resultMap tag establishes a correspondence when the column name of the query is inconsistent with the attribute name of the entity class.This enables encapsulation.

<resultMap type="com.itheima.domain.User" id="userMap">
<id column="id" property="userId"/>
<result column="username" property="userName"/>
<result column="sex" property="userSex"/>
<result column="address" property="userAddress"/>
<result column="birthday" property="userBirthday"/>
</resultMap>
  • id tag: used to specify the primary key field
  • result tag: used to specify non-primary key fields
  • Column property: used to specify the database column name
  • Property property: Used to specify the entity class property name
<select id="findAll" resultMap="userMap">
select * from user 
</select>

Content and order of configuration in ###SqlMapConfig.xml

-properties
–property
-settings (global configuration parameters)
–setting
-typeAliases (type alias)
–typeAliase
–package
-typeHandlers (type processor)
-objectFactory (Object Factory)
-plugins
-environments (Environment Collection Property Object)
- environment (environment sub-attribute object)
- transactionManager (Transaction Management)
- dataSource (data source)
-mappers (mappers)
–mapper
–package

#####properties (properties)

  • First way:
<properties> 
<property name="jdbc.driver" value="com.mysql.jdbc.Driver"/> 
<property name="jdbc.url" value="jdbc:mysql://localhost:3306/review"/>
<property name="jdbc.username" value="root"/> 
<property name="jdbc.password" value="root"/> 
</properties>
  • Second way:
    Define db.properties file under classpath
jdbc.driver=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://localhost:3306/review
jdbc.username=root 
jdbc.password=root

Properrties Label Configuration

<properties url= file:///D:/IdeaProjects/day02_eesy_01mybatisCRUD/src/main/resources/jdbcConfig.properties"> 
</properties>

Our dataSource tag now refers to the configuration above

<dataSource type="POOLED"> 
<property name="driver" value="${jdbc.driver}"/> 
<property name="url" value="${jdbc.url}"/> 
<property name="username" value="${jdbc.username}"/> 
<property name="password" value="${jdbc.password}"/> 
</dataSource>

#####mappers (mappers)
Use resources relative to the class path, such as:

<mapper resource="com/zichuan/dao/IUserDao.xml" />

Note: This method requires the mapper interface name to be the same as the mapper mapping file name and to use the mapper interface class path in the same directory, such as:

<mapper class="com.zichuan.dao.UserDao"/> 

Register all mapper interfaces under the specified package, such as:

<package name="cn.zichaun.mybatis.mapper"/> 

Note: This method requires the mapper interface name to be the same as the mapper mapping file name and placed in the same directory.

Connection Pool Technology for ###Mybatis

Configure the connection pool in Mybatis by implementing it in the SqlMapConfig.xml configuration file of Mybatis.

When MyBatis initializes, it creates a corresponding type of data source DataSource based on the type property, that is:
type="POOLED": MyBatis creates a PooledDataSource instance
type="UNPOOLED": MyBatis creates an UnpooledDataSource instance
type="JNDI": MyBatis will look up the DataSource instance from the JNDI service and return to using

Transaction Control for ###Mybatis

Because the Mybatis framework encapsulates JDBC, the transaction control mode of the Mybatis framework itself uses the JDBC setAutoCommit() method to set the transaction commit mode.
Connections taken out of the connection pool call the connection.setAutoCommit(false) method, so we must use the sqlSession.commit() method, which is equivalent to using the connection.commit() method in JDBC to commit transactions.

Dynamic SQL Statement for ###Mybatis
Label for ####Dynamic SQL

<select id="findByUser" resultType="user" parameterType="user"> 
select * from user where 1=1 
<if test="username!=null and username != '' "> 
and username like #{username} 
</if> 
<if test="address != null"> 
and address like #{address} 
</if> 
</select>

Test

User u = new User(); 
u.setUsername("%king%"); 
u.setAddress("%Shunyi%"); 
//6. Perform operations 
List<User> users = userDao.findByUser(u);

Label for ####Dynamic SQL
To simplify the conditional assembly of where 1=1 above, tags can be used to simplify development.

<select id="findByUser" resultType="user" parameterType="user"> 
<include refid="defaultSql"></include> 
<where> 
<if test="username!=null and username != '' "> 
and username like #{username} 
</if> 
<if test="address != null"> 
and address like #{address} 
</if> 
</where> 
</select>


Label for ####Dynamic Labels

<!-- Query all users in id In a collection of --> 
<select id="findInIds" resultType="user" parameterType="queryvo"> 
<!-- select * from user where id in (1,2,3,4,5); --> 
<include refid="defaultSql"></include> 
	<where> 
		<if test="ids != null and ids.size() > 0"> 
		<foreach collection="ids" open="id in ( " close=")" item="uid" separator=","> 
		#{uid} 
		</foreach> 
		</if> 
	</where> 
</select> 

SQL statement:
select field from user where id in (?)
Tags are used to traverse a collection, and its properties:
Collection: represents the collection elements to traverse, be careful not to write #{}
open: Represents the beginning of a statement
close:Represents the end
item: Represents each element of a traversed collection, resulting variable name
sperator: for separator

Simplified SQL fragments in #####Mybatis

Sql can extract duplicate SQL and use include reference to achieve SQL reuse.

<!-- Extracting duplicate statement code snippets --> 
<sql id="defaultSql"> 
select * from user 
</sql>

<!-- according to id query --> 
<select id="findById" resultType="UsEr" parameterType="int">
<include refid="defaultSql"></include> 
where id = #{uid} 
</select>

One-to-many of ##Mybatis multi-table queries
A User can have multiple accounts

  • Mode 1
select a.*,u.username,u.address from account a,user u where a.uid =u.id;

Returns information for both tables so accountuser contains all accounts and inherits User

return super.toString() + " AccountUser [username=" + username + ", address=" + address + "]";
<select id="findAll" resultType="accountuser"> 
select a.*,u.username,u.address from account a,user u where a.uid =u.id; 
</select>
  • Mode 2
    Using resultMap, define a dedicated resultMap to map one-to-one query results.
    From the object-oriented (has a) relationship, we know that we can add an object of the User class to the Account class to represent who the account is.
private User user; 
public User getUser() { 
return user; 
} 
public void setUser(User user) { 
this.user = user; 
}
<!-- Establish correspondence --> 
<resultMap type="account" id="accountMap"> 
<id column="aid" property="id"/> 
<result column="uid" property="uid"/> 
<result column="money" property="money"/> 
<!-- It is used to specify a reference entity property from a table --> 
<association property="user" javaType="user"> 
<id column="id" property="id"/> 
<result column="username" property="username"/> 
<result column="sex" property="sex"/> 
<result column="birthday" property="birthday"/> 
<result column="address" property="address"/> 
</association> 
</resultMap>
<select id="findAll" resultMap="accountMap"> 
select u.*,a.id as aid,a.uid,a.money from account a,user u where a.uid =u.id; 
</select>
  • Requirements:
    Query all user information and user-associated account information.
  • Analysis:
    The user information and his account information are one-to-many relationships, and if the user does not have account information during the query process, we also want to query the user information at this time. We think the left outer join query is more appropriate.
    User class joins List
<resultMap type="user" id="userMap"> 
<id column="id" property="id"></id> 
<result column="username" property="username"/> 
<result column="address" property="address"/> 
<result column="sex" property="sex"/> 
<result column="birthday" property="birthday"/> 
<!-- collection Is the corresponding relationship used to establish set attributes in one-to-many 
ofType Data type used to specify collection elements 
--> 
<collection property="accounts" ofType="account"> 
<id column="aid" property="id"/> 
<result column="uid" property="uid"/> 
<result column="money" property="money"/>
</collection> 
</resultMap> 
<!-- Configure Query All Operations --> 
<select id="findAll" resultMap="userMap"> 
select u.*,a.id as aid ,a.uid,a.money from user u left [outer] join account a on u.id =a.uid 
</select>

collection
The section defines the account information associated with the user.Represents the result set of an associated query
property="accList":
Which property of the result set of the associated query is stored on the User object.
ofType="account":
Specifies the object type in the result set of the associated query, that is, the object type in the List.You can use an alias or a fully qualified name here.

Many-to-many of ##Mybatis multi-table queries
Many-to-many relationship model between users and roles

SELECT 
r.*,u.id uid, 
u.username username, 
u.birthday birthday, 
u.sex sex, 
u.address address 
FROM 
ROLE r 
INNER JOIN 
USER_ROLE ur 
ON ( r.id = ur.rid) 
INNER JOIN 
USER u 
ON (ur.uid = u.id);
<!--Definition role Table ResultMap--> 
<resultMap id="roleMap" type="role"> 
<id property="roleId" column="rid"></id> 
<result property="roleName" column="role_name"></result> 
<result property="roleDesc" column="role_desc"></result> 
<collection property="users" ofType="user"> 
<id column="id" property="id"></id> 
<result column="username" property="username"></result> 
<result column="address" property="address"></result> 
<result column="sex" property="sex"></result> 
<result column="birthday" property="birthday"></result> 
</collection> 
</resultMap>
<!--Query all--> 
<select id="findAll" resultMap="roleMap"> 
select u.*,r.id as rid,r.role_name,r.role_desc from role r
left outer join user_role ur on r.id = ur.rid 
left outer join user u on u.id = ur.uid 
</select> 
</mapper>

###Mybatis Delayed Loading Policy

Delayed loading:
Loading is done when data is needed and not when data is not needed.Delayed loading is also known as lazy loading.
Benefits: Querying from a single table before associating queries from related tables when needed greatly improves database performance, since querying from a single table is faster than querying multiple tables from an association.
Disadvantages:
Because database queries only occur when data is needed, this can cause users to wait longer and experience less when querying large amounts of data because queries also take time.

When mybatis implemented the multitable operation on the third day, we used resultMap to implement one-to-one, one-to-many, and many-to-many relationships.One-to-one and one-to-many mappings are implemented mainly through association and collection.Association, collection have deferred load function.

 <mapper namespace="com.zichuan.dao.IAccountDao"> 
<!-- Establish correspondence --> 
<resultMap type="account" id="accountMap"> 
<id column="aid" property="id"/> 
<result column="uid" property="uid"/> 
<result column="money" property="money"/> 
<!-- It is used to specify a reference entity property from a table --> 
<association property="user" javaType="user" 
select="com.zichuan.dao.IUserDao.findById" 
column="uid"> 
</association> 
</resultMap> 
<select id="findAll" resultMap="accountMap"> 
select * from account 
</select> 

<!-- according to id query --> 
<select id="findById" resultType="user" parameterType="int" > 
select * from user where id = #{uid} 
</select>
</mapper> 
  • Select: Fill in the id of the select map we want to call
  • column: Fill in the parameters we want to pass to the select Map

We need to add the delayed loading configuration to the Mybatis configuration file SqlMapConfig.xml.

<!-- Turn on support for delayed loading -->
<settings> 
<setting name="lazyLoadingEnabled" value="true"/> 
<setting name="aggressiveLazyLoading" value="false"/> 
</settings>

Delayed Loading Using Collection
Nodes also have a select attribute, a column attribute.
Add List attribute to User entity class

<resultMap type="user" id="userMap">
<id column="id" property="id"></id>
<result column="username" property="username"/>
<result column="address" property="address"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday"/>
<!-- collection Is the corresponding relationship used to establish set attributes in one-to-many
ofType Data type used to specify collection elements
select Is the unique identification used to specify the query account (for the account) dao Fully qualified class name plus method name)
column Is used to specify which field's value to use as a conditional query
-->
<collection property="accounts" ofType="account"
select="com.itheima.dao.IAccountDao.findByUid"
column="id">
</collection>
</resultMap>
<!-- Configure Query All Operations -->
<select id="findAll" resultMap="userMap">
select * from user
</select>
<!-- According to user id Query account information -->
<select id="findByUid" resultType="account" parameterType="int">
select * from account where uid = #{uid}
</select>
  • Label:
    Used primarily to load associated collection objects
  • select property:
    The sql statement used to specify the query account list, so the id of the sql mapping is filled in
  • Columumn property:
    The parameter source of the sql statement used to specify the select property. The above parameter comes from the user's id column, so it is written as the field name id

###Mybatis Cache
Level 1 Cache
The first level cache is a SqlSession level cache and exists as long as the SqlSession has no flush or close
A first-level cache is a SqlSession-wide cache, which is emptied when SqlSession modifications, adds, deletes, commit(), close() and other methods are called.

Level 2 Cache
Secondary caches are mapper mapping level caches. Multiple SqlSessions operate on the same Mapper mapping sql statement. Multiple SqlSessions can share the second level caches. Secondary caches are across SqlSessions.
sqlSession1 queries user information, which stores the query data in a secondary cache.

  • First turn on the secondary cache for mybatis.
    Step 1: Open the secondary cache in the SqlMapConfig.xml file
<settings> 
<!-- Turn on support for secondary caching --> 
<setting name="cacheEnabled" value="true"/> 
</settings> 

This step can be omitted because cacheEnabled defaults to true.Open secondary cache for true representative;Not enabling secondary caching for false means.
Step 2: Configure the associated Mapper mapping file

<cache>The label indicates the current one mapper Mapping will use a secondary cache, depending on the criteria mapper Of namespace Value.
<mapper namespace="com.itheima.dao.IUserDao"> 
<!-- Turn on support for secondary caching --> 
<cache></cache> 
</mapper>

Step 3: Configure the useCache property on the statement

<!-- according to id query --> 
<select id="findById" resultType="user" parameterType="int" useCache="true"> 
select * from user where id = #{uid} 
</select> 

Setting useCache="true" in the label in the UserDao.xml mapping file means that the current statement will use a secondary cache, which can be set to false if not.
Note: For each query that requires the latest data sql, set useCache=false to disable secondary caching.

SqlSession sqlSession1 = factory.openSession();
sqlSession1.close();//Level 1 cache disappeared
SqlSession sqlSession2 = factory.openSession();

Secondary Cache from Factory
###Mybatis Annotation Development

@Insert:Add New
@Update:Implement Updates
@Delete:Implement Delete
@Select:Implement Query
@Result:Implement result set encapsulation
@Results:Can be used with @Result to encapsulate multiple result sets
@ResultMap: Encapsulate references to @Results definitions
@One:Implement one-to-one result set encapsulation
@Many:Implement one-to-many result set encapsulation
@SelectProvider: Implement dynamic SQL mapping
@CacheNamespace: Implement the use of annotation secondary caches

If the entity class name does not match the database
In the persistence layer interface

@Select("select * from user") 
@Results(id="userMap", 
value= { 
@Result(id=true,column="id",property="userId"), 
@Result(column="username",property="userName"), 
@Result(column="sex",property="userSex"), 
@Result(column="address",property="userAddress"), 
@Result(column="birthday",property="userBirthday") 
}) 
List<User> findAll();
@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);
@Insert("insert into user(username,sex,birthday,address)values(#{username},#{sex},#{birthday},#{address})")
@SelectKey(keyColumn="id",keyProperty="id",resultType=Integer.class,before = false, statement = { "select last_insert_id()" })
int saveUser(User user);
@Update("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id =#{id} ")
int updateUser(User user);
@Delete("delete from user where id = #{uid} ")
int deleteUser(Integer userId);
@Select("select count(*) from user ")
int findTotal();
@Select("select * from user where username like #{username} ")
List<User> findByName(String name);

By annotating, we no longer need to write a UserDao.xml mapping file.

<!-- Configuration Mapping Information -->
<mappers>
<!-- To configure dao The location of the interface in two ways
 First: Use mapper Label Configuration class attribute
 Second: Use package Label, specify directly dao Package in which the interface is located
-->
<package name="com.itheima.dao"/>
</mappers>

Using annotations for complex relationship mapping development
Before implementing complex relationship mapping, we can configure it in the mapping file. When developing with annotations, we need to use the @Results annotation, @Result annotation, @One annotation, @Many annotation.

  • @Results comment
    Instead of labels
    You can use either a single @Result annotation or a @Result collection in this annotation
    @Results({@Result(), @Result()}) or @Results(@Result())
  • @Resutl comment
    Instead of labels and Tags
  • Property description in @Result:
    Is id a primary key field
    Column name of column database
    Property requires the property name to be assembled
    One needs the @One comment (@Result (one=@One)())
    The @Many comment (@Result (many=@many)()) that Many needs to use
    **@One comment (one-to-one)**
    Instead of labels, they are the key to a multi-table query, which is used in annotations to specify that a subquery returns a single object.
    @One Annotation Properties Introduction:
    select specifies sqlmapper for multitable queries
    fetchType overrides the global configuration parameter lazyLoadingEnabled.
    Use format:
    @Result(column=" ",property="",one=@One(select=""))
    @Many comment (many-to-one)
    Instead of labels, they are the key to multitable queries, which are used in annotations to specify the set of objects returned by subqueries.
    Note: Aggregated elements are used to handle one-to-many relationships.You need to specify the properties of the mapped Java entity class, the javaType of the properties (typically ArrayList), but the annotations may not define them;
    Use format:
    @Result(property="",column="",many=@Many(select=""))

One-to-one complex relationship mapping and delayed loading using annotations
Add a persistence layer interface to the account and configure it with annotations

Query all accounts, and query the user who owns the account by *** delayed loading ***
@return

@Select("select * from account") 
@Results(id="accountMap", 
value= { 
@Result(id=true,column="id",property="id"), 
@Result(column="uid",property="uid"), 
@Result(column="money",property="money"), 
@Result(column="uid", 
property="user", 
one=@One(select="com.itheima.dao.IUserDao.findById", 
fetchType=FetchType.LAZY) 
) 
}) 
List<Account> findAll();

Add the user's persistence layer interface and configure it with annotations

Query all users
@return

@Select("select * from user") 
@Results(id="userMap", 
value= { 
@Result(id=true,column="id",property="userId"), 
@Result(column="username",property="userName"), 
@Result(column="sex",property="userSex"), 
@Result(column="address",property="userAddress"), 
@Result(column="birthday",property="userBirthday") 
}) 
List<User> findAll(); 

**Query a user based on id**

@param userId
@return

@Select("select * from user where id = #{uid} ") 
@ResultMap("userMap") 
User findById(Integer userId);

One-to-many complex relationship mapping using annotations

  • One-to-many relationship mapping: The primary table method should contain a collection reference from the table
    private List accounts;
    Write user's persistence layer interface and configure it with annotations

**Query all users**

@return

@Select("select * from user") 
@Results(id="userMap", 
value= { 
@Result(id=true,column="id",property="userId"), 
@Result(column="username",property="userName"), 
@Result(column="sex",property="userSex"), 
@Result(column="address",property="userAddress"), 
@Result(column="birthday",property="userBirthday"), 
@Result(column="id",property="accounts", 
many=@Many( 
select="com.itheima.dao.IAccountDao.findByUid", 
fetchType=FetchType.LAZY 
) 
) 
}) 
List<User> findAll(); 
} 

**@Many: **
Equivalent Configuration

  • select property: represents the sql statement to be executed
  • fetchType property: Represents how the load is loaded, generally set to the value of LAZY if you want to delay loading
    Write the persistence layer interface for the account and configure it with annotations
@Select("select * from account where uid = #{uid} ") 
List<Account> findByUid(Integer userId);

Annotation-based secondary cache for ####mybatis
Turn on secondary cache support in SqlMapConfig

<!-- Configure Secondary Cache --> 
<settings> 
<!-- Turn on support for secondary caching --> 
<setting name="cacheEnabled" value="true"/> 
</settings>

Configuring secondary caches using annotations in persistent layer interfaces

@CacheNamespace(blocking=true)//mybatis implements configuration of secondary cache based on annotations 
public interface IUserDao {}

Keywords: Java Database MySQL

Added by Errant_Shadow on Sun, 05 Sep 2021 20:53:34 +0300