MyBatisjava
ORMapping: Object Relationship Mapping 對象關係映射mysql
對象指⾯向對象,關係指關係型數據庫sql
Java 到 MySQL 的映射,開發者能夠以⾯向對象的思想來管理數據庫。數據庫
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.6</version> <scope>provided</scope> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build>
use mybatis; create table t_account( id int primary key auto_increment, username varchar(11), password varchar(11), age int )
import lombok.Data; @Data public class Account { private long id; private String username; private String password; private int age; }
<?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> <!-- 配置MyBatis運⾏環境 --> <environments default="development"> <environment id="development"> <!-- 配置JDBC事務管理 --> <transactionManager type="JDBC"></transactionManager> <!-- POOLED配置JDBC數據源鏈接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/mybatis? useUnicode=true&characterEncoding=UTF-8"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </dataSource> </environment> </environments> </configuration>
一、MyBatis 框架須要開發者⾃定義 SQL 語句,寫在 Mapper.xml ⽂件中,實際開發中,會爲每一個實體類建立對應的 Mapper.xml ,定義管理該對象數據的 SQL。apache
<?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.southwind.mapper.AccoutMapper"> <insert id="save" parameterType="com.southwind.entity.Account"> insert into t_account(username,password,age) values(#{username},#{password},#{age}) </insert> </mapper>
namespace 一般設置爲⽂件所在包+⽂件名的形式。api
insert 標籤表示執⾏添加操做。緩存
select 標籤表示執⾏查詢操做。session
update 標籤表示執⾏更新操做。mybatis
delete 標籤表示執⾏刪除操做。app
id 是實際調⽤ MyBatis ⽅法時須要⽤到的參數。parameterType 是調⽤對應⽅法時參數的數據類型。
二、在全局配置⽂件 config.xml 中註冊 AccountMapper.xml
<?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> <!-- 配置MyBatis運⾏環境 --> <environments default="development"> <environment id="development"> <!-- 配置JDBC事務管理 --> <transactionManager type="JDBC"></transactionManager> <!-- POOLED配置JDBC數據源鏈接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/mybatis? useUnicode=true&characterEncoding=UTF-8"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </dataSource> </environment> </environments> <!-- 註冊AccountMapper.xml --> <mappers> <mapper resource="com/southwind/mapper/AccountMapper.xml"></mapper> </mappers> </configuration>
三、調⽤ MyBatis 的原⽣接⼝執⾏添加操做。
public class Test { public static void main(String[] args) { //加載MyBatis配置⽂件 InputStream inputStream =Test.class.getClassLoader().getResourceAsStream("config.xml"); SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlSessionFactory =sqlSessionFactoryBuilder.build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); String statement = "com.southwind.mapper.AccoutMapper.save"; Account account = new Account(1L,"張三","123123",22); sqlSession.insert(statement,account); sqlSession.commit(); } }
⾃定義接⼝,定義相關業務⽅法。
編寫與⽅法相對應的 Mapper.xml。
一、⾃定義接⼝
package com.southwind.repository; import com.southwind.entity.Account; import java.util.List; public interface AccountRepository { public int save(Account account); public int update(Account account); public int deleteById(long id); public List<Account> findAll(); public Account findById(long id); }
二、建立接⼝對應的 Mapper.xml,定義接⼝⽅法對應的 SQL 語句。
statement 標籤可根據 SQL 執⾏的業務選擇 insert、delete、update、select。
MyBatis 框架會根據規則⾃動建立接⼝實現類的代理對象。
規則:
Mapper.xml 中 namespace 爲接⼝的全類名。
Mapper.xml 中 statement 的 id 爲接⼝中對應的⽅法名。
Mapper.xml 中 statement 的 parameterType 和接⼝中對應⽅法的參數類型⼀致。
Mapper.xml 中 statement 的 resultType 和接⼝中對應⽅法的返回值類型⼀致。
<?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.southwind.repository.AccountRepository"> <insert id="save" parameterType="com.southwind.entity.Account"> insert into t_account(username,password,age) values(#{username},#{password},#{age}) </insert> <update id="update" parameterType="com.southwind.entity.Account"> update t_account set username = #{username},password = #{password},age= #{age} where id = #{id} </update> <delete id="deleteById" parameterType="long"> delete from t_account where id = #{id} </delete> <select id="findAll" resultType="com.southwind.entity.Account"> select * from t_account </select> <select id="findById" parameterType="long" resultType="com.southwind.entity.Account"> select * from t_account where id = #{id} </select> </mapper>
三、在 confifig.xml 中註冊 AccountRepository.xml
<!-- 註冊AccountMapper.xml --> <mappers> <mapper resource="com/southwind/mapper/AccountMapper.xml"></mapper> <mapper resource="com/southwind/repository/AccountRepository.xml"></mapper> </mappers>
四、調⽤接⼝的代理對象完成相關的業務操做
package com.southwind.test; import com.southwind.entity.Account; import com.southwind.repository.AccountRepository; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; import java.util.List; public class Test2 { public static void main(String[] args) { InputStream inputStream =Test.class.getClassLoader().getResourceAsStream("config.xml"); SqlSessionFactoryBuilder sqlSessionFactoryBuilder = newSqlSessionFactoryBuilder(); SqlSessionFactory sqlSessionFactory =sqlSessionFactoryBuilder.build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); //獲取實現接⼝的代理對象 AccountRepository accountRepository =sqlSession.getMapper(AccountRepository.class); //添加對象 // Account account = new Account(3L,"王五","111111",24); // int result = accountRepository.save(account); // sqlSession.commit(); //查詢所有對象 // List<Account> list = accountRepository.findAll(); // for (Account account:list){ // System.out.println(account); // } // sqlSession.close(); //經過id查詢對象 // Account account = accountRepository.findById(3L); // System.out.println(account); // sqlSession.close(); //修改對象 // Account account = accountRepository.findById(3L); // account.setUsername("⼩明"); // account.setPassword("000"); // account.setAge(18); // int result = accountRepository.update(account); // sqlSession.commit(); // System.out.println(result); // sqlSession.close(); //經過id刪除對象 int result = accountRepository.deleteById(3L); System.out.println(result); sqlSession.commit(); sqlSession.close(); } }
Mapper.xml
statement 標籤:select、update、delete、insert 分別對應查詢、修改、刪除、添加操做。
parameterType:參數數據類型
一、基本數據類型,經過 id 查詢 Account
<select id="findById" parameterType="long" resultType="com.southwind.entity.Account"> select * from t_account where id = #{id} </select>
二、String 類型,經過 name 查詢 Account
<select id="findByName" parameterType="java.lang.String" resultType="com.southwind.entity.Account"> select * from t_account where username = #{username} </select>
三、包裝類,經過 id 查詢 Account
<select id="findById2" parameterType="java.lang.Long" resultType="com.southwind.entity.Account"> select * from t_account where id = #{id} </select>
四、多個參數,經過 name 和 age 查詢 Account
<select id="findByNameAndAge" resultType="com.southwind.entity.Account"> select * from t_account where username = #{arg0} and age = #{arg1} </select>
五、Java Bean
<update id="update" parameterType="com.southwind.entity.Account"> update t_account set username = #{username},password = #{password},age = #{age} where id = #{id} </update>
resultType:結果類型
一、基本數據類型,統計 Account 總數
<select id="count" resultType="int"> select count(id) from t_account </select>
二、包裝類,統計 Account 總數
<select id="count2" resultType="java.lang.Integer"> select count(id) from t_account </select>
三、String 類型,經過 id 查詢 Account 的 name
<select id="findNameById" resultType="java.lang.String"> select username from t_account where id = #{id} </select>
四、Java Bean
<select id="findById" parameterType="long" resultType="com.southwind.entity.Account"> select * from t_account where id = #{id} </select>
注意每次都要在cofig.xml裏面映射
Student
import lombok.Data; @Data public class Student { private long id; private String name; private Classes classes; }
Classes
import lombok.Data; import java.util.List; @Data public class Classes { private long id; private String name; private List<Student> students; }
StudentRepository
import com.southwind.entity.Student; public interface StudentRepository { public Student findById(long id); }
StudentRepository.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.southwind.repository.StudentRepository"> <resultMap id="studentMap" type="com.southwind.entity.Student"> <id column="id" property="id"></id>//只有主鍵用id,其餘用result,column是sql表,映射到實體類property <result column="name" property="name"></result> <association property="classes" javaType="com.southwind.entity.Classes"> <id column="cid" property="id"></id> <result column="cname" property="name"></result> </association> </resultMap> <select id="findById" parameterType="long" resultMap="studentMap"> select s.id,s.name,c.id as cid,c.name as cname from student s,classes c where s.id = #{id} and s.cid = c.id </select> </mapper>
ClassesRepository
import com.southwind.entity.Classes; public interface ClassesRepository { public Classes findById(long id); }
ClassesRepository.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.southwind.repository.ClassesRepository"> <resultMap id="classesMap" type="com.southwind.entity.Classes"> <id column="cid" property="id"></id> <result column="cname" property="name"></result> <collection property="students" ofType="com.southwind.entity.Student"> <id column="id" property="id"/> <result column="name" property="name"/> </collection> </resultMap> <select id="findById" parameterType="long" resultMap="classesMap"> select s.id,s.name,c.id as cid,c.name as cname from student s,classes c where c.id = #{id} and s.cid = c.id </select> </mapper>
多對多
用一張中間錶鏈接顧客與貨物
Customer
import lombok.Data; import java.util.List; @Data public class Customer { private long id; private String name; private List<Goods> goods; }
Goods
import lombok.Data; import java.util.List; @Data public class Goods { private long id; private String name; private List<Customer> customers; }
CustomerRepository
import com.southwind.entity.Customer; public interface CustomerRepository { public Customer findById(long id); }
CustomerRepository.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.southwind.repository.CustomerRepository"> <resultMap id="customerMap" type="com.southwind.entity.Customer"> <id column="cid" property="id"></id> <result column="cname" property="name"></result> <collection property="goods" ofType="com.southwind.entity.Goods">//customer裏面有goods集合 <id column="gid" property="id"/> <result column="gname" property="name"/> </collection> </resultMap> <select id="findById" parameterType="long" resultMap="customerMap"> select c.id cid,c.name cname,g.id gid,g.name gname from customer c,goods g,customer_goods cg where c.id = #{id} and cg.cid = c.id and cg.gid = g.id </select> </mapp
GoodsRepository
import com.southwind.entity.Goods; public interface GoodsRepository { public Goods findById(long id); }
GoodsRepository.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.southwind.repository.GoodsRepository"> <resultMap id="goodsMap" type="com.southwind.entity.Goods"> <id column="gid" property="id"></id> <result column="gname" property="name"></result> <collection property="customers" ofType="com.southwind.entity.Customer"> <id column="cid" property="id"/> <result column="cname" property="name"/> </collection> </resultMap> <select id="findById" parameterType="long" resultMap="goodsMap"> select c.id cid,c.name cname,g.id gid,g.name gname from customer c,goods g,customer_goods cg where g.id = #{id} and cg.cid = c.id and cg.gid = g.id </select> </mapper>
test
public class Test3 { public static void main(String[] args) { InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml"); SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); StudentRepository studentRepository = sqlSession.getMapper(StudentRepository.class); Student student = studentRepository.findByIdLazy(1L); System.out.println(student.getClasses()); // ClassesRepository classesRepository = sqlSession.getMapper(ClassesRepository.class); // System.out.println(classesRepository.findByIdLazy(student.getClasses().getId())); // ClassesRepository classesRepository = sqlSession.getMapper(ClassesRepository.class); // System.out.println(classesRepository.findById(2L)); // CustomerRepository customerRepository = sqlSession.getMapper(CustomerRepository.class); // System.out.println(customerRepository.findById(1L)); // GoodsRepository goodsRepository = sqlSession.getMapper(GoodsRepository.class); // System.out.println(goodsRepository.findById(1L)); sqlSession.close(); } }
MyBatis 框架須要:實體類、⾃定義 Mapper 接⼝、Mapper.xml
傳統的開發中上述的三個組件須要開發者⼿動建立,逆向⼯程能夠幫助開發者來⾃動建立三個組件,減輕開發者的⼯做量,提⾼⼯做效率。
如何使⽤
MyBatis Generator,簡稱 MBG,是⼀個專⻔爲 MyBatis 框架開發者定製的代碼⽣成器,可⾃動⽣成MyBatis 框架所需的實體類、Mapper 接⼝、Mapper.xml,⽀持基本的 CRUD 操做,可是⼀些相對複雜的 SQL 須要開發者⾃⼰來完成。
新建 Maven ⼯程,pom.xml
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> </dependency> </dependencies>
建立 MBG 配置⽂件 generatorConfifig.xml
一、jdbcConnection 配置數據庫鏈接jdbc信息。
二、javaModelGenerator 配置 JavaBean 的⽣成策略。
三、sqlMapGenerator 配置 SQL 映射⽂件⽣成策略。
四、javaClientGenerator 配置 Mapper 接⼝的⽣成策略。
五、table 配置⽬標數據表(tableName:表名,domainObjectName:JavaBean 類名)。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="testTables" targetRuntime="MyBatis3"> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis? useUnicode=true&characterEncoding=UTF-8" userId="root" password="root" ></jdbcConnection> <javaModelGenerator targetPackage="com.southwind.entity"//實體類存放的包 targetProject="./src/main/java"></javaModelGenerator>//包放的位置 <sqlMapGenerator targetPackage="com.southwind.repository" targetProject="./src/main/java"></sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="com.southwind.repository" targetProject="./src/main/java"> </javaClientGenerator> <table tableName="t_user" domainObjectName="User"></table> </context> </generatorConfiguration>
import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.exception.InvalidConfigurationException; import org.mybatis.generator.exception.XMLParserException; import org.mybatis.generator.internal.DefaultShellCallback; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<String> warings = new ArrayList<String>(); boolean overwrite = true; String genCig = "/generatorConfig.xml";//剛纔寫的配置文件路徑 File configFile = new File(Main.class.getResource(genCig).getFile()); ConfigurationParser configurationParser = newConfigurationParser(warings); Configuration configuration = null; try { configuration = configurationParser.parseConfiguration(configFile); } catch (IOException e) { e.printStackTrace(); } catch (XMLParserException e) { e.printStackTrace(); } DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = null; try { myBatisGenerator = newMyBatisGenerator(configuration,callback,warings); } catch (InvalidConfigurationException e) { e.printStackTrace(); } try { myBatisGenerator.generate(null); } catch (SQLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
什麼是延遲加載?
延遲加載也叫懶加載、惰性加載,使⽤延遲加載能夠提⾼程序的運⾏效率,針對於數據持久層的操做,
在某些特定的狀況下去訪問特定的數據庫,在其餘狀況下能夠不訪問某些表,從⼀定程度上減小了 Java應⽤與數據庫的交互次數。
查詢學⽣和班級的時,學⽣和班級是兩張不一樣的表,若是當前需求只須要獲取學⽣的信息,那麼查詢學⽣單表便可,若是須要經過學⽣獲取對應的班級信息,則必須查詢兩張表。
不一樣的業務需求,須要查詢不一樣的表,根據具體的業務需求來動態減小數據表查詢的⼯做就是延遲加載。
<settings> <!-- 打印SQL--> <setting name="logImpl" value="STDOUT_LOGGING" /> <!-- 開啓延遲加載 --> <setting name="lazyLoadingEnabled" value="true"/> </settings>
StudentRepository
public Student findByIdLazy(long id);
StudentRepository.xml
<resultMap id="studentMapLazy" type="com.southwind.entity.Student"> <id column="id" property="id"></id> <result column="name" property="name"></result> <association property="classes" javaType="com.southwind.entity.Classes" select="com.southwind.repository.ClassesRepository.findByIdLazy" column="cid">//重點 </association> </resultMap> <select id="findByIdLazy" parameterType="long" resultMap="studentMapLazy"> select * from student where id = #{id} </select
ClassesRepository
public Classes findByIdLazy(long id);
ClassesRepository.xml
<select id="findByIdLazy" parameterType="long" resultType="com.southwind.entity.Classes"> select * from classes where id = #{id} </select>
什麼是 MyBatis 緩存
使⽤緩存能夠減小 Java 應⽤與數據庫的交互次數,從⽽提高程序的運⾏效率。⽐如查詢出 id = 1 的對象,第⼀次查詢出以後會⾃動將該對象保存到緩存中,當下⼀次查詢時,直接從緩存中取出對象便可,⽆需再次訪問數據庫。
MyBatis 緩存分類
一、⼀級緩存:SqlSession 級別,默認開啓,而且不能關閉。
操做數據庫時須要建立 SqlSession 對象,在對象中有⼀個 HashMap ⽤於存儲緩存數據,不一樣的SqlSession 之間緩存數據區域是互不影響的。⼀級緩存的做⽤域是 SqlSession 範圍的,當在同⼀個 SqlSession 中執⾏兩次相同的 SQL 語句事,第⼀次執⾏完畢會將結果保存到緩存中,第⼆次查詢時直接從緩存中獲取。
須要注意的是,若是 SqlSession 執⾏了 DML 操做(insert、update、delete),MyBatis 必須將緩存清空以保證數據的準確性。
import com.southwind.entity.Account; import com.southwind.repository.AccountRepository; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; public class Test4 { public static void main(String[] args) { InputStream inputStream =Test.class.getClassLoader().getResourceAsStream("config.xml"); SqlSessionFactoryBuilder sqlSessionFactoryBuilder = newSqlSessionFactoryBuilder(); SqlSessionFactory sqlSessionFactory =sqlSessionFactoryBuilder.build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); AccountRepository accountRepository =sqlSession.getMapper(AccountRepository.class); Account account = accountRepository.findById(1L); System.out.println(account); sqlSession.close();//關掉就會查兩次,不關只查一次 sqlSession = sqlSessionFactory.openSession(); accountRepository = sqlSession.getMapper(AccountRepository.class); Account account1 = accountRepository.findById(1L); System.out.println(account1); } }
二、⼆級緩存:Mapper 級別,默認關閉,能夠開啓。
使⽤⼆級緩存時,多個 SqlSession 使⽤同⼀個 Mapper 的 SQL 語句操做數據庫,獲得的數據會存在⼆級緩存區,一樣是使⽤ HashMap 進⾏數據存儲,相⽐較於⼀級緩存,⼆級緩存的範圍更⼤,多個SqlSession 能夠共⽤⼆級緩存,⼆級緩存是跨 SqlSession 的。
⼆級緩存是多個 SqlSession 共享的,其做⽤域是 Mapper 的同⼀個 namespace,不一樣的 SqlSession兩次執⾏相同的 namespace 下的 SQL 語句,參數也相等,則第⼀次執⾏成功以後會將數據保存到⼆級緩存中,第⼆次可直接從⼆級緩存中取出數據。
一、MyBatis ⾃帶的⼆級緩存
<settings> <!-- 打印SQL--> <setting name="logImpl" value="STDOUT_LOGGING" /> <!-- 開啓延遲加載 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 開啓⼆級緩存 --> <setting name="cacheEnabled" value="true"/> </settings>
//加在mapper標籤底下 <cache></cache>
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @AllArgsConstructor @NoArgsConstructor public class Account implements Serializable { private long id; private String username; private String password; private int age; }
二、ehcache ⼆級緩存
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.4.3</version> </dependency
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"> <diskStore/> <defaultCache maxElementsInMemory="1000" maxElementsOnDisk="10000000" eternal="false" overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> </defaultCache> </ehcache>
<settings> <!-- 打印SQL--> <setting name="logImpl" value="STDOUT_LOGGING" /> <!-- 開啓延遲加載 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 開啓⼆級緩存 --> <setting name="cacheEnabled" value="true"/> </settings>
<cache type="org.mybatis.caches.ehcache.EhcacheCache"> <!-- 緩存建立以後,最後⼀次訪問緩存的時間⾄緩存失效的時間間隔 --> <property name="timeToIdleSeconds" value="3600"/> <!-- 緩存⾃建立時間起⾄失效的時間間隔 --> <property name="timeToLiveSeconds" value="3600"/> <!-- 緩存回收策略,LRU表示移除近期使⽤最少的對象 --> <property name="memoryStoreEvictionPolicy" value="LRU"/> </cache>
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Account { private long id; private String username; private String password; private int age; }
使⽤動態 SQL 可簡化代碼的開發,減小開發者的⼯做量,程序能夠⾃動根據業務參數來決定 SQL 的組成。
都是寫在repository.xml裏面的
if 標籤
if 標籤能夠⾃動根據表達式的結果來決定是否將對應的語句添加到 SQL 中,若是條件不成⽴則不添加,若是條件成⽴則添加。
<select id="findByAccount" parameterType="com.southwind.entity.Account" resultType="com.southwind.entity.Account"> select * from t_account <where> <if test="id!=0"> id = #{id} </if> <if test="username!=null"> and username = #{username} </if> <if test="password!=null"> and password = #{password} </if> <if test="age!=0"> and age = #{age} </if> </where> </select>
where 標籤能夠⾃動判斷是否要刪除語句塊中的 and 關鍵字,若是檢測到 where 直接跟 and 拼接,則⾃動刪除 and,一般狀況下 if 和 where 結合起來使⽤。
<select id="findByAccount" parameterType="com.southwind.entity.Account" resultType="com.southwind.entity.Account"> select * from t_account <where> <if test="id!=0"> id = #{id} </if> <if test="username!=null"> and username = #{username} </if> <if test="password!=null"> and password = #{password} </if> <if test="age!=0"> and age = #{age} </if> </where> </select>
相似if標籤
<select id="findByAccount" parameterType="com.southwind.entity.Account" resultType="com.southwind.entity.Account"> select * from t_account <where> <choose> <when test="id!=0"> id = #{id} </when> <when test="username!=null"> username = #{username} </when> <when test="password!=null"> password = #{password} </when> <when test="age!=0"> age = #{age} </when> </choose> </where> </select>
trim 標籤中的 prefifix 和 suffiffiffix 屬性會被⽤於⽣成實際的 SQL 語句,相似where,會刪掉匹配的字段,會和標籤內部的語句進⾏拼接,若是語句先後出現了 prefifixOverrides 或者 suffiffiffixOverrides 屬性中指定的值,MyBatis 框架會⾃動將其刪除
<select id="findByAccount" parameterType="com.southwind.entity.Account" resultType="com.southwind.entity.Account"> select * from t_account <trim prefix="where" prefixOverrides="and"> <if test="id!=0"> id = #{id} </if> <if test="username!=null"> and username = #{username} </if> <if test="password!=null"> and password = #{password} </if> <if test="age!=0"> and age = #{age} </if> </trim> </select>
set 標籤⽤於 update 操做,會⾃動根據參數選擇⽣成 SQL 語句,好比修改屬性的時候,只改了部分,這時候不必把相同的屬性也作替換
<update id="update" parameterType="com.southwind.entity.Account"> update t_account <set> <if test="username!=null"> username = #{username}, </if> <if test="password!=null"> password = #{password}, </if> <if test="age!=0"> age = #{age} </if> </set> where id = #{id} </update>
foreach 標籤能夠迭代⽣成⼀系列值,這個標籤主要⽤於 SQL 的 in 語句。
<select id="findByIds" parameterType="com.southwind.entity.Account" resultType="com.southwind.entity.Account"> select * from t_account <where> <foreach collection="ids" open="id in (" close=")" item="id" separator=","> #{id} </foreach> </where> </select>
AccountRepository
public List<Account> findByIds(Account account);