springmvc+spring+mybatis整合案例 [first]

简介: 本次总结一个出门级别的ssm整合案例(只介绍查询操作 具体其他操作可以自己自由实现)注意事项:1.本案例使用intellij idea开发2.具体jar包不做介绍(本人导入了spring的全部包+mybatis的包以及数据库驱动包和pring-mybatis整合工具包)3.本案例很大程度上参考了一些教学视频(如有侵权,请给我留言)4.本案例只供学习使用.

本次总结一个出门级别的ssm整合案例(只介绍查询操作 具体其他操作可以自己自由实现)

注意事项:

1.本案例使用intellij idea开发

2.具体jar包不做介绍(本人导入了spring的全部包+mybatis的包以及数据库驱动包和pring-mybatis整合工具包)

3.本案例很大程度上参考了一些教学视频(如有侵权,请给我留言)

4.本案例只供学习使用.

具体开发流程:

  1. 程序结构图:
    结构图

  2. 配置文件的编写.

    2.1 web.xml

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


    <!--配置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>springmvc</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>springmvc</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>

    <!--配置乱码解决方案-->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>
2.2 applicationContext.xml(具体的bean是在具体编码后填写)
<?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/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
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

        <!--配置通知-->
        <tx:advice id="txAdvice" transaction-manager="txManager">
                <tx:attributes>
                        <tx:method name="select*" read-only="true"/>
                        <tx:method name="update*" propagation="REQUIRED"/>
                        <tx:method name="insert*" propagation="REQUIRED"/>
                        <tx:method name="delete" propagation="REQUIRED"/>
                </tx:attributes>
        </tx:advice>
        <!--配置切面-->
        <aop:config>
                <aop:pointcut id="piontcut" expression="execution(* com.engle.service.impl.*.*(..))"/>
                <aop:advisor advice-ref="txAdvice" pointcut-ref="piontcut"/>
        </aop:config>


        <!--连接数据库配置文件-->
        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
                <property name="location" value="classpath:database.properties"/>
        </bean>

        <!--配置数据源-->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
                <property name="driverClassName" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
        </bean>

        <!--配置session工厂-->
        <bean id="sqlsessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
                <property name="dataSource" ref="dataSource"/>
                <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>

        <bean id="userDao" class="com.engle.dao.impl.UserDaoImpl">
                <property name="sqlSessionFactory" ref="sqlsessionFactory"/>
        </bean>

        <bean id="userService" class="com.engle.service.impl.UserServiceImpl">
                <property name="userDao" ref="userDao"/>
        </bean>

        <!--配置事务管理器-->
        <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                <property name="dataSource" ref="dataSource"/>
        </bean>
        <!--扫描注解-->
        <context:component-scan base-package="com.engle" />

</beans>
2.3 database.properties(数据库配置文件)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/*yourdatabasename*
username=root
password=*yourpassword*
2.4 mybatis-config.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>
    <!--指定别名-->
    <typeAliases>
        <typeAlias type="com.engle.vo.User" alias="user"/>
    </typeAliases>
    <!--指定映射文件-->
    <mappers>
        <mapper resource="com/engle/vo/UserMapper.xml"/>
    </mappers>
</configuration>
2.5 springmvc.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: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">

    <!--扫描注解所在的包-->
    <context:component-scan base-package="com.engle.controller"/>
</beans>

3.具体的编码工作

3.1 vo模块(POJOs)

package com.engle.vo;

/**
 * Created by engle on 16-5-24.
 */
public class User {
    private int id;
    private String name;
    private  String password;

    public User() {
    }



    public User(int id, String name, String password) {
        super();
        this.id = id;
        this.name = name;
        this.password = password;
    }



    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

usermapper.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="com.engle.vo.UserMapper">
    <!--采用* 表的属性必须和pojos属性名相同-->
    <select id="selectAll" resultType="com.engle.vo.User">
        SELECT * FROM user
    </select>

</mapper>

3.2 dao模块(包括impl)

UserDao

/**
 * Created by engle on 16-5-24.
 */
public interface UserDao {
    public List<User> selectAll();
}

UserDaoImpl


/**
 * Created by engle on 16-5-23.
 */
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {


    public List<User> selectAll() {
        String statement = "com.engle.vo.UserMapper.selectAll";
        return getSqlSession().selectList(statement);
    }
}

3.3 service模块(包括impl)
UserService

public interface UserService {
    public List<User> selectAll();
}

UserServiceImpl

/**
 * Created by engle on 16-5-23.
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public List<User> selectAll() {
        return userDao.selectAll();
    }
}

3.4 utils模块

MybatisUtils

/**
 * Created by engle on 16-5-23.
 */
public class MybatisUtils {
    /**
     * 获取userservice对象
     */
    public static UserService getUserService() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        return (UserService) context.getBean("userService");
    }

}

