SSM整合全过程【多代码多图警告】

5 篇文章 0 订阅
5 篇文章 0 订阅

一、单独配置Spring并运行测试

1.导入依赖

测试依赖:

		<!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
        <!--spring test-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>

SpringIOC容器依赖:

		<!--spring ioc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <!--spring 事务管理-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>

Spring AOP依赖:

		<!--spring 第三方aop-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>
        <!--spring aop-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>

Spring-jdbc依赖:

        <!--spring jdbc模板-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>

2.创建Spring配置文件

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

    <!--开启spring 注解扫描-->
    <context:component-scan base-package="com.ps.ssm.service"></context:component-scan>

    <!--开启aop自动代理-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

    <!--开启事务注解支持-->
    <tx:annotation-driven></tx:annotation-driven>

</beans>

至于那些连接数据库相关的,我们等到配置Mybatis的时候一起配置

3.创建最简单的业务逻辑代码

实体类:

package com.ps.ssm.pojo;

public class Account {
    private int id;
    private int uid;
    private double money;

    public Account() {
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + money +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    public Account(int id, int uid, double money) {
        this.id = id;
        this.uid = uid;
        this.money = money;
    }
}

数据访问层:

public interface AccountDao {
    
    List<Account> findAll();
    
    int save(Account account);
}

业务层:

public interface AccountService {
    List<Account> findAll();
     void save(Account account) ;
}

@Service
public class AccountServiceImpl implements AccountService {
    
    private AccountDao accountDao;

    public List<Account> findAll() {
        System.out.println("find account finished!");
        return null;
    }
    
	@Transactional
    public void save(Account account) {
        System.out.println("保存账户成功!");
    }
}

4. 测试搭建是否成功

测试代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestAccountService {

    @Autowired
    private AccountService accountService;

    @Test
    public void testFind() {
        List<Account> all = accountService.findAll();
    }
}

测试结果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yxSbO6oh-1603445288331)(img/image-20201023163355269.png)]

由于我的是已经搭建好的,所以会有其他的输出,你只需要看到有这行输出即可

二、单独配置SpringMVC并运行测试

1.导入依赖

SpringMVC依赖:

        <!--spring mvc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>

servlet API:

        <!--
		这个的话版本随便导入,因为只是在编译的时候用一下,运行的时候会使用tomcat中的,如果害怕依赖冲突可以在下面加上<scope>provided</scope> 保证部署到tomcat运行时不会发生冲突
		servlet api-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>

json转换工具:

        <!--jackson
		这个版本的话可以根据自己的来,但是要保证高于2.9.0不然很大概率会报错
		-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>

2.创建配置文件

配置web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

    <!--配置前端控制器-->
    <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: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:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--开启注解扫描-->
    <context:component-scan base-package="com.ps.ssm.controller"></context:component-scan>
    <!--放开静态资源-->
    <mvc:default-servlet-handler/>
    <!--开启注解驱动,创建控制器适配器和控制器映射器-->
    <mvc:annotation-driven/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".html"></property>
    </bean>

</beans>

3.创建相关类和静态资源

创建控制器:

@Controller
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/find")
    public String find() {
        return "list";
    }
}

创建要跳转的页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
list html

<h1>账号列表</h1>

</body>
</html>

初始访问页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
index html
</body>
</html>

4.部署并测试

部署到tomcat:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9jJM2Rkj-1603445288334)(img/image-20201023164840015.png)]

访问find:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lzLZTEjo-1603445288336)(img/image-20201023164925387.png)]

三、单独配置Mybatis并运行测试

1.导入依赖

mybatis依赖:

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.0</version>
        </dependency>

数据库驱动和连接池:

        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <!--数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.18</version>
        </dependency>

2.创建配置文件

jdbc配置文件:

mysql.driver:com.mysql.jdbc.Driver
mysql.url:jdbc:mysql://localhost:3306/javaclass
mysql.username:root
mysql.password:123456

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"></properties>
    
    <!--给类或包下面的类起别名,目标:在接口映射文件中只需要写类名就可以-->
    <typeAliases>
        <package name="com.ps.ssm.pojo"/>
    </typeAliases>

    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="pooled">
                <property name="driver" value="${mysql.driver}"/>
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>

    </environments>

    <!--加载接口映射文件-->
    <mappers>
        <!--加载指定包下所有的接口映射文件-->
        <package name="com.ps.ssm.dao"/>
    </mappers>

