Mybatis 简介
1.1 什么是Mybatis
MyBatis 是一款优秀的持久层框架,他支持自定义Sql,存储过程以及高级映射,MyBatis免除了几乎所有JDBC代码以及设置参数和获取结果集的工作,MyBatis可以通过简单的xml或这届来配置和映射原始类型,接口和java pojo 为数据库中的记录
MyBats官网
1.2 为什么是Mybatis
1)Mybatis 是一个半自动的持久化层框架
2)jdbc
3) Hibernate & Spring Data Jpa
长难度复杂sql,对于Hinbernate 而言处理也不容易
内部自动生成sql,不容易做特殊优化
全映射的全自动框架,大量自动的pojo进行部分映射时比较困难,导致数据库性能下降
1.3 ORM框架
ORM 表示 Object-RelationalMapping 。他时一个思想,其本质是吧数据库中的数据用对象来表示
2.xml文件配置Mybatis
2.1 导入依赖
<!--测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--spring核心包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<!--mybatis和spring集成的-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.0</version>
</dependency>
<!--Druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
2.2 项目结构
【注意,config,dao,service包,SpringConfiguration类】是全注解配置时使用的,target包下如果没有mapper的编译文件,重新编译一下项目
2.3 编写Mybatis-config.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>
<settings>
<!--开启驼峰命名规则-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--延迟加载的全局开关-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--开启按需加载的开关-->
<setting name="aggressiveLazyLoading" value="false"/>
<!--开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
</configuration>
2.4 编写druid.properties 数据库配置文件
【注意】:我使用的MySql是8.0,请大家改成对应的
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/cs?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8&useUnicode=yes
jdbc.username=root
jdbc.password=root
2.5 遍application.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.alibaba.com/schema/stat"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="cn.zb.spring"/>
<!--引入外部数据库配置文件-->
<context:property-placeholder location="classpath:druid.properties"/>
<!--配置数据库连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--注册事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--开启事务的注解-->
<tx:annotation-driven/>
<!--配置接口扫描,因为UsersMapper.java没有实现类,所以必须依靠cglib在内存里构造代理对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入mapper接口所在的包-->
<property name="basePackage" value="cn.zb.spring.mapper"/>
<!--注入sqlSessionFactoryBeanName 也就时IOC容器里面的sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!--在Spring容器中注册sqlSessionFactory的实例-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--配置mybatis主配置文件-->
<property name="configLocation" value="classpath:Mybatis-config.xml"/>
<!--别名配置 可以修改别名的包路径-->
<property name="typeAliasesPackage" value="cn.zb.spring.entity" />
<!--配置 XML映射-->
<property name="mapperLocations" value="classpath*:mapper/*.xml" />
</bean>
<!--批量配置映射器 可以修改映射器包路径-->
<!--映射xml文件-->
<!--<mapper resource="cn/zb/spring/mapper/UsersMapper.xml"/>-->
<!--映射接口类-->
<!--<mapper class="cn.zb.spring.mapper"/>-->
<!--整个包映射-->
<mybatis-spring:scan base-package="cn.zb.spring.mapper"/>
</beans>
3. Spring 整合lombok
3.1 下载插件,依赖前面导过了
3.2 编写实体类,了解Lombok基础注解
【注意】:实体类字段应于数据库字段对应,且是驼峰命名法
package cn.zb.spring.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data //提供类所有属性的get,set方法,此外还提供了equals,canEqual,hashCode.toString方法
@AllArgsConstructor //提供全参的构造方法
@NoArgsConstructor //提供无参的构造方法
public class Users {
private Long userId;
private String userName;
private String userPwd;
}
3.3 编写UsersMapper接口以及UsersMapper.xml文件
package cn.zb.spring.mapper;
import cn.zb.spring.entity.Users;
import org.springframework.stereotype.Repository;
@Repository
public interface UsersMapper {
//根据id查询,返回Users对象,方法名与UsersMapper.xml中id对应
Users getByUserId(int userId);
//查询所有
List<Users> getAll();
}
【注意】: #{value} ,${value}都是占位符,${value} 有sql注入的风险,不会区分数据类型
<?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="cn.zb.spring.mapper.UsersMapper">
<select id="getByUserId" resultType="cn.zb.spring.entity.Users">
select * from users where user_id=#{userId}
</select>
<select id="getAll" resultType="cn.zb.spring.entity.Users">
select * from users
</select>
</mapper>
3.4 编写测试类
package cn.zb.test;
import cn.zb.spring.entity.Users;
import cn.zb.spring.mapper.UsersMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application.xml")
public class SpringTest {
@Autowired
private UsersMapper usersMapper;
@Test
public void test1(){
Users users = usersMapper.getByUserId(1);
System.out.println(users);
}
@Test
public void test2(){
int pageIndex=0; //分页插件从0开始查
int pageSize=5;
PageInfo<Object> pageInfo = PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> usersMapper.getAll());
//获取的对象集合
pageInfo.getList().forEach(System.out::println);
//表中共有多少数据条数
System.out.println(pageInfo.getTotal());
}
}
4. 通过注解配置Mybatis
4.1 编写SpringConfiguration配置类代替 application.xml
package cn.zb.spring;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan("cn.zb.spring") //开启包扫描
//@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableTransactionManagement //开启事务
@MapperScan("cn.zb.spring.mapper")
@Import({MybatisConfig.class}) //引入Mybatis配置类
public class SpringConfiguration {
}
4.2 编写DuridConfig类替代application.xml 中的数据源配置
package cn.zb.spring.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
@PropertySource(value = "classpath:druid.properties") //引入druid配置文件
public class DruidConfig {
@Value("${jdbc.driverClassName}")
private String driverClassName;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DruidDataSource getDDruidDataSource(){
DruidDataSource dataSource=new DruidDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
// 不通过配置文件获取,直接传属性
// @Bean
// public DruidDataSource getDDruidDataSource(){
// DruidDataSource dataSource=new DruidDataSource();
// dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
// dataSource.setUrl("jdbc:mysql://localhost:3306/cs?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8&useUnicode=yes");
// dataSource.setUsername("root");
// dataSource.setPassword("root");
// return dataSource;
// }
//创建JdbcTemplate对象
@Bean
public JdbcTemplate getJdbcTemplate(DataSource dataSource){
JdbcTemplate jdbcTemplate=new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
}
4.3 编写MybatisConfig配置类,替代application.xml的Mybait配置
package cn.zb.spring.config;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(@Autowired DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage("cn.zb.spring.entity");
Configuration configuration = new Configuration();
configuration.setMapUnderscoreToCamelCase(true);
sqlSessionFactoryBean.setConfiguration(configuration);
return sqlSessionFactoryBean;
}
}
4.4 编写UsersMapper,使用注解开发接口
package cn.zb.spring.mapper;
import cn.zb.spring.entity.Users;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UsersMapper {
//根据id查询,返回Users对象,方法名与UsersMapper.xml中id对应
@Select("select * from users where user_id=#{userId}")
//@Update("sql") //修改
//@Delete("sql") //删除
//@Insert("sql") //新增
Users getByUserId(int userId);
@Select("select * from users")
List<Users> getAll();
}
4.5 编写测试类
package cn.zb.test;
import cn.zb.spring.SpringConfiguration;
import cn.zb.spring.mapper.UsersMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) //替换原来的运行期
@ContextConfiguration(classes = {SpringConfiguration.class}) //指定配置文件或配置类
public class SpringJunitTest {
@Autowired
private UsersMapper usersMapper;
@Test
public void test1(){
System.out.println(usersMapper.getByUserId(1));
}
@Test
public void test2(){
int pageIndex=0; //分页插件从0开始查
int pageSize=5;
PageInfo<Object> pageInfo = PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> usersMapper.getAll());
//获取的对象集合
pageInfo.getList().forEach(System.out::println);
//表中共有多少数据条数
System.out.println(pageInfo.getTotal());
}
}
本文仅做记录使用,参考其他的文献