写点什么

Spring+SpringMVC+Mybatis 框架整合(SSM 整合)

作者:Java高工P7
  • 2021 年 11 月 11 日
  • 本文字数:5976 字

    阅读完需:约 20 分钟

<artifactId>c3p0</artifactId>


<version>0.9.1.2</version>


<type>jar</type>


<scope>compile</scope>


</dependency>


</dependencies>


<build>


<finalName>day03_SSM</finalName>


<plugins>


<plugin>


<artifactId>maven-clean-plugin</artifactId>


<version>3.1.0</version>


</plugin>


<plugin>


<artifactId>maven-resources-plugin</artifactId>


<version>3.0.2</version>


</plugin>


<plugin>


<artifactId>maven-compiler-plugin</artifactId>


<version>3.8.0</version>


</plugin>


<plugin>


<artifactId>maven-surefire-plugin</artifactId>


<version>2.22.1</version>


</plugin>


<plugin>


<artifactId>maven-war-plugin</artifactId>


<version>3.2.2</version>


</plugin>


<plugin>


<artifactId>maven-install-plugin</artifactId>


<version>2.5.2</version>


</plugin>


<plugin>


<artifactId>maven-deploy-plugin</artifactId>


<version>2.8.2</version>


</plugin>


</plugins>


</pluginManagement>


</build>


</project>


4.项目结构搭建:



编写 Account 实体类


/**


  • @Author: Ly

  • @Date: 2020-09-29 21:14


*/