</configuration>

3.修改数据访问层,获取数据

public interface AccountDao {

    @Select("select * from account")
    List<Account> findAll();

    int save(Account account);
}

4.编写测试代码测试结果

测试代码:

package com.ps.ssm.dao;

import com.ps.ssm.pojo.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestAccountDao {

    @Test
    public void testFindAll() throws IOException {
        //1.创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //2.读取配置配置文件
        InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
        //3.创建 SqlSessionFactory对象
        SqlSessionFactory sessionFactory = sqlSessionFactoryBuilder.build(in);
        //4.打开链接
        SqlSession sqlSession = sessionFactory.openSession();
        //5.获得映射对象
        AccountDao mapper = sqlSession.getMapper(AccountDao.class);
        //6.调用接口方法
        List<Account> all = mapper.findAll();
        for (Account account : all) {
            System.out.println(account);
        }
        //7.关闭连接
        sqlSession.close();
    }
}

测试结果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kqmJ8pZB-1603445288337)(img/image-20201023165518851.png)]

四、Spring和SpringMVC整合并测试运行

概述:

由于Spring和SpringMVC都是同一个包下的框架,所以他们可以无缝集成,也就是稍微配置一下就可以了;

修改web.xml配置

修改这里的配置是为了让服务器运行的时候可以加载Spring的配置文件,这样就可以把Spring的IOC和AOP都激活了;

    <!--配置加载Spring配置文件,也就是在tomcat启动的时候加载Spring配置文件-->
    <listener>
        <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
public class AccountController {

    //前面我在业务层实体类上添加了@Service注解,所以这里可以直接获取
    @Autowired
    private AccountServiceImpl accountService;

    @RequestMapping("/find")
    public String find() {
        List<Account> all = accountService.findAll();
        return "list";
    }
}

运行tomcat测试结果:

在这里插入图片描述

以上这就是Spring和SpringMVC的整合

五、Spring和Mybatis整合并测试运行

1.导入依赖

        <!--spring 整个mybatis需要导入的依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>

这个依赖必须导入,并且这个是由mybatis提供的,如果想进一步了解如何配置的可以取它的官网寻找答案

2.修改Spring中的配置文件

添加数据源,即配置数据库相关

   <!--配置事务管理器-->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置DataSource-->
    <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
        <property name="driverClassName" value="${mysql.driver}"></property>
        <property name="url" value="${mysql.url}"></property>
        <property name="username" value="${mysql.username}"></property>
        <property name="password" value="${mysql.password}"></property>
    </bean>

    <!--加载外部属性文件,即加载外部的数据库驱动文件-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

把Mybatis交由Spring处理,即由Spring创建Mybatis的相关内容:

    <!--配置会话工厂对象,负责创建SqlSessionFactory-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!--给指定包下的类取别名-->
        <property name="typeAliasesPackage" value="com.ps.ssm.pojo"></property>
        <!--配置接口映射文件的位置-->
        <!--        <property name="mapperLocations" value="classpath:com/ps/ssm/dao/*Mapper.xml"></property>-->
        <!--配置mybatis主配置文件位置-->
        <!--<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>-->
    </bean>

    <!--配置代理对象,这个代理对象负责创建接口的代理对象,也就是帮我们创建持久层的代理对象
    也可以称为:接口扫描器对象,扫描接口创建接口的实现类对象,而这个实现类对象是代理对象
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
        <!--配置要扫描那个包,那个包是需要帮助创建代理对象的包-->
        <property name="basePackage" value="com.ps.ssm.dao  "></property>
    </bean>

配置完上面这两个,就不需要mybatis的配置文件了,因为那个配置文件中的内容这里都包含了

3.修改业务层代码

即给业务层添加自动注入

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    public List<Account> findAll() {
        System.out.println("find account finished!");
        return accountDao.findAll();
    }

    @Transactional
    public void save(Account account) {
        System.out.println("保存账户成功!");
    }
}

这样配置之后,业务层就可以从Spring的IOC容器中获得Mybatis的相关代理对象,也就是Spring和Mybatis集成完成

4.编写测试代码,测试结果

测试代码:

package com.ps.ssm.service;

