手把手带初学者快速入门 JAVA Web SSM 框架

news2024/10/6 0:37:59

博主也是刚开始学习SSM,为了帮大家节省时间,写下SSM快速入门博客
有什么不对的地方还请 私信 或者 评论区 指出

​只是一个简单的整合项目,让初学者了解一下SSM的大致结构
项目先把框架写好,之后在填写内容

项目压缩包

完整的蓝奏压缩包在文末链接

目录

SSM整合原始方法
   数据库
   创建Maven项目
   先修改pox.xml

   项目结构创建
       编写逻辑结构
          创建实体类对应的Mapper接口
          创建业务层接口
          创建业务层的实现方法
          编写Web层Controller包
       编写添加页面和列表展示页面
          添加save页面
          添加accountList页面
       编写配置文件
          添加jdbc和log4j文件
          修改web.xml
          添加applicationContext.xml和spring-mvc.xml文件
          添加mapper配置文件
          添加mybatis配置文件

   项目内容填充
      填充mybatis配置文件
         修改sqlMapConfig.xml
         修改AccountMapper.xml
      填充Spring配置文件
         修改applicationContext.xml
         修改spring-mvc.xml
      填充web.xml配置文件
         修改web.xml
      编写逻辑代码
         修改AccountController类文件
         修改AccountServiceImpl类文件

   测试
       配置Tomcat
       运行
       测试添加方法
       测试查询方法

mybatis整合spring
    修改配置文件
       创建sqlMapConfig-spring.xml文件
          修改加载jdbc.properties文件的代码
          修改数据库环境的代码
          修改加载映射的代码
       配置sessionFactory
          修改AccountServiceImpl类
       声明式事务控制
    mybatis整合spring阶段修改后完整代码
    测试mybatis整合spring

SSM整合原始方法

数据库

就一个表

后面会放上DataGrip的SQL导出文件

表截图

创建Maven项目

image-20230125090907908

这里搜索会匹配对应的模板(选择路径尽量只使用英文和下划线,(中文路径如果出现问题,有的时候很难找到))

image-20230125112643895

先修改pox.xml

依赖加到对应位置,各个依赖的版本要根据当前tomcatjdk版本

Tips:tomcat10没有Javax包 要用jakarta包 tomcat9及以下要把jakarta换成javax

不知道怎么修改依赖看这里

依赖仓库(找到需要的依赖直接复制,防止自己写错)

    <dependencies>
        <!--spring相关-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.19</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>6.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>6.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>6.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>6.0.0</version>
        </dependency>

        <!--servlet和jsp-->
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.0.0</version>
            <scope>provided</scope>
        </dependency>


        <!-- https://mvnrepository.com/artifact/jakarta.servlet.jsp/jakarta.servlet.jsp-api -->
        <dependency>
            <groupId>jakarta.servlet.jsp</groupId>
            <artifactId>jakarta.servlet.jsp-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.glassfish.web/jakarta.servlet.jsp.jstl -->
        <!--    一定要重视scope,否则报错-->
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>jakarta.servlet.jsp.jstl</artifactId>
            <version>2.0.0</version>
            <scope>compile</scope>
        </dependency>

        <!--mybatis相关-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.11</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
            <!--     有的时候会出现找不到com.mysql.cj.jdbc.Driver 运行时不再与tomcat的lib冲突,在依赖项的范围我限制为provided-->
            <!--            <scope>provided</scope>-->
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

添加依赖后记得导入一下

两种导入方法是一样的,你修改pom后右上角会有个提示,点击右上角提示,或者 右键->选择Maven->Reload project 添加依赖

image-20230125164413882

项目结构创建

编写逻辑结构

如果Maven项目没有 蓝色Java包

image-20230125192705239

右键main -> New -> Directory -> 直接选择下面的那个Java蓝色包就可以

image-20230125192802335

image-20230125192908373

在Java包下面建好目录

image-20230125193206471