public class Account implements Serializable {


private Integer id;


private String name;


private Double money;


public Integer getId() {


return id;


}


public void setId(Integer id) {


this.id = id;


}


public String getName() {


return name;


}


public void setName(String name) {


this.name = name;


}


public Double getMoney() {


return money;


}


public void setMoney(Double money) {


this.money = money;


}


@Override


public String toString() {


return "Account{" +


"id=" + id +


", name='" + name + ''' +


", money=" + money +


'}';


}


}


编写业务层接口


/**


  • @Author: Ly

  • @Date: 2020-09-29 21:18


*/


public interface AccountService {


//查询所有账户


public List<Account> findAll();


//保存账户信息


public void saveAccount(Account account);


}


整合 Spring 与 SpringMVC




测试 Spring 框架在 web 工程中独立运行


第一步:编写 spring 配置文件并导入约束 applicationContext.xml


<?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:aop="http://www.springframework.org/schema/aop"


xmlns:tx="http://www.springframework.org/schema/tx"


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/tx


http://www.springframework.org/schema/tx/spring-tx.xsd


http://www.springframework.org/schema/aop


http://www.springframework.org/schema/aop/spring-aop.xsd


http://www.springframework.org/schema/context


http://www.springframework.org/schema/context/spring-context.xsd">


<context:component-scan base-package="com.ly">


<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>


</context:component-scan>


</beans>


第二步:使用注解配置业务层


/**


  • @Author: Ly

  • @Date: 2020-09-29 21:19


*/


@Service("accountService")


public class AccountServiceImpl implements AccountService {


@Override


public List<Account> findAll() {


System.out.println("业务层:查询所有账户");


return null;


}


@Override


public void saveAccount(Account account) {


System.out.println("业务层:保存账户");


}


}


第三步:测试 Spring


/**


  • @Author: Ly

  • @Date: 2020-09-29 21:33


*/


public class TestSpring {


@Test


public void run1(){


//加载配置文件 applicationContext.xml


ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");


//获取对象


AccountService as=(AccountService)ac.getBean("accountService");


//调用方法


as.findAll();


}


}


测试 SpringMVC 在 web 工程中独立运行


第一步:在 web.xml 中配置核心控制器(DispatcherServlet)


<!DOCTYPE web-app PUBLIC


"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"


"http://java.sun.com/dtd/web-app_2_3.dtd" >


<web-app>


<display-name>Archetype Created Web Application</display-name>


<servlet>


<servlet-name>dispatcherServlet</servlet-name>


<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>


<init-param>


<param-name>contextConfigLocation</param-name>


<param-value>classpath:springmvc.xml</param-value>


</init-param>


<load-on-startup>1</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>


第二步:编写 SpringMVC 的配置文件


<?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">


<context:component-scan base-package="com.ly">


<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />


</context:component-scan>


<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">


<property name="prefix" value="/WEB-INF/pages/"></property>


<property name="suffix" value=".jsp"></property>


</bean>


<mvc:resources mapping="/css/**" location="/css/"/>


<mvc:resources mapping="/images/**" location="/images/"/>


<mvc:resources mapping="/js/**" location="/js/"/>


mvc:annotation-driven</mvc:annotation-driven>


</beans>


第三步:编写控制器代码:


/**


  • @Author: Ly

  • @Date: 2020-09-29 21:21


*/


@Controller


@RequestMapping("/account")


public class AccountController {


@RequestMapping("/findAll")


public String findAll(){


System.out.println("表现层:查询所有账户信息");


return "list";


}


}


第四步:新建 jsp 页面测试代码


<%@ page contentType="text/html;charset=UTF-8" language="java" %>


<html>


<head>


<title>Title</title>


</head>


<body>


<a href="account/findAll">测试</a>


</body>


</html>


成功后的跳转界面


<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>


<html>


<head>


<title>Title</title>


</head>


<body>


<h3>查询了所有账户信息</h3>


</body>


</html>


整合 Spring 和 SpringMVC


第一步:在 web.xml 中配置监听器实现启动服务创建容器


配置 spring 提供的监听器,用于启动服务时加载容器 。该间监听器只能加载 WEB-INF 目录中名称为 applicationContext.xml 的配置文件 ,这样在 tomcat 服务器启动时,就会加载 spring 的配置文件了。


<listener>


<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>


</listener>


<context-param>


<param-name>contextConfigLocation</param-name>


<param-value>classpath:applicationContext.xml</param-value>


</context-param>


第二步:在控制器中实现依赖注入


@Autowired


private AccountService accountService;


@RequestMapping("/findAll")


public String findAll(Model model){


System.out.println("表现层:查询所有的信息");


//调用 service 方法


accountService.findAll();


return "list";


}


第三步:再次测试代码


整合 Spring 与 Mybatis




测试 MyBatis 框架在 web 工程中独立运行


第一步:编写 AccountDa


【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】
浏览器打开:qq.cn.hn/FTf 免费领取
复制代码


o 持久层接口,我们使用代理 dao 的方式来操作持久层,Dao 的实现类就是多余的。


/**


  • @Author: Ly

  • @Date: 2020-09-29 21:15

  • 账户 dao 接口


*/


//@Repository


public interface AccountDao {


//查询所有账户


@Select("select * from account")


public List<Account> findAll();


//保存账户信息


@Insert("insert into account (name,money) values(#{name},#{money})")


public void saveAccount(Account account);


}


第二步:编写 SqlMapConfig 配置文件


<?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>


<property name="driver" value="com.mysql.cj.jdbc.Driver"></property>


<property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8"></property>


<property name="username" value="root"></property>


<property name="password" value="123456"></property>


</properties>


<typeAliases>


<package name="com.ly.domain"/>


</typeAliases>


<environments default="mysql">


<environment id="mysql">


<transactionManager type="JDBC"/>


<dataSource type="POOLED">


<property name="driver" value="${driver}"></property>


<property name="url" value="${url}"></property>


<property name="username" value="${username}"></property>


<property name="password" value="${password}"></property>


</dataSource>


</environment>


</environments>


<mappers>


<package name="com.ly.dao"/>


</mappers>


</configuration>


第三步:测试运行结果


/**


  • @Author: Ly

  • @Date: 2020-09-30 09:12


*/


public class TestMybatis {


@Test


public void run1() throws Exception {


//加载 mybatis 配置文件


InputStream in=Resources.getResourceAsStream("SqlMapConfig.xml");


//创建 SqlSessionFactory 对象


SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);


//创建 SqlSession 对象


SqlSession session=factory.openSession();


//获取到代理对象


AccountDao dao=session.getMapper(AccountDao.class);


//查询所有数据


List<Account> list=dao.findAll();


for(Account account:list){


System.out.println(account);


}


//关闭资源


session.close();


in.close();


}


@Test


public void run2() throws Exception {


Account account=new Account();


account.setName("aas");


account.setMoney(2222d);


//加载 mybatis 配置文件


InputStream in=Resources.getResourceAsStream("SqlMapConfig.xml");


//创建 SqlSessionFactory 对象


SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);


//创建 SqlSession 对象


SqlSession session=factory.openSession();


//获取到代理对象


AccountDao dao=session.getMapper(AccountDao.class);


//保存数据


dao.saveAccount(account);


//提交事务


session.commit();


//关闭资源


session.close();


in.close();


}


}


整合 Spring 和 MyBatis


整合思路:把 mybatis 配置文件(SqlMapConfig.xml)中内容配置到 spring 配置文件中,同时把 mybatis 配置文件的内容清掉。


第一步:在 applicationContext.xml 中配置 mybatis 文件


① Spring 接管 MyBatis 的 Session 工厂


② 配置自动扫描所有 Mapper 接口和文件


③ 配置 spring 的事务


<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">


<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>


<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8"></property>


<property name="user" value="root"></property>


<property name="password" value="123456"></property>


</bean>


<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">


<property name="dataSource" ref="dataSource"></property>


</bean>


<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">


<property name="basePackage" value="com.ly.dao"></property>


</bean>


<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">


<property name="dataSource" ref="dataSource"></property>


</bean>


<tx:advice id="txAdvice" transaction-manager="transactionManager">


tx:attributes


<tx:method name="find*" read-only="true"/>


<tx:method name="*" isolation="DEFAULT"/>


</tx:attributes>


</tx:advice>


aop:config


<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.ly.service.impl.ServiceImpl.(..))"/>


</aop:config>


第二步:在 AccountDao 接口上添加 @Repository 注解,实现注入


第三部:修改 AccountServiceImpl 业务层实现类,实现注入


/**


  • @Author: Ly

  • @Date: 2020-09-29 21:19


*/


@Service("accountService")


public class AccountServiceImpl implements AccountService {


@Autowired


private AccountDao accountDao;


@Override


public List<Account> findAll() {


System.out.println("业务层:查询所有账户");


return accountDao.findAll();


}


@Override


public void saveAccount(Account account) {


System.out.println("业务层:保存账户");


accountDao.saveAccount(account);


}


}


第四步:改控制器中的方法


/**


  • @Author: Ly

  • @Date: 2020-09-29 21:21


*/


@Controller


@RequestMapping("/account")


public class AccountController {


@Autowired


private AccountService accountService;


@RequestMapping("/findAll")


public String findAll(Model model){


System.out.println("表现层:查询所有的信息");


//调用 service 方法


List<Account> list=accountService.findAll();


model.addAttribute("list",list);


return "list";

用户头像

Java高工P7

关注

还未添加个人签名 2021.11.08 加入

还未添加个人简介

评论

发布
暂无评论
Spring+SpringMVC+Mybatis框架整合(SSM整合)