Java study notes-Day76 MyBatis framework (three)



One, type alias


Type aliases can set an abbreviated name for a Java type. It is only used for XML configuration and is intended to reduce redundant writing of fully qualified class names. To be <typeAliases>placed in the mybatis configuration file <configuration>. After configuration, Goods can be used instead of any place where com.etc.entity.Goods is used.

  <typeAliases>
  	<typeAlias type="com.etc.entity.Goods" alias="Goods"/>
  	<typeAlias type="com.etc.entity.GoodsType" alias="GoodsType"/>
  </typeAliases>

Second, the difference between # and $ in MyBatis

element # $
Type match #: Will be pre-compiled, and type matching $: No data type matching
Replace or splice #: Used for variable substitution $: Essentially string splicing
Scenes The transmission of variables must be used #, and using #{}it is equivalent to using the placeholder form of PrepareStatement, which improves efficiency. Can prevent sql injection and other problems. #The method is generally used to pass in the added, modified value or query, delete the where condition id value $It's just a simple string splicing. Be especially careful about SQL injection. It can only be used for non-variable parts $. $The method is generally used to pass in database objects, such as group by fields, order by fields, table names, field names, etc. If you cannot use placeholders, you need to use ${}

Three, MyBatis cache


MyBatis has built-in a powerful transactional query cache mechanism, which can be easily configured and customized. By default, only the local session cache is enabled, which only caches the data in one session. To enable the global second-level cache, you only need to add a line to your SQL mapping file <cache>.

1. Level 1 cache


The first level cache (local cache) is a session-level cache, which is enabled by default. If a session performs a query operation, it will put the result of the query operation in the first-level cache. If the same query operation is performed by the session within a short period of time, it will be directly retrieved from the first-level cache instead of Go to the database to get the data. It must be an operation within the scope of the same session to obtain the data in the first-level cache.

The following are two cases of the first level cache:

  • Case 1: The same session, the same Mapper.
  • Case 2: The same session, different Mappers.
package com.etc.test;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.etc.dao.GoodsMapper;
import com.etc.entity.Goods;

public class TestGoodsSelectCache {
    
    
	public static void main(String[] args) throws IOException {
    
    
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sqlSessionFactory.openSession();
		GoodsMapper mapper = session.getMapper(GoodsMapper.class);
		Goods goods = mapper.selectGoodsById(1);
		// 一级缓存
		System.out.println("*********一级缓存(同一个session,同一个mapper)***********");
		Goods goods1 = mapper.selectGoodsById(1);
		System.out.println(goods);
		System.out.println(goods1);
		System.out.println("*********一级缓存(同一个session,不同mapper)***********");
		// 一级缓存
		GoodsMapper mapper2 = session.getMapper(GoodsMapper.class);
		Goods goods2 = mapper2.selectGoodsById(1);
		System.out.println(goods2);
	}
}

Insert picture description here

2. Level 2 cache


Only operations within the scope of different sessions can obtain the data in the second-level cache. The secondary cache is not enabled by default.
  

Steps to enable secondary cache:

(1) adding a line in the mapping file <cache/>to enable global L2 cache.

<cache/>The effect of the statement is as follows:

  • The results of all select statements in the mapping statement file will be cached.
  • All insert, update, and delete statements in the mapped statement file will refresh the cache.
  • The cache will use the least recently used algorithm (LRU, Least Recently Used) algorithm to clear unnecessary cache.
  • The cache is not refreshed regularly (that is, there is no refresh interval).
  • The cache will hold 1024 references to lists or objects (regardless of which query method returns).
  • The cache is considered a read/write cache, which means that the acquired object is not shared and can be safely modified by the caller without interfering with potential modifications made by other callers or threads.
<?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.etc.dao.GoodsMapper">
	<resultMap id="GoodsResultMap" type="Goods">
		<id column="goodsid" property="goodsid" />
		<result column="goodsname" property="goodsname" />
		<result column="goodsprice" property="goodsprice" />
		<result column="goodsinfo" property="goodsinfo" />
		<result column="goodscount" property="goodscount" />
		<result column="cover" property="cover" />
		<result column="typeid" property="typeid" />
		<result column="shopid" property="shopid" />
		<result column="goodsstate" property="goodsstate" />
		<!-- 关联一个GoodsType对象 -->
		<association property="goodstype" column="typeid" javaType="GoodsType">
			<id column="typeid" property="typeid" />
			<result column="typename" property="typename" />
			<result column="typeinfo" property="typeinfo" />
		</association>
	</resultMap>
	<select id="selectGoodsById" resultMap="GoodsResultMap">
		select * from tbl_goods
		inner join tbl_goodstype on tbl_goods.typeid=tbl_goodstype.typeid
		where tbl_goods.goodsid=#{
    
    goodsid}
	</select>
	<cache></cache>
