spring使用xml配置整合mybatis
一、配置项目
1. 目录结构
2. 导入依赖
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
<!-- mybatis和spring集成的依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.2</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<!-- 阿里公司的数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.18</version>
</dependency>
<!-- log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
3. 创建jdbc.properties数据库配置文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
4. 创建log4j.properties日志配置文件
#
log4j.rootLogger=DEBUG,stdout
# MyBatis logging configuration...
# MyBatis
log4j.logger.com.example.test.datasource.service.UserServiceImpl=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
5. 创建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="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- <mappers>-->
<!-- <mapper resource="mapper_xml/student.xml"/>-->
<!-- 将dao包下的所有mapper文件全部扫描 -->
<!-- <package name="com.example.test.datasource.mappers"/>-->
<!-- </mappers>-->
</configuration>
6.给bean.xml配置文件添加mybatis自动注入配置
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 加载外部数据库属性配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 声明数据源DataSource,这里数据源使用阿里数据源 -->
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="clone">
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 声明SqlSessionFactoryBean,在这个类的内部,创建SqlSessionFactory对象,之后就可以获取SqlSession对象 -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定数据源 -->
<property name="dataSource" ref="myDataSource"/>
<!-- 指定mybatis主配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 指定mapper配置文件,配置SQL映射的文件路径 -->
<property name="mapperLocations" value="classpath:mapper_xml/*.xml"/>
</bean>
<!-- 声明MapperScannerConfigurer -->
<!--
MapperScannerConfigurer作用:
循环basePackage所表示的包,把包中的每个接口都找到,调用SqlSession.getMapper(XXXMapper.class)
把每个mapper接口都创建出对应的mapper代理对象,并将mapper代理对象放在容器中
对于StudentMapper接口,其代理对象为 studentMapper
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定SqlSessionFactory对象的名称 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/>
<!-- 指定基本包,mapper接口所在的包名 -->
<property name="basePackage" value="com.example.test.datasource.mappers"/>
</bean>
<!--声明使用spring的事务处理,声明后可使用@Transactional注解实现方法|类的事务处理-->
<!--1、声明事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--连接的数据库,指定数据源-->
<property name="dataSource" ref="myDataSource"/>
</bean>
<!--2、开启事务注解驱动,告诉sprint使用注解管理事务,创建代理对象-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 声明service -->
<bean id="studentServiceImpl" class="com.example.test.datasource.service.StudentServiceImpl">
<property name="mapper" ref="studentMapper"/>
</bean>
</beans>
7. 创建数据库
CREATE TABLE `student` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`gender` tinyint(1) NOT NULL,
`grade` int(11) NOT NULL,
`score` int(11) NOT NULL,
`balance` decimal(10,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
二、创建实体、映射、服务类
1.创建实体类
package com.example.test.datasource.entities;
import java.math.BigDecimal;
public class Student {
private int id;
private String name;
private int gender;
private int grade;
private int score;
private BigDecimal balance;
public Student() {
}
public Student(int id, String name, int gender, int grade, int score, BigDecimal balance) {
this.id = id;
this.name = name;
this.gender = gender;
this.grade = grade;
this.score = score;
this.balance = balance;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", gender=" + gender +
", grade=" + grade +
", score=" + score +
", balance=" + balance +
'}';
}
}
2.创建映射类
package com.example.test.datasource.mappers;
import com.example.test.datasource.entities.Student;
import java.util.List;
public interface StudentMapper {
List<Student> queryAll();
int addStudent(Student student);
}
3.创建服务类
package com.example.test.datasource.service;
import com.example.test.datasource.entities.Student;
import java.util.List;
public interface StudentService {
List<Student> queryAll();
int addStudent(Student student);
}
package com.example.test.datasource.service;
import com.example.test.datasource.entities.Student;
import com.example.test.datasource.mappers.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
public class StudentServiceImpl implements StudentService {
private StudentMapper mapper;
public void setMapper(StudentMapper mapper) {
this.mapper = mapper;
}
@Override
public List<Student> queryAll()
{
return mapper.queryAll();
}
@Override
public int addStudent(Student student)
{
return mapper.addStudent(student);
}
}
三、SQL测试
String config = "bean.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(config);
StudentService studentService = context.getBean(StudentServiceImpl.class);
List<Student> students = studentService.queryAll();
System.out.println(students);
运行结果: