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);