现在entity包下面建实体类(对应数据列的类)

image-20230125193401495

快速创建get() set() toString() 方法

下面附上实体类Account代码 (一定要把属性和数据库对应)

package org.example.entity;

public class Account {

    private Integer id;
    private String name;
    private Double money;

    public Integer getId() {
        return id;
    }

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

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

    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;
    }
}

创建实体类对应的Mapper接口

mapper包创建完接口,添加两个业务方法 添加用户查找所有用户

image-20230125194614560

mapper包下的AccountMapper接口

package org.example.mapper;

import org.example.entity.Account;

import java.util.List;

public interface AccountMapper {
    public void save(Account account);  //保存用户
    public List<Account> findAll();     //查找所有用户
}

创建业务层接口

和上面一样: 在service包创建完接口,添加两个业务方法 添加用户查找所有用户

image-20230125195029064

Service层接口AccountService代码

package org.example.service;

import org.example.entity.Account;

import java.util.List;

public interface AccountService {
    public void save(Account account);  //保存用户

    public List<Account> findAll();     //查找所有用户
}

创建业务层的实现方法

service包创建一个impl包 在这个包下面创建AccountServiceImpl类,实现AccountService接口 ,

实现两个方法 添加用户查找所有用户 (可以根据错误提示,鼠标对着报错位置点左上角小红灯泡或者快捷键Alt+Enter直接实现)

image-20230125200655273

选中需要实现的方法,点击OK

Service层实现类AccountServiceImpl代码

package org.example.service.impl;

import org.example.entity.Account;
import org.example.service.AccountService;

import java.util.List;

public class AccountServiceImpl implements AccountService {
    @Override
    public void save(Account account) {

    }

    @Override
    public List<Account> findAll() {
        return null;
    }
}

编写Web层Controller包

Controller包下面创建AccountController类 ,添加两个之前接口对应的方法(后面在填充内容)

image-20230125202400208

编写添加页面和列表展示页面

jsp 页面是固定的,这里就直接写好了

添加save页面

webapp文件夹下面创建添加页面save.jsp

webapp右键 -> New -> JSP/JSPX -> 名字为save,选择jsp即可

image-20230125203009958

image-20230125203152552

下面是save.jsp的代码

<%--
  Created by IntelliJ IDEA.
  User: 14397
  Date: 2023/1/25
  Time: 20:33
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>添加账户信息表单</h1>
<form name="accountForm" action="${pageContext.request.contextPath}/account/save" method="post">
    账户名称:<input type="text" name="name"><br>
    账户金额:<input type="text" name="money"><br>
    <input type="submit" value="保存"><br>
</form>
</body>
</html>

添加accountList页面

WEB-INF文件夹 下面创建 pages文件夹 ,里面创建 accountList.jsp (文件夹创建以后就pass了,只为了防止初学者不太熟悉IDEA)

Tips:引入taglib才能添加controller层传过来的数据

<%--
  Created by IntelliJ IDEA.
  User: 14397
  Date: 2023/1/25
  Time: 20:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--    下面这一行是从数据库向页面添加数据需要的内容--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>展示账户数据列表</h1>
<table border="1">
    <tr>
        <th>账户id</th>
        <th>账户名称</th>
        <th>账户金额</th>
    </tr>
    <%--        循环添加,从controller层传过来的数据--%>
    <c:forEach items="${accountList}" var="account">
        <tr>
            <td>${account.id}</td>
            <td>${account.name}</td>
            <td>${account.money}</td>
        </tr>
    </c:forEach>

</table>
</body>
</html>

编写配置文件

添加jdbc和log4j文件

resources文件夹下面创建 jdbc.propertieslog4j.properties 文件,大家可以自行复制

jdbc.properties中的mysql信息要进行更改 具体更改内容

jdbc.properties中的内容

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=123456

log4j.properties 中的内容

#
# Hibernate, Relational Persistence for Idiomatic Java
#
# License: GNU Lesser General Public License (LGPL), version 2.1 or later.
# See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
#

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=all, stdout

