Spring+SpringMVC+MyBatis实践入门
环境介绍
在这篇博客中,我将在idea中基于Maven构建一个SSM(Spring+SpringMVC+MyBatis)测试项目。
我使用的工具和库:
JDK 23
Apache Tomcat 11
MySQL 8.0.32
Apache Maven 3.9.9
idea 2024.3 社区版
Spring框架6.1.0
MyBatis 3.5.16(Hibernate 是替代方案。)
MyBatis-Spring 3.0.4
网盘下载链接: https://pan.baidu.com/s/1_uS-mAdi1rXZb5d0x_rKeA?pwd=nh38
也可以尝试其他的稳定或发布版本。
Spring框架和SpringMVC
Spring 框架为任何类型的部署平台上基于 Java 的现代企业应用程序提供了全面的编程和配置模型。
Spring 的一个关键要素是应用程序级别的基础设施支持:Spring 专注于企业应用程序的“管道”,以便团队可以专注于应用程序级别的业务逻辑,而无需与特定部署环境建立不必要的联系。
Spring框架提供了以下功能:
核心技术:dependency injection, events, resources, i18n, validation, data binding, type conversion, SpEL, AOP.
测试:mock objects, TestContext framework, Spring MVC Test, WebTestClient.
数据访问:transactions, DAO support, JDBC, ORM, Marshalling XML.
Spring MVC 和 Spring WebFlux Web 框架。
集成:remoting, JMS, JCA, JMX, email, tasks, scheduling, cache.
语言:Kotlin, Groovy, dynamic languages.
Maven
Apache Maven 是一个软件项目管理和理解工具。基于项目对象模型 (POM) 的概念,Maven 可以通过仓库来管理项目的构建、报告和文档。
项目创建过程
基本流程:
- 准备数据库;
- 在 idea 中创建项目;
- 修改配置文件;
- 创建类;
- 启动Tomcat服务器。
- POSTMAN测试接口
数据库准备
安装 MySQL,创建数据库并授予给定用户权限。创建一个表并向表中插入一些测试数据。
CREATE TABLE `t_project` (
`project_id` bigint NOT NULL AUTO_INCREMENT,
`project_name` varchar(100) DEFAULT NULL,
`project_desc` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
`create_time` varchar(100) DEFAULT NULL,
`create_user_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`modify_time` varchar(100) DEFAULT NULL,
`modify_user_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
PRIMARY KEY (`project_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
创建一个maven项目
maven项目的创建过程参考:SpringMVC Maven项目搭建 简单易上手
项目结构:
POM文件中导入maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.neo</groupId>
<artifactId>springmvc01</artifactId>
<version>1.0-SNAPSHOT</version>
<!--打包方式war包-->
<packaging>war</packaging>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>6.2.0</spring.version>
<jackson-databind.version>2.18.1</jackson-databind.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<!-- <dependency>-->
<!-- <groupId>org.springframework</groupId>-->
<!-- <artifactId>spring-aop</artifactId>-->
<!-- <version>${spring.version}</version>-->
<!-- </dependency>-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.16</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.23</version>
</dependency>
</dependencies>
</project>
配置文件修改
jdbc.properties 用于存储有关数据库连接的信息。 XML 文件加载后可以直接使用这些值。举个例子:
# Common
mysql.jdbc.driverClassName=com.mysql.jdbc.Driver
mysql.jdbc.url=jdbc:mysql://localhost:3306/[schema_name]
mysql.jdbc.username=[username]
mysql.jdbc.password=[password]
# Used in Druid
mysql.jdbc.initialSize=0
mysql.jdbc.maxActive=20
mysql.jdbc.maxIdle=20
mysql.jdbc.minIdle=1
mysql.jdbc.maxWait=60000
spring-mybatis.xml 通常用于data source bean 和 sql session factory 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: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">
<!-- Data Source Bean -->
<bean id="dataSource"
class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName"
value="${mysql.jdbc.driverClassName}" />
<property name="url" value="${mysql.jdbc.url}" />
<property name="username"
value="${mysql.jdbc.username}" />
<property name="password"
value="${mysql.jdbc.password}" />
<!-- You could use other data source manager driver such as: class="org.springframework.jdbc.datasource.DriverManagerDataSource". If so, the properties below should be removed based on the schema of xml. -->
<property name="initialSize"
value="${mysql.jdbc.initialSize}" />
<property name="maxActive"
value="${mysql.jdbc.maxActive}" />
<property name="maxIdle" value="${mysql.jdbc.maxIdle}" />
<property name="minIdle" value="${mysql.jdbc.minIdle}" />
<property name="maxWait" value="${mysql.jdbc.maxWait}" />
</bean>
<!-- SQL Session Factory Bean -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- auto scan mapping xml files -->
<property name="mapperLocations"
value="classpath:org/zhuzhu/ssm/mapper/*.xml" />
<!-- If there are special configurations such as alias, could add: <property name="configLocation" value="classpath:mybatis-config.xml"></property> -->
</bean>
<!-- DAO interfaces -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.zhuzhu.ssm.dao" />
<property name="sqlSessionFactoryBeanName"
value="sqlSessionFactory" />
</bean>
</beans>
spring-tx.xml 用于AOP(面向方面编程)和事务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: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">
<!-- Auto scan AOP annotation -->
<aop:aspectj-autoproxy
proxy-target-class="true" />
<!-- Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Configure the transaction in detail. -->
<tx:advice id="transactionAdvice"
transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"
isolation="DEFAULT" read-only="false"
rollback-for="Exception" />
<tx:method name="delete*" propagation="REQUIRED"
isolation="DEFAULT" read-only="false"
rollback-for="Exception" />
<tx:method name="update*" propagation="REQUIRED"
isolation="DEFAULT" read-only="false"
rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<!-- Configure AOP: auto generate proxy for targets -->
<aop:config proxy-target-class="true">
<aop:pointcut id="transactionPointcut"
expression="execution(* org.zhuzhu.ssm.service..*Impl.*(..))" />
<aop:advisor advice-ref="transactionAdvice"
pointcut="within(org.zhuzhu.ssm.controller.*)" />
</aop:config>
</beans>
spring-mvc.xml 用于 MVC 注释和视图解析器 bean。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Auto scan components -->
<context:component-scan
base-package="org.zhuzhu.ssm.dao" />
<context:component-scan
base-package="org.zhuzhu.ssm.service" />
<context:component-scan
base-package="org.zhuzhu.ssm.controller" />
<context:component-scan
base-package="org.zhuzhu.ssm.mapper" />
<!-- Register MVC annotation driver -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<mvc:resources mapping="/**" location="/" />
<!-- Configure View Resolver. -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
spring.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Load properties configuration file. -->
<context:property-placeholder
location="classpath:db.properties" />
<!-- Autowired Annotaion Bean -->
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<!-- if you want to only load a single spring configuration file, you could import all other files here. -->
<import resource="spring-mvc.xml" />
<import resource="spring-mybatis.xml" />
<import resource="spring-tx.xml" />
</beans>
log4j2.xml是Log4j2的配置文件。在之前版本的Log4j中,配置文件是log4j.properties。您可以设置日志的输出方式、级别、输出格式等。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
</Console>
<RollingFile name="RollingFile"
filename="log/test.log"
filepattern="${logPath}/%d{YYYYMMddHHmmss}-rolling.log">
<PatternLayout
pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
<Policies>
<SizeBasedTriggeringPolicy
size="100 MB" />
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingFile>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console" />
<AppenderRef ref="RollingFile" />
</Root>
</Loggers>
</Configuration>
最后,web.xml也需要修改。
...
<!-- Load spring configuration files. -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<!-- Servlet Context Listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Encoding Filter -->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!-- Encoding filter for jsp page -->
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Front-end controller servlet -->
<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:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Logging -->
<context-param>
<!-- Log Profile Path -->
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j2.xml</param-value>
</context-param>
<context-param>
<!-- Refresh intervals for log pages -->
<param-name>log4jRefreshInterval</param-name>
<param-value>6000</param-value>
</context-param>
<context-param>
<param-name>controller</param-name>
<param-value>controller-log</param-value>
</context-param>
<context-param>
<param-name>loggingLevel</param-name>
<param-value>info</param-value>
</context-param>
<listener>
<listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>
...
ProjectMapper.xml 是将数据库中的表映射到模型类的映射器文件。还可以为 DAO 类中的方法配置 SQL 语句。示例如下所示:
<?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.neo.project.dao.ProjectDAO">
<resultMap id="userResultMap"
type="org.neo.project.model.ProjectDO">
<id property="projectId" column="project_id" />
<result property="projectName" column="project_name" />
<result property="projectDesc" column="project_desc" />
<result property="createTime" column="create_time" />
<result property="createUserId" column="create_user_id" />
<result property="modifyTime" column="modify_time" />
<result property="modifyUserId" column="modify_user_id" />
</resultMap>
<select id="listAllProjects" resultMap="userResultMap">
SELECT project_id, project_name, project_desc, create_time,create_user_id,modify_time,modify_user_id
FROM t_project;
</select>
<select id="getProjectById" parameterType="java.lang.Integer"
resultMap="userResultMap">
SELECT project_id, project_name, project_desc, create_time,create_user_id,modify_time,modify_user_id
FROM user
WHERE project_id=#{projectId,jdbcType=INTEGER};
</select>
<insert id="saveProject" parameterType="org.neo.project.model.ProjectDO"
useGeneratedKeys="true" keyColumn="project_id" keyProperty="projectId">
INSERT
INTO user(project_name, project_desc, create_time,create_user_id,modify_time,modify_user_id)
VALUES(#{projectName,jdbcType=VARCHAR},
#{projectDesc,jdbcType=VARCHAR},
#{createTime,jdbcType=VARCHAR},
#{createUserId,jdbcType=VARCHAR},
#{modifyTime,jdbcType=VARCHAR},
#{modifyUserId,jdbcType=VARCHAR}
);
</insert>
<update id="modifyProject"
parameterType="org.neo.project.model.ProjectDO">
UPDATE user SET
project_name=#{userName,jdbcType=VARCHAR},
project_desc=#{userPassword,jdbcType=VARCHAR},
create_time=#{userEmail,jdbcType=VARCHAR},
create_user_id=#{userEmail,jdbcType=VARCHAR},
modify_time=#{userEmail,jdbcType=VARCHAR},
modify_user_id=#{userEmail,jdbcType=VARCHAR}
WHERE
project_id=#{userId,jdbcType=INTEGER};
</update>
<delete id="deleteProject" parameterType="java.lang.Integer">
DELETE FROM t_project WHERE
project_id=#{projectId,jdbcType=INTEGER}
</delete>
</mapper>
创建Java类
编写Controller、service、DAO层的java代码
ProjectController.java
package org.neo.project.controller;
import org.neo.project.model.ProjectDO;
import org.neo.project.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @program: springmvc01
* @author: neo
* @create: 2024-11-16 19:22
**/
@RestController
@RequestMapping("project")
public class ProjectController {
@Autowired
private ProjectService projectService;
@RequestMapping("listAllProjects1")
public String listAllProjects1(){
return "projectService.listAllProjects()";
}
@RequestMapping("listAllProjects")
@ResponseBody
public Object listAllProjects(){
return projectService.listAllProjects();
}
// @RequestMapping("getProjectById")
// public ProjectDO getProjectById(Integer projectId) {
// return projectService.getProjectById(projectId);
// }
// @RequestMapping("saveProject")
// public void saveProject(ProjectDO projectDO) {
// projectService.saveProject(projectDO);mybatis
// }
// @RequestMapping("modifyProject")
// public void modifyProject(ProjectDO projectDO) {
// projectService.modifyProject(projectDO);
// }
// @RequestMapping("deleteProject")
// public void deleteProject(Integer projectId) {
// projectService.deleteProject(projectId);
// }
}
ProjectService.java
package org.neo.project.service;
import org.neo.project.model.ProjectDO;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @program: springmvc01
* @author: neo
* @create: 2024-11-16 19:24
**/
public interface ProjectService {
List<ProjectDO> listAllProjects();
ProjectDO getProjectById(Integer projectId);
void saveProject(ProjectDO projectDO);
void modifyProject(ProjectDO projectDO);
void deleteProject(Integer projectId);
}
ProjectServiceImpl.java
package org.neo.project.service.impl;
import org.neo.project.dao.ProjectDAO;
import org.neo.project.model.ProjectDO;
import org.neo.project.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @program: springmvc01
* @author: neo
* @create: 2024-11-16 19:24
**/
@Service
public class ProjectServiceImpl implements ProjectService {
@Autowired
private ProjectDAO projectDAO;
@Override
public List<ProjectDO> listAllProjects() {
return projectDAO.listAllProjects();
// return null;
}
@Override
public ProjectDO getProjectById(Integer projectId) {
// return projectDAO.getProjectById(projectId);
return null;
}
@Override
public void saveProject(ProjectDO projectDO) {
// projectDAO.saveProject(projectDO);
}
@Override
public void modifyProject(ProjectDO projectDO) {
// projectDao.modifyProject(projectDO);
}
@Override
public void deleteProject(Integer projectId) {
// projectDao.deleteProject(projectId);
}
}
ProjectDAO.java
package org.neo.project.dao;
import org.apache.ibatis.annotations.Mapper;
import org.neo.project.model.ProjectDO;
import java.util.List;
/**
* @program: springmvc01
* @author: neo
* @create: 2024-11-16 19:23
**/
public interface ProjectDAO {
List<ProjectDO> listAllProjects();
ProjectDO getProjectById(Integer projectId);
void saveProject(ProjectDO projectDO);
void modifyProject(ProjectDO projectDO);
void deleteProject(Integer projectId);
}
Project.java
package org.neo.project.model;
/**
* @program: springmvc01
* @author: neo
* @create: 2024-11-17 16:36
**/
public class ProjectDO {
private static final long serialVersionUID = 1L;
private static final String TABLE_NAME = "t_project";
private Long projectId; // 项目ID
private String projectName; // 项目名称
private String projectDesc; // 项目描述
private String createTime; // 创建时间
private String createUserId; // 创建用户
private String modifyTime; // 修改时间
private String modifyUserId; // 修改用户
public Long getProjectId() {
return projectId;
}
public void setProjectId(Long projectId) {
this.projectId = projectId;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectDesc() {
return projectDesc;
}
public void setProjectDesc(String projectDesc) {
this.projectDesc = projectDesc;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getCreateUserId() {
return createUserId;
}
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
public String getModifyTime() {
return modifyTime;
}
public void setModifyTime(String modifyTime) {
this.modifyTime = modifyTime;
}
public String getModifyUserId() {
return modifyUserId;
}
public void setModifyUserId(String modifyUserId) {
this.modifyUserId = modifyUserId;
}
}
配置Tomcat启动
POST测试接口
原文地址:https://blog.csdn.net/fuxiaojun1988/article/details/143867558
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!