案例介绍 使用spring整合mybatis技术,完成账户模块(Account)的基础增删改查功能
表结构如下
列名 类型 id int 主键、自增 name varchar(24) 姓名,字符串,最多24个字符 money double(10,2) 账户余额,最大值99999999.99。小数点前最多8位,小数点后最多2位。本案例使用double类型,实际开发中使用decimal(10,2)
XML方式整合 第一步 引入依赖 需要引入mysql,mybatis,spring,druid连接池,以及整合mybatis和spring的依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 <dependencies > <dependency > <groupId > org.projectlombok</groupId > <artifactId > lombok</artifactId > <version > 1.18.4</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-context</artifactId > <version > 5.0.5.RELEASE</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-test</artifactId > <version > 5.0.5.RELEASE</version > </dependency > <dependency > <groupId > org.aspectj</groupId > <artifactId > aspectjweaver</artifactId > <version > 1.8.13</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-tx</artifactId > <version > 5.0.5.RELEASE</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis</artifactId > <version > 3.5.3</version > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > 5.1.46</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-jdbc</artifactId > <version > 5.1.6.RELEASE</version > </dependency > <dependency > <groupId > com.alibaba</groupId > <artifactId > druid</artifactId > <version > 1.1.21</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis-spring</artifactId > <version > 1.3.0</version > </dependency > <dependency > <groupId > junit</groupId > <artifactId > junit</artifactId > <version > 4.12</version > <scope > test</scope > </dependency > </dependencies >
第二步 创建数据库 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 ; ; ; ; ; ; CREATE DATABASE `spring01` ;USE `spring01`; DROP TABLE IF EXISTS `account`;CREATE TABLE `account` ( `id` int (11 ) NOT NULL AUTO_INCREMENT, `name` varchar (24 ) DEFAULT NULL , `money` double (10 ,2 ) DEFAULT NULL , PRIMARY KEY (`id`) ) ENGINE= InnoDB AUTO_INCREMENT= 4 DEFAULT CHARSET= utf8; insert into `account`(`id`,`name`,`money`) values (1 ,'jack' ,1000.00 ),(2 ,'tom' ,1000.00 ),(3 ,'rose' ,1000.00 );; ; ; ;
第三步 创建dao\service\domain 创建实体类 Account
1 2 3 4 5 6 7 8 9 10 11 12 13 14 package cn.itcast.domain;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data @AllArgsConstructor @NoArgsConstructor public class Account { private Integer id; private String name; private Double money; }
创建 Dao
1 2 3 4 5 6 7 8 9 package cn.itcast.dao;import cn.itcast.domain.Account;import java.util.List;public interface AccountDao { List<Account> findAll () ; }
创建Service
1 2 3 4 5 6 7 8 9 package cn.itcast.service;import cn.itcast.domain.Account;import java.util.List;public interface AccountService { List<Account> findAll () ; }
创建Service实现类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package cn.itcast.service.impl;import cn.itcast.dao.AccountDao;import cn.itcast.domain.Account;import cn.itcast.service.AccountService;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import java.util.List;public class AccountServiceImpl implements AccountService { private AccountDao accountDao; public List<Account> findAll () { return accountDao.findAll(); } public AccountDao getAccountDao () { return accountDao; } public void setAccountDao (AccountDao accountDao) { this .accountDao = accountDao; } }
第四步 创建jdbc.properties 1 2 3 4 jdbc.driver =com.mysql.jdbc.Driver jdbc.url =jdbc:mysql://localhost:3306/spring01 jdbc.username =root jdbc.password =root
第五步 创建mapper映射文件 映射文件的编写必须遵循下面两个原则:
该映射文件必须和dao在相同的目录(包)下,比如接口在src/cn/itcast/dao目录下,那么配置文件也必须在resource/cn/itcast/dao目录下。 配置文件的名字和dao接口名保持一致,这里叫AccountDao.xml 。比如接口叫AccountDao.java,那么配置文件的名字必须叫AccountDao.xml 1 2 3 4 5 6 7 8 9 10 <?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.itcast.dao.AccountDao" > <select id ="findAll" resultType ="account" > select * from account </select > </mapper >
第六步 创建 spring主配置文件 主配置文件名叫applicationContext.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <?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 http://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" > </context:property-placeholder > <bean id ="ds" class ="com.alibaba.druid.pool.DruidDataSource" > <property name ="driverClassName" value ="${jdbc.driver}" > </property > <property name ="url" value ="${jdbc.url}" > </property > <property name ="username" value ="${jdbc.username}" > </property > <property name ="password" value ="${jdbc.password}" > </property > </bean > <bean class ="org.mybatis.spring.SqlSessionFactoryBean" > <property name ="dataSource" ref ="ds" > </property > <property name ="typeAliasesPackage" value ="cn.itcast.domain" > </property > </bean > <bean class ="org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name ="basePackage" value ="cn.itcast.dao" > </property > </bean > <bean class ="cn.itcast.service.impl.AccountServiceImpl" > <property name ="accountDao" ref ="accountDao" > </property > </bean > </beans >
第七步 创建测试类 1 2 3 4 5 6 7 8 public class App { public static void main (String[] args) { ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext ("applicationContext.xml" ); AccountService accountService = classPathXmlApplicationContext.getBean(AccountService.class); List<Account> all = accountService.findAll(); System.out.println(all); } }
注解方式整合 第一步 引入依赖 需要引入mysql,mybatis,spring,druid连接池,以及整合mybatis和spring的依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 <dependencies > <dependency > <groupId > org.projectlombok</groupId > <artifactId > lombok</artifactId > <version > 1.18.4</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-context</artifactId > <version > 5.0.5.RELEASE</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-test</artifactId > <version > 5.0.5.RELEASE</version > </dependency > <dependency > <groupId > org.aspectj</groupId > <artifactId > aspectjweaver</artifactId > <version > 1.8.13</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-tx</artifactId > <version > 5.0.5.RELEASE</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis</artifactId > <version > 3.5.3</version > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > 5.1.46</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-jdbc</artifactId > <version > 5.1.6.RELEASE</version > </dependency > <dependency > <groupId > com.alibaba</groupId > <artifactId > druid</artifactId > <version > 1.1.21</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis-spring</artifactId > <version > 1.3.0</version > </dependency > </dependencies >
第二步 创建数据库 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 /* SQLyog Ultimate v12.09 (64 bit) MySQL - 5.5.40 : Database - spring01 ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`spring01` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `spring01`; /*Table structure for table `account` */ DROP TABLE IF EXISTS `account`; CREATE TABLE `account` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(24) DEFAULT NULL, `money` double(10,2) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; /*Data for the table `account` */ insert into `account`(`id`,`name`,`money`) values (1,'jack',1000.00),(2,'tom',1000.00),(3,'rose',1000.00); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
第三步 创建dao\service\domain 创建实体类 Account
1 2 3 4 5 6 7 8 9 10 11 12 13 14 package cn.itcast.domain;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data @AllArgsConstructor @NoArgsConstructor public class Account { private Integer id; private String name; private Double money; }
创建 Dao
1 2 3 4 5 6 7 8 9 10 11 package cn.itcast.dao;import cn.itcast.domain.Account;import org.apache.ibatis.annotations.Select;import java.util.List;public interface AccountDao { @Select("select * from account") List<Account> findAll () ; }
创建Service
1 2 3 4 5 6 7 8 9 package cn.itcast.service; import cn.itcast.domain.Account; import java.util.List; public interface AccountService { List<Account> findAll() ; }
创建Service实现类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package cn.itcast.service.impl;import cn.itcast.dao.AccountDao;import cn.itcast.domain.Account;import cn.itcast.service.AccountService;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import java.util.List;public class AccountServiceImpl implements AccountService { private AccountDao accountDao; public List<Account> findAll () { return accountDao.findAll(); } public AccountDao getAccountDao () { return accountDao; } public void setAccountDao (AccountDao accountDao) { this .accountDao = accountDao; } }
第四步 创建jdbc.properties 1 2 3 4 jdbc.driver =com.mysql.jdbc.Driver jdbc.url =jdbc:mysql://localhost:3306/spring01 jdbc.username =root jdbc.password =root
第五步 创建数据库连接池的配置文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 package cn.itcast.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 javax.sql.DataSource;@Configuration @PropertySource("jdbc.properties") public class JdbcConfig { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean public DataSource getDataSource () { DruidDataSource druidDataSource = new DruidDataSource (); druidDataSource.setUsername(this .username); druidDataSource.setPassword(this .password); druidDataSource.setUrl(this .url); druidDataSource.setDriverClassName(this .driver); return druidDataSource; } }
第六步 创建整合MyBatis的配置文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 package cn.itcast.config;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.mapper.MapperScannerConfigurer;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;@Configuration public class MyBatisConfig { @Bean public SqlSessionFactoryBean getSqlSessionFactoryBean (@Autowired DataSource dataSource) { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean (); sqlSessionFactoryBean.setTypeAliasesPackage("cn.itcast.domain" ); sqlSessionFactoryBean.setDataSource(dataSource); return sqlSessionFactoryBean; } @Bean public MapperScannerConfigurer getMapperScannerConfigurer () { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer (); mapperScannerConfigurer.setBasePackage("cn.itcast.dao" ); return mapperScannerConfigurer; } }
第七步 创建主配置文件 1 2 3 4 5 6 7 8 9 10 11 package cn.itcast.config;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Import;@Configuration @ComponentScan("cn.itcast") @Import({JdbcConfig.class,MyBatisConfig.class}) public class AppConfig {}
第八步 配置Service层 自定义类,如果需要交由Spring管理,添加 @Component,@Controller,@Service,@Repository 等注解
本案例在Service的实现类上添加注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 package cn.itcast.service.impl;import cn.itcast.dao.AccountDao;import cn.itcast.domain.Account;import cn.itcast.service.AccountService;import lombok.Data;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Service("accountService") public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao ; public List<Account> findAll () { return accountDao.findAll(); } public void setAccountDao (AccountDao accountDao) { this .accountDao = accountDao; } }
第九步 编写测试类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import cn.itcast.config.AppConfig;import cn.itcast.domain.Account;import cn.itcast.service.AccountService;import org.junit.Test;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import java.util.List;public class AppTest { @Test public void findAll () { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext (AppConfig.class); AccountService accountService = applicationContext.getBean(AccountService.class); List<Account> all = accountService.findAll(); System.out.println(all); } }