修改web.xml

修改 webapp/WEB-INF/web.xml文件 主要是添加 spring监听器 springmvc前端控制器 乱码过滤器

头文件原始是2.3 要修改为2.5 这边建议你直接复制下面的web.xml代码比较保险

image-20230125212648821

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"
         id="WebApp_ID" version="2.5">


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

    <!--  spring监听器-->
 
    <!--  springmvc前端控制器-->

    <!--  乱码过滤器-->
 


</web-app>

添加applicationContext.xml和spring-mvc.xml文件

resources文件夹下面创建 applicationContext.xmlspring-mvc.xml 文件,大家可以自行复制

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

 
    
</beans>

spring-mvc.xml代码(先把头文件引入)

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

 
</beans>
添加mapper配置文件

resources 文件夹下面创建和Java包一样路径的xml文件

Tips: 这次不能用 .创建要用 / resources文件下的路径一定要用 / 创建

image-20230125214741800

看起来可能效果一样,但是 . 创建的是文件夹叫 . ,而 / 创建的是路径,具体可以去文件夹打开看一下效果

image-20230125214859286

AccountMapper.xml代码

<?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="org.example.mapper.accountMapper">


</mapper>
添加mybatis配置文件

resources文件夹下面创建 sqlMapConfig.xml 文件,大家可以自行复制

AccountMapper.xml代码

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


</configuration>

项目内容填充

填充mybatis配置文件

修改sqlMapConfig.xml

修改resources下的sqlMapConfig.xml

主要内容:引入jdbc.properties 定义类的别名 数据库环境 加载映射

sqlMapConfig.xml代码

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

    <!--    加载jdbc.properties文件-->
    <properties resource="jdbc.properties"></properties>

    <!--    定义类的别名,方便xml使用,两种方式都可以-->
    <typeAliases>
        <typeAlias type="org.example.entity.Account" alias="account"/>
        <!--        <package name="org.example.entity"/>-->
    </typeAliases>

    <!--    数据库环境,引用jdbc.properties文件,一定要注意对应好名字-->
    <environments default="development">
        <environment id="development">
            <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>

    <!--    加载映射-->
    <!--    mybatis不让用. 必须用/  两种方式都可以-->
    <mappers>
        <mapper resource="org/example/mapper/AccountMapper.xml"/>
        <!--        <package name="org/example/mapper"/>-->
    </mappers>


</configuration>
修改AccountMapper.xml

修改resources下的AccountMapper.xml

主要内容:编写保存查询所有的SQL语句

AccountMapper.xml代码