</mapper>

(2) The entity class implements the serialization interface.

package com.etc.entity;
import java.io.Serializable;

public class Goods implements Serializable {
    
    
    private int goodsid;
    private String goodsname;
    private Double goodsprice;
    private String goodsinfo;
    private int goodscount;
    private String cover;
    private int typeid;
    private int shopid;
    private int goodsstate;
    private GoodsType goodstype;   
    public Goods(int goodsid, String goodsname, Double goodsprice, String goodsinfo, int goodscount,
			String cover, int typeid, int shopid, int goodsstate, Goods goods) {
    
    
		super();
		this.goodsid = goodsid;
		this.goodsname = goodsname;
		this.goodsprice = goodsprice;
		this.goodsinfo = goodsinfo;
		this.goodscount = goodscount;
		this.cover = cover;
		this.typeid = typeid;
		this.shopid = shopid;
		this.goodsstate = goodsstate;
	}
	public Goods() {
    
    
		super();
	}
	public GoodsType getGoodstype() {
    
    
		return goodstype;
	}
	public void setGoodstype(GoodsType goodstype) {
    
    
		this.goodstype = goodstype;
	}
	public int getGoodsid() {
    
    
        return goodsid;
    }
    public void setGoodsid(int goodsid) {
    
    
        this.goodsid = goodsid;
    }
    public String getGoodsname() {
    
    
        return goodsname;
    }
    public void setGoodsname(String goodsname) {
    
    
        this.goodsname = goodsname == null ? null : goodsname.trim();
    }
    public Double getGoodsprice() {
    
    
        return goodsprice;
    }
    public void setGoodsprice(Double goodsprice) {
    
    
        this.goodsprice = goodsprice;
    }
    public String getGoodsinfo() {
    
    
        return goodsinfo;
    }
    public void setGoodsinfo(String goodsinfo) {
    
    
        this.goodsinfo = goodsinfo == null ? null : goodsinfo.trim();
    }
    public int getGoodscount() {
    
    
        return goodscount;
    }
    public void setGoodscount(int goodscount) {
    
    
        this.goodscount = goodscount;
    }
    public String getCover() {
    
    
        return cover;
    }
    public void setCover(String cover) {
    
    
        this.cover = cover == null ? null : cover.trim();
    }
    public int getTypeid() {
    
    
        return typeid;
    }
    public void setTypeid(int typeid) {
    
    
        this.typeid = typeid;
    }
    public int getShopid() {
    
    
        return shopid;
    }
    public void setShopid(int shopid) {
    
    
        this.shopid = shopid;
    }
    public int getGoodsstate() {
    
    
        return goodsstate;
    }
    public void setGoodsstate(int goodsstate) {
    
    
        this.goodsstate = goodsstate;
    }
	@Override
	public String toString() {
    
    
		return "Goods [goodsid=" + goodsid + ", goodsname=" + goodsname + ", goodsprice=" + goodsprice + ", goodsinfo="
				+ goodsinfo + ", goodscount=" + goodscount + ", cover=" + cover + ", typeid=" + typeid + ", shopid="
				+ shopid + ", goodsstate=" + goodsstate + ", goodstype=" + goodstype + "]";
	}
}

(3) use session.commit();submitted to a session.

package com.etc.test;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.etc.dao.GoodsMapper;
import com.etc.entity.Goods;

public class TestGoodsSelectCache {
    
    
	public static void main(String[] args) throws IOException {
    
    
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sqlSessionFactory.openSession();
		GoodsMapper mapper = session.getMapper(GoodsMapper.class);
		Goods goods = mapper.selectGoodsById(1);
		System.out.println(goods);
		session.commit();//让二级缓存生效
		// 二级缓存
		System.out.println("*********二级缓存(不同的session)***********");
		SqlSession session2 = sqlSessionFactory.openSession();
		GoodsMapper mapper2 = session2.getMapper(GoodsMapper.class);
		Goods goods2 = mapper.selectGoodsById(1);
		System.out.println(goods2);
	}
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42141141/article/details/114379589