import com.ps.ssm.pojo.Account;
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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestAccountService {

    @Autowired
    private AccountService accountService;

    @Test
    public void testFind() {
        List<Account> all = accountService.findAll();
        for (Account account : all) {
            System.out.println(account);
        }
    }

}

测试结果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1n9wjg9H-1603445288340)(img/image-20201023172022463.png)]

经过上面的配置,其实已经算的SSM完全集成了,那么接下来就要整体测试一下了:

5.SSM整体测试

修改控制器,设置控制器返回json:

package com.ps.ssm.controller;

import com.ps.ssm.pojo.Account;
import com.ps.ssm.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/find")
    @ResponseBody
    public List<Account> find() {
        return accountService.findAll();
    }
}

修改前端页面,发起Ajax异步请求获取json字符串:
注意,我在这里使用的是jquery3.3.1发送的ajax异步请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
list html

<h1>账号列表</h1>

<button onclick="getData()">加载数据</button>

<table id="account_table">
    <tr>
        <th>账号</th>
        <th>编号</th>
        <th>金额</th>
    </tr>
</table>

<script src="js/jquery-3.3.1.min.js"></script>
<script>

    //加载数据
    function getData() {
        $.get({
            url: "find",//url地址
            dataType: "json",//返回的数据格式
            success: function (list) {//成功回调
                var tds = "    <tr>\n" +
                    "        <th>账号</th>\n" +
                    "        <th>编号</th>\n" +
                    "        <th>金额</th>\n" +
                    "    </tr>";
                $(list).each(function (index, account) {//遍历返回的json对象
                    tds += "<tr>\n" +
                        "    <td>" + account.id + "</td>\n" +
                        "    <td>" + account.uid + "</td>\n" +
                        "    <td>" + account.money + "</td>\n" +
                        "</tr>";
                });
                $("#account_table").html(tds);//把拼接好的结果添加到表格中
            },
            error: function () {
                alert("没有获取到数据");
            }
        });
    }
</script>

</body>
</html>

测试前页面效果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KZ2tfuZG-1603445288341)(img/image-20201023172621257.png)]

点击按钮后:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7SZ17pcW-1603445288342)(img/image-20201023172655085.png)]

好的,整合结束!

SSM整合指的是SpringSpringMVCMyBatis三个框架的整合。而多对多查询是指关系型数据库中多个表之间存在多对多的关系,需要通过中间表来建立关联。下面是一个基于SSM整合的多对多查询的例子: 假设我们有两个表:学生表(student)和课程表(course),它们之间存在多对多的关系,需要通过中间表(student_course)来建立关联。我们可以通过以下步骤实现多对多查询: 1. 在MyBatis的映射文件中定义两个查询语句,一个用于查询学生信息,一个用于查询课程信息: ``` <!-- 查询学生信息 --> <select id="getStudentById" parameterType="int" resultType="Student"> select * from student where id = #{id} </select> <!-- 查询课程信息 --> <select id="getCourseById" parameterType="int" resultType="Course"> select * from course where id = #{id} </select> ``` 2. 在MyBatis的映射文件中定义一个查询语句,用于查询学生所选的所有课程: ``` <!-- 查询学生所选的所有课程 --> <select id="getCoursesByStudentId" parameterType="int" resultType="Course"> select c.* from course c, student_course sc where c.id = sc.course_id and sc.student_id = #{studentId} </select> ``` 3. 在SpringMVC中定义一个Controller,用于接收前端请求,调用Service层中的方法,查询学生信息、课程信息以及学生所选的所有课程信息: ``` @Controller @RequestMapping("/student") public class StudentController { @Autowired private StudentService studentService; @Autowired private CourseService courseService; @RequestMapping("/{id}") public ModelAndView getStudentCourses(@PathVariable("id") int studentId) { // 查询学生信息 Student student = studentService.getStudentById(studentId); // 查询学生所选的所有课程信息 List<Course> courses = courseService.getCoursesByStudentId(studentId); // 查询每个课程的详细信息 for (Course course : courses) { course = courseService.getCourseById(course.getId()); } // 返回结果 ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("student", student); modelAndView.addObject("courses", courses); modelAndView.setViewName("student_courses"); return modelAndView; } } ``` 4. 在前端页面中展示查询结果。 以上就是一个基于SSM整合的多对多查询的例子。注意,这只是一种示例,具体实现方式可能因为业务需求而有所不同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值