<?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="org.example.mapper.AccountMapper">

    <!--    保存-->
    <insert id="save" parameterType="account">
        insert into account
        values (#{id}, #{name}, #{money})
    </insert>

    <!--    查询所有-->
    <select id="findAll" resultType="account">
        select *
        from account
    </select>
</mapper>

填充Spring配置文件

修改applicationContext.xml

修改resources下的applicationContext.xml

主要内容:Spring扫描service和mapper包

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

    <!--    Spring扫描service和mapper-->
    <context:component-scan base-package="org.example">
        <!--        删除Controller注解          mvc扫controller-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
</beans>	
修改spring-mvc.xml

修改resources下的spring-mvc.xml

主要内容:mvc扫描controller包 配置mvc注解驱动 内部资源视图解析器 开放静态资源访问权限

spring-mvc.xml代码

<?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">
    
    <!--    扫描controller-->
    <context:component-scan base-package="org.example.controller"></context:component-scan>

    <!--    配置mvc注解驱动-->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!--    内部资源视图解析器-->
    <bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--    开放静态资源访问权限-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>

</beans>

填充web.xml配置文件

修改web.xml

修改webapp/WEB-INF下的web.xml

主要内容:spring监听器 springmvc前端控制器 乱码过滤器

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"
         id="WebApp_ID" version="2.5">

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

    <!--  spring监听器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--  springmvc前端控制器-->
    <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:spring-mvc.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>

编写逻辑代码

修改AccountController类文件

修改org.example.controller下的AccountController类文件

主要内容:编写保存查询所有的web层方法

AccountController代码

package org.example.controller;

import org.example.entity.Account;
import org.example.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 org.springframework.web.servlet.ModelAndView;

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

@Controller //声明控制器,指定一个路径前缀,设置utf格式(不设置容易出现乱码)
@RequestMapping(value = "/account", produces = "text/html;charset=UTF-8")
public class AccountController {
    @Autowired
    private AccountService accountService;  //先报错因为没有配置

    //保存    从save.jsp的form表单提交跳转过来的
    @RequestMapping("/save")    //  /save访问当前方法
    @ResponseBody               //不进行页面跳转
    public String save(Account account) throws IOException {
        accountService.save(account);   //调用Service层的保存方法
        return "保存成功";
    }

    //查询
    @RequestMapping("/findAll")    //  /findAll访问当前方法
    public ModelAndView findAll() throws IOException {
        List<Account> list = accountService.findAll();
        ModelAndView modelAndView = new ModelAndView(); //返回视图
        modelAndView.addObject("accountList", list);    //添加视图的数据
        modelAndView.setViewName("accountList");    //指定视图的页面
        return modelAndView;
    }
}

修改AccountServiceImpl类文件

修改org.example.service.impl下的AccountServiceImpl类文件

主要内容:编写保存查询所有的业务层方法

AccountServiceImpl代码

package org.example.service.impl;

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.example.entity.Account;
import org.example.mapper.AccountMapper;
import org.example.service.AccountService;
import org.springframework.stereotype.Service;

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


@Service("accountService")      //Service注解,声明
public class AccountServiceImpl implements AccountService {


    @Override
    public void save(Account account) {
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");   //找对应文件
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);//获得工厂对象
            SqlSession sqlSession = sqlSessionFactory.openSession(true);    //得到Session对象,这里如果不添加参数,下面需要加一个commit
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);   //获得AccountMapper
            mapper.save(account);   //执行save操作
//            sqlSession.commit();  //如果上面sqlsession不加参数,就要commit
            sqlSession.close(); //关闭对象
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public List<Account> findAll() {    //和上面一样,调用不一样的方法,这个需要接收返回数据
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            List<Account> accountList = mapper.findAll();
            sqlSession.close();
            return accountList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

测试

配置Tomcat

点击右上角的Current File -> Edit Configurations -> 点击+ -> Tomcat Serve/Local(看好下面有个TomEE Serve,别选错了) -> Deployment -> 点击+ ->Artifact -> 选择项目: war exploded -> 点击OK

image-20230126112515219

image-20230126112600800

image-20230126112703444

image-20230126112723777

image-20230126112746470

运行

image-20230126113253285

测试添加方法

手动修改地址栏:http://localhost:8080/项目名/save.jsp

image-20230126113534994

输入信息点击保存 -> 地址栏跳到account/save并且页面显示保存成功即为添加成功,再去数据库看一下有没有数据

image-20230126113621711

测试查询方法

手动修改地址栏:http://localhost:8080/项目名/account/findAll

image-20230126114010456

显示即为运行成功

mybatis整合spring

修改配置文件

主要缺点:AccountServiceImpl代码中每一个方法都需要创建Session工厂 ,每次都需要提交关闭sqlSession

主要修改方法:Session工厂给Spring容器管理,获得Mapper实例把事务控制交给spring容器进行声明式事务控制

创建sqlMapConfig-spring.xml文件

添加resources包下

主要内容:sqlMapConfig的很多内容可以通过spring实现,复制sqlMapConfig内容到sqlMapConfig-spring,在新文件进行修改,保留原来的文件

修改加载jdbc.properties文件的代码

sqlMapConfig-spring删除加载jdbc.properties文件的代码

applicationContext.xml文件,中间添加一段代码

 <!--    加载jdbc.properties文件-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

修改数据库环境的代码

sqlMapConfig-spring删除数据库环境的代码

applicationContext.xml文件,中间添加一段代码

 <!--    配置数据库环境-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

修改加载映射的代码

sqlMapConfig-spring删除加载映射的代码

applicationContext.xml文件,中间添加一段代码

<!--    加载映射,扫描mapper所在包-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="org.example.mapper"></property>
    </bean>

到目前为止,sqlMapConfig-spring.xml里面只剩下定义别名

配置sessionFactory

applicationContext.xml文件,中间添加一段代码(pom文件中我们导入mybatis-spring依赖了,直接用)

<!--    配置sessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!--        加载mybatis核心文件-->
        <property name="configLocation" value="classpath:sqlMapConfig-spring.xml"></property>
    </bean>

修改AccountServiceImpl类

接下来AccountServiceImpl类中的AccountMapper会自动注入,可以把原来的方法中的内容删除了,变成如下图

image-20230126174507583

创建一个私有全局AccountMapper变量,声明AutoWired注解,然后方法里面和原来一样调用方法就可以了(不需要创建工厂提交)

	@Autowired
    private AccountMapper accountMapper;

    @Override
    public void save(Account account) {
        accountMapper.save(account);
    }

    @Override
    public List<Account> findAll() {
        return accountMapper.findAll();
    }

此时就可以运行了查看效果了

声明式事务控制

主要内容:平台事务管理器 配置事务增强 事务的aop织入

applicationContext.xml文件,中间添加一段代码

<!--    声明式事务控制-->
    <!--    平台事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--    配置事务增强-->
    <tx:advice id="txAdvice">
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!--    事务的aop织入-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* org.example.service.impl.*.*(..))"></aop:advisor>
    </aop:config>

mybatis整合spring阶段修改后完整代码

sqlMapConfig-spring.xml代码

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

    <!--    定义类的别名,方便xml使用,两种方式都可以-->
    <typeAliases>
        <typeAlias type="org.example.entity.Account" alias="account"/>
        <!--        <package name="org.example.entity"/>-->
    </typeAliases>

</configuration>

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="org.example">
        <!--        删除Controller注解          mvc扫controller-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--    加载jdbc.properties文件-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>


    <!--    配置数据库环境-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--    配置sessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!--        加载mybatis核心文件-->
        <property name="configLocation" value="classpath:sqlMapConfig-spring.xml"></property>
    </bean>

    <!--    加载映射,扫描mapper所在包-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="org.example.mapper"></property>
    </bean>

    <!--    声明式事务控制-->
    <!--    平台事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--    配置事务增强-->
    <tx:advice id="txAdvice">
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!--    事务的aop织入-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* org.example.service.impl.*.*(..))"></aop:advisor>
    </aop:config>

