使用SSM框架整合完成对数据库表的增删改查操作。
- 准备数据库和表
- 创建web项目
- 编写mybatis在ssm环境中单独使用
- 编写spring在ssm环境汇总单独使用
- spring整合mybatis
- 编写springmvc在ssm环境中可以单独使用
- spring整合springmvc
- Spring声明式事务配置
编写mybatis在ssm环境中单独使用
基于mybatis先来实现对数据表的查询
- 引入mybatis的相关依赖
<dependencies>
<!-- 引入mysql数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- 引入druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<!-- 引入mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!-- 引入junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
- 创建pojo层的类
public class Account {
private Integer id;
private String name;
private Double money;
- 创建DAO层接口类
public interface AccountDao {
/**
* 查询所有账户
*/
List<Account> findAll();
}
- 在
resources
中创建mapper配置文件:com.prim.dao.AccountDao.xml
注意必须和dao层的接口全类名相同
<?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.prim.dao.AccountDao">
<select id="findAll" resultType="com.prim.domain.Account">
select * from account
</select>
</mapper>
- 配置mybatis核心配置文件: 在
resources
目录下新建SqlMapConfig.xml
mybatis的核心配置文件
<?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>
<!-- 数据库properties -->
<properties resource="jdbc.properties"/>
<!-- 配置POJO类别名 -->
<typeAliases>
<package name="com.prim.domain"/>
</typeAliases>
<!-- 开发环境-数据源信息配置 -->
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 配置映射文件 -->
<mappers>
<package name="com.prim.dao"/>
</mappers>
</configuration>
在resources
目录下新建jdbc.properties
配置数据库信息
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/spring_db?characterEncoding=UTF-8
jdbc.username = root
jdbc.password = 123456
- 编写测试类,测试数据库连接是否成功,能否查询到数据表信息
public class MyBatisTest {
@Test
public void test() throws IOException {
InputStream stream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(stream);
SqlSession sqlSession = sessionFactory.openSession();
AccountDao mapper = sqlSession.getMapper(AccountDao.class);
List<Account> accounts = mapper.findAll();
System.out.println(accounts);
}
}
输出结果:如果能查询到数据表信息则说明mybatis编程环境配置成功了。
[Account{id=1, name='tom', money=100.0}, Account{id=2, name='jerry', money=1900.0}, Account{id=3, name='prim', money=1000.0}, Account{id=4, name='prim', money=1000.0}]
编写spring在ssm环境汇总单独使用
- 配置spring的相关坐标
<!-- spring核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- AOP 规范依赖 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<!-- spring jdbc template 可以代替DbUtils -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- spring tx 事务管理 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- spring test和Junit整合 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
- 业务层的编写:
AccountService
@Service
public class AccountServiceImpl implements AccountService {
@Override
public List<Account> findAll() {
System.out.println("findAll执行了");
return null;
}
}
- 编写spring核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<!-- IOC 注解扫描开启-->
<context:component-scan base-package="com.prim.service"/>
</beans>
- 测试spring配置是否正确
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class SpringTest {
@Autowired
private AccountService accountService;
@Test
public void test() {
accountService.findAll();
}
}
输出结果:findAll执行了 表示spring配置成功
spring整合mybatis
在上述中,我们知道Mybatis的创建的过程,来看下面的代码:
InputStream stream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(stream);
SqlSession sqlSession = sessionFactory.openSession();
AccountDao mapper = sqlSession.getMapper(AccountDao.class);
List<Account> accounts = mapper.findAll();
System.out.println(accounts);
Mybaits代理了AccountDao的接口,是通过sqlSession进行代理的,也就是说如果要在service注入dao层的实例,那么dao层的接口要交给spring进行代理创建,我们才能通过IOC将dao层的实例注入到service层代码中。
- 需要引入spring整合mybatis的依赖包
<!-- mybatis 整合spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
Spring 核心配置文件管理myBatis,将mybatis的配置文件删除。
<!-- 整合mybatis --> <!-- 引入jdbc.properties 引入外部的properties文件需要使用 context:property-placeholder --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 把sqlSessionFactory的创建权交给了spring,帮助我们生产sqlSession对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- POJO别名设置 --> <property name="typeAliasesPackage" value="com.prim.domain"/> <!-- 引入加载myBatis的核心配置文件,也可以不用去加载的 --> <!-- <property name="configLocation" value="classpath:SqlMapConfig.xml"/> --> </bean> <!-- mapper映射扫描,对mapper接口扫描,并且生产代理对象,存储到IOC容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.prim.dao"/> </bean>
Service层注入DAO层的实例
@Service public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; @Override public List<Account> findAll() { System.out.println("findAll执行了"); return accountDao.findAll(); } }
测试spring整合mybatis是否成功
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:applicationContext.xml"}) public class SpringTest { @Autowired private AccountService accountService; @Test public void test() { List<Account> accounts = accountService.findAll(); System.out.println(accounts); } }
打印结果:
[Account{id=1, name='tom', money=100.0}, Account{id=2, name='jerry', money=1900.0}, Account{id=3, name='prim', money=1000.0}, Account{id=4, name='prim', money=1000.0}]
编写springmvc在ssm环境中可以单独使用
实现:Controller中的方法可以查询到所有数据表信息
引入Spring MVC相关的依赖
<!-- 引入spring MVC 相关的依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency>
导入页面资源,配置前端控制器
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 服务器启动时,加载springMVC核心配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 中文乱码过滤器 --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
controller层编写和jsp文件
@Controller public class AccountController { @RequestMapping("/findAll") public String findAll(Model model) { Account account = new Account(); account.setId(1); account.setName("张飞"); account.setMoney(1000d); Account account2 = new Account(); account2.setId(1); account2.setName("刘备"); account2.setMoney(1000d); List<Account> accounts = new ArrayList<>(); accounts.add(account); accounts.add(account2); model.addAttribute("list", accounts); return "list"; } }
spring mvc 核心配置文件配置
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- IOC 扫描注解 --> <context:component-scan base-package="com.prim.controller"/> <!-- 配置处理映射器和处理适配器 mvc注解增强:支持json 读写 --> <mvc:annotation-driven/> <!-- 配置视图解析器 --> <bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 放行静态资源 --> <mvc:default-servlet-handler/> </beans>
spring整合springmvc
Spring和Spring MVC 根本不用整合,本来就是一家人。我们只需要spring和web容器整合,让web容器启动的时候去自动加载spring核心配置文件
applicationContext.xml
,web容器销毁,spring IOC 容器也需要销毁。
在web.xml中配置监听器ContextLoaderListener
监听器会在web容器启动的时候,去自动加载spring核心配置文件
<listener>
<!-- ContextLoaderListener 监听器会在web容器启动的时候,去自动加载spring核心配置文件 -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 全局参数 指定spring核心配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
Controller层的代码就可以注入Service层的实例了。
@Controller
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(Model model) {
List<Account> list = accountService.findAll();
model.addAttribute("list", list);
return "list";
}
}
Spring 配置声明式事务
<!-- spring 声明式事务 -->
<!-- 配置事务管理器 必须要配置的-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源对象注入 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 注解方式控制事务 -->
<tx:annotation-driven/>
对AccountServiceImpl的类添加事务注解,对所有方法进行事务支持
@Service
@Transactional
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
System.out.println("findAll执行了");
return accountDao.findAll();
}
@Override
public void save(Account account) {
accountDao.save(account);
}
}