CREATE DATABASE `mybatis-example`;
USE `mybatis-example`;
CREATE TABLE `t_emp`(
emp_id INT AUTO_INCREMENT,
emp_name CHAR(100),
emp_salary DOUBLE(10,5),
PRIMARY KEY(emp_id)
);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("tom",200.33);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("jerry",666.66);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("andy",777.77);
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.alexgroupId>
<artifactId>part04-ssm-integrationartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<properties>
<spring.version>6.0.6spring.version>
<jakarta.annotation-api.version>2.1.1jakarta.annotation-api.version>
<jakarta.jakartaee-web-api.version>9.1.0jakarta.jakartaee-web-api.version>
<jackson-databind.version>2.15.0jackson-databind.version>
<hibernate-validator.version>8.0.0.Finalhibernate-validator.version>
<mybatis.version>3.5.11mybatis.version>
<mysql.version>8.0.25mysql.version>
<pagehelper.version>5.1.11pagehelper.version>
<druid.version>1.2.8druid.version>
<mybatis-spring.version>3.0.2mybatis-spring.version>
<jakarta.servlet.jsp.jstl-api.version>3.0.0jakarta.servlet.jsp.jstl-api.version>
<logback.version>1.2.3logback.version>
<lombok.version>1.18.26lombok.version>
<maven.compiler.source>17maven.compiler.source>
<maven.compiler.target>17maven.compiler.target>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>jakarta.annotationgroupId>
<artifactId>jakarta.annotation-apiartifactId>
<version>${jakarta.annotation-api.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>jakarta.platformgroupId>
<artifactId>jakarta.jakartaee-web-apiartifactId>
<version>${jakarta.jakartaee-web-api.version}version>
<scope>providedscope>
dependency>
<dependency>
<groupId>jakarta.servlet.jsp.jstlgroupId>
<artifactId>jakarta.servlet.jsp.jstl-apiartifactId>
<version>${jakarta.servlet.jsp.jstl-api.version}version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>${jackson-databind.version}version>
dependency>
<dependency>
<groupId>org.hibernate.validatorgroupId>
<artifactId>hibernate-validatorartifactId>
<version>${hibernate-validator.version}version>
dependency>
<dependency>
<groupId>org.hibernate.validatorgroupId>
<artifactId>hibernate-validator-annotation-processorartifactId>
<version>${hibernate-validator.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>${pagehelper.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>${mybatis-spring.version}version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>${logback.version}version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>${lombok.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>${druid.version}version>
dependency>
dependencies>
project>
@Data
public class Employee {
private Integer empId;
private String empName;
private Double empSalary;
}
<configuration debug="true">
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%npattern>
<charset>UTF-8charset>
encoder>
appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
root>
<logger name="com.alex.mybatis" level="DEBUG" />
configuration>
主要配置 controller,springmvc 相关组件配置
/**
* projectName: com.alex.config
*
* 1.实现Springmvc组件声明标准化接口WebMvcConfigurer 提供了各种组件对应的方法
* 2.添加配置类注解@Configuration
* 3.添加mvc复合功能开关@EnableWebMvc
* 4.添加controller层扫描注解
* 5.开启默认处理器,支持静态资源处理
*/
@Configuration
@EnableWebMvc
@ComponentScan("com.alex.controller")
public class WebJavaConfig implements WebMvcConfigurer {
//开启静态资源
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
主要配置 service,注解 aop 和声明事务相关配置
/**
* projectName: com.alex.config
*
* 1. 声明@Configuration注解,代表配置类
* 2. 声明@EnableTransactionManagement注解,开启事务注解支持
* 3. 声明@EnableAspectJAutoProxy注解,开启aspect aop注解支持
* 4. 声明@ComponentScan("com.alex.service")注解,进行业务组件扫描
* 5. 声明transactionManager(DataSource dataSource)方法,指定具体的事务管理器
*/
@EnableTransactionManagement
@EnableAspectJAutoProxy
@Configuration
@ComponentScan("com.alex.service")
public class ServiceJavaConfig {
@Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
主要配置 mapper 代理对象,连接池和 mybatis 核心组件配置
//1.读取外部配置文件
InputStream ips = Resources.getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);
//3.创建sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.获取mapper代理对象
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
//5.数据库方法调用
int rows = empMapper.deleteEmpById(1);
System.out.println("rows = " + rows);
//6.提交和回滚
sqlSession.commit();
sqlSession.close();
@Bean
public SqlSessionFactory sqlSessionFactory(){
//1.读取外部配置文件
InputStream ips = Resources.getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);
return sqlSessionFactory;
}
package org.mybatis.spring;
public class SqlSessionFactoryBean
implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ContextRefreshedEvent> {
//封装了实例化流程
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
//实例化对象逻辑
afterPropertiesSet();
}
//返回对象逻辑
return this.sqlSessionFactory;
}
}
数据库连接信息
jdbc.user=root
jdbc.password=root
jdbc.url=jdbc:mysql:///mybatis-example
jdbc.driver=com.mysql.cj.jdbc.Driver
数据库信息以及 mapper 扫描包设置使用 Java 配置类处理!mybatis 其他的功能(别名、settings、插件等信息)依然在 mybatis-config.xml 配置!
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="logImpl" value="SLF4J"/>
<setting name="autoMappingBehavior" value="FULL"/>
settings>
<typeAliases>
<package name="com.alex.pojo"/>
typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="mysql"/>
plugin>
plugins>
configuration>
持久层 Mapper 配置、数据库配置、Mybatis 配置信息
@Configuration
@PropertySource("classpath:jdbc.properties")
public class MapperJavaConfig {
@Value("${jdbc.user}")
private String user;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.driver}")
private String driver;
//数据库连接池配置
@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setDriverClassName(driver);
return dataSource;
}
/**
* 配置SqlSessionFactoryBean,指定连接池对象和外部配置文件即可
* @param dataSource 需要注入连接池对象
* @return 工厂Bean
*/
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
//实例化SqlSessionFactory工厂
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//设置连接池
sqlSessionFactoryBean.setDataSource(dataSource);
//设置配置文件
//包裹外部配置文件地址对象
Resource resource = new ClassPathResource("mybatis-config.xml");
sqlSessionFactoryBean.setConfigLocation(resource);
return sqlSessionFactoryBean;
}
/**
* 配置Mapper实例扫描工厂,配置
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//设置mapper接口和xml文件所在的共同包
mapperScannerConfigurer.setBasePackage("com.alex.mapper");
return mapperScannerConfigurer;
}
}
sqlSessionFactoryBean
和mapperScannerConfigurer
配置方法时,可能会导致@Value
注解读取不到值为 null 的问题。这是因为SqlSessionFactoryBean
和MapperScannerConfigurer
是基于 MyBatis 框架的配置,它们的初始化顺序可能会导致属性注入的问题。SqlSessionFactoryBean
和MapperScannerConfigurer
在配置类中通常是用来配置 MyBatis 相关的 Bean,例如数据源、事务管理器、Mapper 扫描等。这些配置类通常在@Configuration
注解下定义,并且使用@Value
注解来注入属性值。sqlSessionFactoryBean
和mapperScannerConfigurer
的初始化。在这个过程中,如果@Value
注解所在的 Bean 还没有被完全初始化,可能会导致注入的属性值为 null。@Configuration
@PropertySource("classpath:jdbc.properties")
public class DataSourceJavaConfig {
@Value("${jdbc.user}")
private String user;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.driver}")
private String driver;
//数据库连接池配置
@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setDriverClassName(driver);
return dataSource;
}
}
@Configuration
public class MapperJavaConfig {
/**
* 配置SqlSessionFactoryBean,指定连接池对象和外部配置文件即可
* @param dataSource 需要注入连接池对象
* @return 工厂Bean
*/
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
//实例化SqlSessionFactory工厂
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//设置连接池
sqlSessionFactoryBean.setDataSource(dataSource);
//设置配置文件
//包裹外部配置文件地址对象
Resource resource = new ClassPathResource("mybatis-config.xml");
sqlSessionFactoryBean.setConfigLocation(resource);
return sqlSessionFactoryBean;
}
/**
* 配置Mapper实例扫描工厂,配置
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//设置mapper接口和xml文件所在的共同包
mapperScannerConfigurer.setBasePackage("com.alex.mapper");
return mapperScannerConfigurer;
}
}
/**
* projectName: com.alex.config
*
* description: 持久层配置和Druid和Mybatis配置 使用一个配置文件
*/
@Configuration
public class MapperJavaConfigNew {
/**
* 配置SqlSessionFactoryBean,指定连接池对象和外部配置文件即可
* @param dataSource 需要注入连接池对象
* @return 工厂Bean
*/
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
//实例化SqlSessionFactory工厂
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//设置连接池
sqlSessionFactoryBean.setDataSource(dataSource);
//TODO: 替代xml文件的java配置
/*
*/
//settings [包裹到一个configuration对象,切记别倒错包]
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setMapUnderscoreToCamelCase(true);
configuration.setLogImpl(Slf4jImpl.class);
configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);
sqlSessionFactoryBean.setConfiguration(configuration);
//typeAliases
sqlSessionFactoryBean.setTypeAliasesPackage("com.alex.pojo");
//分页插件配置
PageInterceptor pageInterceptor = new PageInterceptor();
Properties properties = new Properties();
properties.setProperty("helperDialect","mysql");
pageInterceptor.setProperties(properties);
sqlSessionFactoryBean.addPlugins(pageInterceptor);
return sqlSessionFactoryBean;
}
/**
* 配置Mapper实例扫描工厂,配置
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//设置mapper接口和xml文件所在的共同包
mapperScannerConfigurer.setBasePackage("com.alex.mapper");
return mapperScannerConfigurer;
}
}
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
//指定root容器对应的配置类
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] {MapperJavaConfig.class, ServiceJavaConfig.class, DataSourceJavaConfig.class };
}
//指定web容器对应的配置类
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebJavaConfig.class };
}
//指定dispatcherServlet处理路径,通常为 /
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping("list")
public List<Employee> retList(){
List<Employee> employees = employeeService.findAll();
log.info("员工数据:{}",employees);
return employees;
}
}
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
/**
* 查询所有员工信息
*/
@Override
public List<Employee> findAll() {
List<Employee> employeeList = employeeMapper.queryAll();
return employeeList;
}
}
public interface EmployeeMapper {
List<Employee> queryAll();
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.alex.mapper.EmployeeMapper">
<select id="queryAll" resultType="employee">
select emp_id empId,emp_name empName, emp_salary empSalary from t_emp
select>
mapper>