</beans>

AccountServiceImpl类代码

package org.example.service.impl;

import org.example.entity.Account;
import org.example.mapper.AccountMapper;
import org.example.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("accountService")      //Service注解,声明
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public void save(Account account) {
        accountMapper.save(account);
    }

    @Override
    public List<Account> findAll() {
        return accountMapper.findAll();
    }

}

测试mybatis整合spring

手动修改地址栏:http://localhost:8080/项目名/save.jsp

image-20230126194134627

输入信息点击保存 -> 地址栏跳到account/save并且页面显示保存成功即为添加成功,再去数据库看一下有没有数据

image-20230126113621711

手动修改地址栏:http://localhost:8080/项目名/account/findAll

image-20230126114010456

显示即为运行成功

项目压缩包,失效请联系博主,有什么问题欢迎讨论

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/179873.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

浅谈phar反序列化漏洞

目录 基础知识 前言 Phar基础 Phar文件结构 受影响的函数 漏洞实验 实验一 实验二 过滤绕过 补充 基础知识 前言 PHP反序列化常见的是使用unserilize()进行反序列化&#xff0c;除此之外还有其它的反序列化方法&#xff0c;不需要用到unserilize()。就是用到了本文…

C 语言零基础入门教程(十一)

C 数组 C语言支持数组数据结构&#xff0c;它可以存储一个固定大小的相同类型元素的顺序集合。数组是用来存储一系列数据&#xff0c;但它往往被认为是一系列相同类型的变量。 数组的声明并不是声明一个个单独的变量&#xff0c;比如 runoob0、runoob1、…、runoob99&#xf…