3.5 controller模块

UserController

/**
 * Created by engle on 16-5-23.
 */
@Controller
public class UserController {

    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    @RequestMapping("/selectAll")
    public String list(ModelMap map){
        setUserService(MybatisUtils.getUserService());
        map.addAttribute("list",userService.selectAll());
        return "/show.jsp";
    }
}

4. jsp页面的编写
show.jsp

<%@ page import="org.springframework.ui.ModelMap" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="/WEB-INF/tld/c.tld" %>

<html>
  <head>
    <title>show all user</title>
  </head>
  <body>
  <table width="80%" align="center">
    <tr>
      <td>编号</td>
      <td>姓名</td>
      <td>密码</td>
    </tr>

    <c:forEach items="${list }" var="user">
      <tr>
        <td>${user.id }</td>
        <td>${user.name }</td>
        <td>${user.password }</td>
      </tr>

    </c:forEach>
   </table>
  </body>
</html>

5.案例结果:

5.1 数据库查询结果:

这里写图片描述

5.2 网页显示结果
这里写图片描述

6.总结:

在这次的案例中 由于使用的idea工具遇到了很多的麻烦,虽然耗费了不少的时但是很多东西让我有了更深的理解.我觉得也是一件好事.

目录
相关文章
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
1006 0
|
12月前
|
Java 数据库连接 数据库
Spring boot 使用mybatis generator 自动生成代码插件
本文介绍了在Spring Boot项目中使用MyBatis Generator插件自动生成代码的详细步骤。首先创建一个新的Spring Boot项目,接着引入MyBatis Generator插件并配置`pom.xml`文件。然后删除默认的`application.properties`文件,创建`application.yml`进行相关配置,如设置Mapper路径和实体类包名。重点在于配置`generatorConfig.xml`文件,包括数据库驱动、连接信息、生成模型、映射文件及DAO的包名和位置。最后通过IDE配置运行插件生成代码,并在主类添加`@MapperScan`注解完成整合
1630 1
Spring boot 使用mybatis generator 自动生成代码插件
|
12月前
|
Java 数据库连接 API
Java 对象模型现代化实践 基于 Spring Boot 与 MyBatis Plus 的实现方案深度解析
本文介绍了基于Spring Boot与MyBatis-Plus的Java对象模型现代化实践方案。采用Spring Boot 3.1.2作为基础框架,结合MyBatis-Plus 3.5.3.1进行数据访问层实现,使用Lombok简化PO对象,MapStruct处理对象转换。文章详细讲解了数据库设计、PO对象实现、DAO层构建、业务逻辑封装以及DTO/VO转换等核心环节,提供了一个完整的现代化Java对象模型实现案例。通过分层设计和对象转换,实现了业务逻辑与数据访问的解耦,提高了代码的可维护性和扩展性。
462 1
|
11月前
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
327 0
|
SQL Java 数据库
解决Java Spring Boot应用中MyBatis-Plus查询问题的策略。
保持技能更新是侦探的重要素质。定期回顾最佳实践和新技术。比如,定期查看MyBatis-Plus的更新和社区的最佳做法,这样才能不断提升查询效率和性能。
684 1
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
1143 0
|
Java 数据库连接 数据库
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
1885 0
|
11月前
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
1381 0
|
12月前
|
人工智能 Java 测试技术
Spring Boot 集成 JUnit 单元测试
本文介绍了在Spring Boot中使用JUnit 5进行单元测试的常用方法与技巧,包括添加依赖、编写测试类、使用@SpringBootTest参数、自动装配测试模块(如JSON、MVC、WebFlux、JDBC等),以及@MockBean和@SpyBean的应用。内容实用,适合Java开发者参考学习。
1247 0

热门文章

最新文章