Handwriting mybatis framework-increase cache & transaction function

Cache com.simple.ibatis.cache
cache interface-Cache
copy the code
public interface Cache {

/**放入缓存*/
void putCache(String key,Object val);

/**获取缓存*/
Object getCache(String key);

/**清空缓存*/
void cleanCache();

/**获取缓存健数量*/
int getSize();

/**移除key的缓存*/
void removeCache(String key);

}
Copy code
The custom framework cache interface provides basic addition, deletion, modification, and checking functions.

Cache basic implementation class-SimpleCache
copy code
public class SimpleCache implements Cache{ // Internally uses HashMap as a cache to achieve private static Map<String,Object> map = new HashMap<>(); // Call map.put() method to achieve storage Cache function @Override public void putCache(String key, Object val) { map.put(key,val); } // Call map.get() method to realize the cache function @Override public Object getCache(String key) { return map .get(key); } // call the map.clear() method to realize the function of clearing the cache @Override public void cleanCache() { map.clear(); } // call the map.size() method to get the number of cache @Override public int getSize() { return map.size(); }






















// Call the map.remove() method to remove the cache
@Override
public void removeCache(String key) { map.remove(key); } } copy the code simple-ibatis completes the encapsulation of HasaMap and realizes basic cache acquisition and deletion , Clear and other functions.