【Linux】调试器 - gdb 的使用

目录 一、背景知识 二、debug 与 release 1、生成两种版本的可执行程序 2、debug 与 release 的区别 三、gdb 的使用 1、调试指令与指令集 2、源代码显示、运行与退出调试 3、断点操作 4、逐语句与逐过程 5、调试过程中的数据监视 6、调试过程中快速定位问题 一、背…

吴恩达机器学习笔记(三)逻辑回归

机器学习&#xff08;三&#xff09; 学习机器学习过程中的心得体会以及知识点的整理&#xff0c;方便我自己查找&#xff0c;也希望可以和大家一起交流。 —— 吴恩达机器学习第五章 —— 四、逻辑回归 线性回归局限性 线性回归对于分类问题的局限性&#xff1a;由于离群点…

LeetCode动态规划经典题目(九):入门

学习目标&#xff1a; 了解动态规划 学习内容&#xff1a; 1. LeetCode509. 斐波那契数https://leetcode.cn/problems/fibonacci-number/ 2. LeetCode70. 爬楼梯https://leetcode.cn/problems/climbing-stairs/ 3. LeetCode746. 使用最小花费爬楼梯https://leetcode.cn/proble…

ice规则引擎==启动流程和源码分析

启动 git clone代码 创建数据库ice&#xff0c;执行ice server里的sql&#xff0c;修改ice server的配置文件中的数据库信息 启动ice server 和ice test 访问ice server localhost:8121 新增一个app,默认给了个id为1&#xff0c;这个1可以看到在ice test的配置文件中指定…

MP503空气质量气体传感器介绍

MP503空气质量气体传感器简介MP503空气质量气体传感器采用多层厚膜制造工艺&#xff0c;在微型Al2O3陶瓷基片的两面分别制作加热器和金属氧化物半导体气敏层&#xff0c;封装在金属壳体内。当环境空气中有被检测气体存在时传感器电导率发生变化&#xff0c;该气体的浓度越高&am…

Spring Boot开发自定义的starter

目录 一、Spring Boot的starter概述 二、自定义starter的命名规则 三、自定义starter实战 1. 创建spring工程 2. 修改pom.xml 3. 编写配置类 4. 安装到本地maven仓库 5. 在其他项目中引入 6. 测试 一、Spring Boot的starter概述 SpringBoot中的starter是一种非常重要的机…

【web前端】CSS浮动

多个块级元素纵向排列找标准流&#xff0c;横向排列找浮动 浮动的特性&#xff1a; &#xff08;1&#xff09;浮动元素会脱离标准流&#xff08;脱标&#xff09; &#xff08;有的浮动&#xff0c;有的没浮&#xff09; &#xff08;2&#xff09;浮动的元素会在一行内显示…

C#中[]的几种用法

一、导入外部DLL函数 如[DllImport(“kernel32.dll”)]这叫引入kernel32.dll这个动态连接库。这个动态连接库里面包含了很多WindowsAPI函数,如果你想使用这面的函数&#xff0c;就需要这么引入。举个例子&#xff1a; [DllImport(“kernel32.dll”)] private static extern vo…

栈与队列总结

文章目录栈栈的概述栈的实现栈API设计栈代码实现栈的应用栈在系统中的应用括号匹配问题字符串去重问题逆波兰表达式问题队列队列的概述队列的实现队列的API设计队列代码实现队列的经典题目滑动窗口最大值问题求前 K 个高频元素栈 栈的概述 栈是一种基于先进后出(FILO)的数据结…

