Spring整合MyBatis
SSM简介及整合思路
SSM简介
(上图来自百度图片)
SSM全称Spring+SpringMVC+MyBatis,是目前比较主流的Java EE企业级框架,适用于搭建各种大型的企业级应用系统
SSM框架中:
Spring:是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。
SpringMVC:Spring MVC属于Spring Framework的后续产品,已经融合在Spring Web Flow里面,它原生支持的Spring特性,让开发变得非常简单规范。Spring MVC分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。
MyBatis:是一个基于Java的持久层框架,使用简单的XML或注解用于配置,将接口和Java的POJOs(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
整合思路
通过上图我们可以看出,spring将各层进行整合,类似于一个大管家,将MyBatis和SpringMVC揉合在一起:
通过spring管理持久层的mapper(相当于dao接口),使用mapper的扫描器自动扫描mapper接口在spring中进行注册;
通常由Spring来管理service接口,使用xml配置的方式来将service接口配置到spring配置文件中;另外,事务控制一般也是在service层进行配置;
Controller层由SpringMVC来控制,而SpringMVC是Spring的一个模块,所以不需要整合
准备测试数据
SET FOREIGN_KEY_CHECKS=0; DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(20) NOT NULL COMMENT '用户名', `password` varchar(255) NOT NULL COMMENT '密码', `real_name` varchar(255) NOT NULL COMMENT '真实名', `sex` varchar(255) DEFAULT NULL COMMENT '性别', `birthday` date DEFAULT NULL COMMENT '生日', `phone` varchar(255) NOT NULL COMMENT '电话', `utype` tinyint(1) DEFAULT NULL COMMENT '用户类型', `addtime` datetime DEFAULT NULL COMMENT '添加时间', `adduser` varchar(255) DEFAULT NULL COMMENT '添加者', PRIMARY KEY (`id`), UNIQUE KEY `phone` (`phone`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `user` values(1,'qzcsbj1','62f7f5673e94eca261b8fce7ae7863a4','qzcsbj1','男','2018-09-06','13800000001',0,now(),'qzcsbj'); insert into `user` values(2,'qzcsbj2','62f7f5673e94eca261b8fce7ae7863a4','qzcsbj2','女','2018-09-07','13800000002',1,now(),'qzcsbj'); insert into `user` values(3,'qzcsbj3','62f7f5673e94eca261b8fce7ae7863a4','qzcsbj3','男','2018-09-08','13800000003',0,now(),'qzcsbj'); insert into `user` values(4,'qzcsbj4','62f7f5673e94eca261b8fce7ae7863a4','qzcsbj4','女','2018-09-09','13800000004',1,now(),'qzcsbj'); insert into `user` values(5,'qzcsbj5','62f7f5673e94eca261b8fce7ae7863a4','qzcsbj5','女','2018-09-10','13800000005',0,now(),'qzcsbj');
创建实体类
创建实体类的包
连接数据库
逆向生成
实体类
package com.qzcsbj.bean; import java.util.Date; /** * @公众号 : 全栈测试笔记 * @博客 : www.cnblogs.com/uncleyong * @微信 : ren168632201 * @描述 : <> */ public class User { private Integer id; private String username; private String password; private String realName; private String sex; private Date birthday; private String phone; private String utype; private String addtime; private String adduser; public User() { } public User(String username, String password, String realName, String sex, Date birthday, String phone, String utype,String adduser, String addtime) { this.username = username; this.password = password; this.realName = realName; this.sex = sex; this.birthday = birthday; this.phone = phone; this.utype = utype; this.adduser = adduser; this.addtime = addtime; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getUtype() { return utype; } public void setUtype(String utype) { this.utype = utype; } public String getAddtime() { return addtime; } public void setAddtime(String addtime) { this.addtime = addtime; } public String getAdduser() { return adduser; } public void setAdduser(String adduser) { this.adduser = adduser; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", realName='" + realName + '\'' + ", sex='" + sex + '\'' + ", birthday=" + birthday + ", phone='" + phone + '\'' + ", utype='" + utype + '\'' + ", addtime=" + addtime + ", adduser='" + adduser + '\'' + '}'; } }
pom依赖
<?xml version="1.0" encoding="UTF-8"?> <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.0</modelVersion> <groupId>com.qzcsbj.spring-mybatis</groupId> <artifactId>spring-mybatis</artifactId> <version>1.0-SNAPSHOT</version> <!--集中定义版本号--> <properties> <spring.version>4.3.14.RELEASE</spring.version> <mybatis.version>3.4.6</mybatis.version> <mybatis.spring.version>1.3.1</mybatis.spring.version> <mysql.version>5.1.47</mysql.version> <druid.version>1.1.10</druid.version> <junit.version>4.12</junit.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <!-- spring需要的jar包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!--<dependency>--> <!--<groupId>org.springframework</groupId>--> <!--<artifactId>spring-context-support</artifactId>--> <!--<version>${spring.version}</version>--> <!--</dependency>--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> </dependency> <!--Spring测试模块--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!--aop相关--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <!-- Mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!--Spring和MyBatis整合包--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!--spring-jdbc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!-- MySql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!--阿里的数据库连接池工具包--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!--单元测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!--日志--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build> </project>
添加
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://192.168.117.180:3306/gift?useUnicode=true&characterEncoding=utf-8&useSSL=true jdbc.username=root jdbc.password=qzcsbj
### 根logger 设置### log4j.rootLogger = INFO,console log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern = %d{**:mm:ss SSS} [%t] %-5p method: %l----%m%n log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
package com.qzcsbj.mapper; import com.qzcsbj.bean.User; import java.util.List; /** * @公众号 : 全栈测试笔记 * @博客 : www.cnblogs.com/uncleyong * @微信 : ren168632201 * @描述 : <> */ public interface UserMapper { public List<User> getUsers(); }
<?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.qzcsbj.mapper.UserMapper"> <select id="getUsers" resultType="com.qzcsbj.bean.User"> select * from user </select> </mapper>
package com.qzcsbj.service; import com.qzcsbj.bean.User; import java.util.List; /** * @公众号 : 全栈测试笔记 * @博客 : www.cnblogs.com/uncleyong * @微信 : ren168632201 * @描述 : <> */ public interface UserService { public List<User> getUsers(); }
package com.qzcsbj.service.impl; import com.qzcsbj.bean.User; import com.qzcsbj.mapper.UserMapper; import com.qzcsbj.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @公众号 : 全栈测试笔记 * @博客 : www.cnblogs.com/uncleyong * @微信 : ren168632201 * @描述 : <> */ @Service public class UserServiceImlp implements UserService { @Autowired UserMapper userMapper; public List<User> getUsers() { return userMapper.getUsers(); } }
<?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" 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"> <!--Spring扫描程序中的包--> <context:component-scan base-package="com.qzcsbj.*"/> <!--加载数据库属性文件--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--配置数据源--> <bean id="ds" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="url" value="${jdbc.url}"/> </bean> <!--配置MyBatis的sqlSession工厂SqlSessionFactory(Spring框架管理了session,所以也不需要mybatis工具类了)--> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--指定数据库连接对象dataSource--> <property name="dataSource" ref="ds"/> <!--指定Mapper的映射文件位置--> <property name="mapperLocations" value="classpath:com/qzcsbj/mapper/*.xml"/> <!--指定实体类的别名--> <property name="typeAliasesPackage" value="com.qzcsbj.bean"/> </bean> <!--Spring框架扫描Mapper层接口,自动给Mapper层接口生成代理对象--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.qzcsbj.mapper"/> </bean> </beans>
package com.qzcsbj.test; import com.qzcsbj.bean.User; import com.qzcsbj.service.UserService; 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; import java.util.List; /** * @公众号 : 全栈测试笔记 * @博客 : www.cnblogs.com/uncleyong * @微信 : ren168632201 * @描述 : <> */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class TestSpringMyBatis { @Autowired UserService userService; @Test public void test(){ List<User> users = userService.getUsers(); for (User user : users) { System.out.println(user); } } }
结果,成功查询到数据
原文会持续更新,原文地址:https://www.cnblogs.com/uncleyong/p/17026215.html
__EOF__
本文作者:持之以恒(韧)
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevTestOps)、测开等
面试必备:项目实战(性能、自动化)、简历笔试,https://www.cnblogs.com/uncleyong/p/15777706.html
测试提升:从测试小白到高级测试修炼之路,https://www.cnblogs.com/uncleyong/p/10530261.html
欢迎分享:如果您觉得文章对您有帮助,欢迎转载、分享,也可以点击文章右下角【推荐】一下!
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevTestOps)、测开等
面试必备:项目实战(性能、自动化)、简历笔试,https://www.cnblogs.com/uncleyong/p/15777706.html
测试提升:从测试小白到高级测试修炼之路,https://www.cnblogs.com/uncleyong/p/10530261.html
欢迎分享:如果您觉得文章对您有帮助,欢迎转载、分享,也可以点击文章右下角【推荐】一下!