With LRU elimination strategy-LruCache
copy code
/**

  • @author xiabing

  • @description: Cache packaging class, with Lru elimination strategy function
    */
    public class LruCache implements Cache{ // Default cache number private static Integer cacheSize = 100; // Load factor private static Float loadFactory = 0.75F; // Real cache private Cache trueCache; // Override the LinkedHashMap method to implement the Lru function private Map<String,Object> linkedCache; // The cache element to be removed private static Map.Entry removeEntry;









    public LruCache(Cache trueCache){
    this(cacheSize,loadFactory,trueCache);
    }

    public LruCache(Integer cacheSize, Float loadFactory, Cache trueCache) { this.cacheSize = cacheSize; this.loadFactory = loadFactory; this.trueCache = trueCache; this.linkedCache = new LinkedHashMap<String, Object>(cacheSize,loadFactory,true){ @Override // When the number of caches is greater than the set default cache number, linkedHashMap will eliminate the least recently used element, get this element, and eliminate it in the real cache. protected boolean removeEldestEntry(Map.Entry eldest) { if(getSize() > cacheSize){ removeEntry = eldest; return true; } return false; } }; }














    @Override
    public void putCache(String key, Object val) { this.trueCache.putCache(key,val); this.linkedCache.put(key,val); if(removeEntry != null){ // If the least recently found Element, remove it removeCache((String)removeEntry.getKey()); removeEntry = null; } }







    @Override
    public Object getCache(String key) { // The meaning of linkedCache acquisition is to trigger the sorting of linkedHashMap elements linkedCache.get(key); return trueCache.getCache(key); }



    @Override
    public void cleanCache() {
    trueCache.cleanCache();
    linkedCache.clear();
    }

    @Override
    public int getSize() {
    return trueCache.getSize();
    }

    @Override
    public void removeCache(String key) { trueCache.removeCache(key); } } Copy code LruCache is implemented according to the characteristics of LinkedHashMap. If you have any questions about this, please refer to mybatis on the implementation of LruCache function-introduction to mybatis cache




Project code test
Copy code
@Test
// Test cache acquisition
public void shouldGetCache() throws SQLException { // Initialize connection pool PoolDataSource poolDataSource = new PoolDataSource("com.mysql.jdbc.Driver","jdbc:mysql://101.132. 150.75:3306/our-auth","root","root"); Config config = new Config("com/simple/ibatis/mapper",poolDataSource); // Set global configuration, open cache config.setOpenCache(true ); // Get Executor simpleExecutor = config.getExecutor(); UserMapper userMapper = simpleExecutor.getMapper(UserMapper.class);







    User user = new User();
    user.setId(1);
    user.setName("root");
   // 第一次调用
    List<User> userList = userMapper.getUsers(user);
    // 第二次调用,我在源码中有打印输出,若使用了缓存,则打印语句
    List<User> userList1 = userMapper.getUsers(user);
    
    simpleExecutor.close();
}

Copy the code and the
result is printed as this is cache. If you are interested, you can try it yourself

I set the cache globally to be configurable, and LruCache is generated by default. And forcibly refresh the cache before updating, modifying, and deleting SQL operations. For detailed code logic, see the SimpleExecutor class in the project.

Transaction function com.simple.ibatis.transaction
transaction interface-Transaction
copy code
/**

  • @Author xiabing
  • @Desc Add transaction function
    **/
    public interface Transaction { /* Get link / Connection getConnection() throws SQLException; /* Submit / void commit() throws SQLException; /* Rollback / void rollback() throws SQLException; /* Close / void close() throws SQLException; } Copy code JDBC transaction-SimpleTransaction copy code package com.simple.ibatis.transaction;












import com.simple.ibatis.datasource.PoolDataSource;

import java.sql.Connection;
import java.sql.SQLException;

/**

  • @Author xiabing

  • @Desc simple implementation of transaction
    **/
    public class SimpleTransaction implements Transaction{

    private Connection connection; // Database connection
    private PoolDataSource dataSource; // Data source
    private Integer level = Connection.TRANSACTION_REPEATABLE_READ;; // Transaction isolation level
    private Boolean autoCommmit = true; // Whether to submit automatically

    public SimpleTransaction(PoolDataSource dataSource){
    this(dataSource,null,null);
    }

    public SimpleTransaction(PoolDataSource dataSource, Integer level, Boolean autoCommmit) {
    this.dataSource = dataSource;
    if(level != null){
    this.level = level;
    }
    if(autoCommmit != null){
    this.autoCommmit = autoCommmit;
    }
    }

    @Override
    public Connection getConnection() throws SQLException{
    this.connection = dataSource.getConnection();

     this.connection.setAutoCommit(autoCommmit);
    
     this.connection.setTransactionIsolation(level);
    
     return this.connection;
    

    }

    @Override
    public void commit() throws SQLException{
    if(this.connection != null){
    this.connection.commit();
    }
    }

    @Override
    public void rollback() throws SQLException{
    if(this.connection != null){
    this.connection.rollback();
    }
    }

    /* Before closing the link, if the automatic submission is set to false, you must perform a rollback operation /
    @Override
    public void close() throws SQLException{ if(!autoCommmit && connection != null){ connection.rollback(); } / * put back into pool / IF (connection = null!) { dataSource.removeConnection (connection); } / * link is set to null / this.connection = null; } } copy the code simpleTransaction major transaction management capabilities to the database itself (Ie connection), the transaction isolation level is the transaction isolation level of mysql by default. Through the management of Connection, transaction control of a series of operations on connection is realized.












Copy the code
Test
public void shouldOpenTransaction() { /* Basic configuration / PoolDataSource poolDataSource = new PoolDataSource("com.mysql.jdbc.Driver","jdbc:mysql://101.132.150.75:3306/our-auth","root ","Root"); Config config = new Config("com/simple/ibatis/mapper",poolDataSource); /* Set to enable transaction and close auto commit / config.setOpenTransaction(true);




    /**获取执行器*/
    Executor simpleExecutor = config.getExecutor();
    UserMapper userMapper = simpleExecutor.getMapper(UserMapper.class);

    User user = new User();
    user.setId(1);
    user.setName("xiabing");
    /**更新名字为xiabing,但未提交*/
    userMapper.update(user);

    User user1 = userMapper.getUserById(1);
    /**获取ID为1的名字,为root,说明上文的语句还没有提交*/
    System.out.println(user1.getName());
    /**事务提交语句*/
    //simpleExecutor.commit();
}
龙华大道1号http://www.kinghill.cn/LongHuaDaDao1Hao/index.html

Guess you like

Origin blog.csdn.net/weixin_45032957/article/details/108600052