Android开发环境搭建

前面从全局和整体角度看了下Android包含哪些东西&#xff0c;自然&#xff0c;也涵盖了开发需要了解的内容&#xff0c;具体参见博文&#xff1a;从技术角度看Android大系统的构成_龙赤子的博客-CSDN博客 写完博文&#xff0c;感觉对Android开发也胸有成竹了&#xff0c;于是就…

ActiveReports.NET 17.0 Crack

ActiveReports.NET 17 添加新的 RDL 仪表板报告类型、新的 Blazor Web Designer&#xff0c;以及对 .NET 7 的全面支持。 2023 年 1 月 25 日 - 15:28新版本 特征 RDL 仪表板 - 新报告类型 RDL 仪表板提供了一种在可滚动的交互式容器中显示数据可视化控件&#xff08;例如图表、…

【Typescript学习】使用 React 和 TypeScript 构建web应用(三)所有组件

教程来自freecodeCamp&#xff1a;【英字】使用 React 和 TypeScript 构建应用程序 跟做&#xff0c;仅记录用 其他资料&#xff1a;https://www.freecodecamp.org/chinese/news/learn-typescript-beginners-guide/ 第三天 以下是视频(0:40-0:60) 的内容 目录第三天1 创建Todo…

JavaEE day6 初识JavaScript

什么是JS JS是通行在各种浏览器的一种语言&#xff0c;JAVA后端代码运行在服务器上&#xff0c;JS代码内容配合HTML&#xff0c;浏览器对JS代码进行解释运行&#xff0c;然后展现在浏览器上&#xff0c;web开发离不开JS。 一般步骤为&#xff1a;&#xff08;index.html与scr…

LinuxC—高级IO

高级IO 1 非阻塞IO/有限状态机编程 1.1 基本概念 定义 有限状态机(Finite State Machine) 缩写为 FSM&#xff0c;状态机有 3 个组成部分&#xff1a;状态、事件、动作。 状态&#xff1a;所有可能存在的状态。包括当前状态和条件满足后要迁移的状态。事件&#xff1a;也称为…

自动驾驶环境感知——视觉传感器技术

文章目录1. 摄像头的成像原理1.1 单目视觉传感器的硬件结构1.2 单目视觉的成像原理 –小孔成像模型1.3 单目视觉的成像原理 – 像素坐标系1.4 单目视觉三维坐标系转换 – 外参1.5 单目视觉的坐标系转换 – 从世界坐标点到像素坐标1.6 单目视觉的特性2. 视觉传感器的标定2.1 视觉…

CSS之精灵图

1. 精灵图 1.1 为什么需要精灵图 一个网页中往往会应用很多小的背景图像作为修饰&#xff0c;当网页中的图像过多时&#xff0c;服务器就会频繁地接收和发送请求图片&#xff0c;造成服务器请求压力过大&#xff0c;这将大大降低页面的加载速度。 为什么使用精灵图&#xff…

9、断点调试

文章目录9、断点调试9.1 为什么需要Debug9.2 Debug的步骤1 添加断点2 启动调试3 单步调试工具介绍9.3 多种Debug情况介绍1 行断点2 方法断点3 字段断点4 条件断点5 异常断点6 线程断点7 强制结束9.4 自定义调试数据视图9.5 常见问题【尚硅谷】idea实战教程-讲师&#xff1a;宋红…

Linux安装mysql--CentOS系统

Linux安装mysql 安装包&#xff1a; https://pan.baidu.com/s/10xvFpfl4nTktaEdhKbY3og 首先启动虚拟机&#xff0c;我是用FinalShell连接的 然后将下载的安装包上传至Linux系统中&#xff0c;直接rz回车就会跳出选择文件的窗口&#xff0c;选择需要上传的安装包即可等待上传…