引言:一个好的项目必须有一个好的框架支持,今天我们来讲一下Java中一个很重要的框架——SSM框架。所谓SSM框架就是Spring+SpringMVC+MyBatis的整合。
maven项目的创建是基础,一个好的maven项目直接决定了项目开发的效率。
众所周知,Java的后期学习基本上是重配置,轻代码。所以一个好的项目,首先要从配置出发,并且要把配置做好,才能有利于后面的代码编写。
<properties>
<project.spring.version>5.2.12.RELEASEproject.spring.version>
<project.slf4j.version>1.7.5project.slf4j.version>
<project.druid.version>1.2.4project.druid.version>
<project.lombok.version>1.18.16project.lombok.version>
<project.mysql.version>8.0.22project.mysql.version>
<project.mybatis.version>3.5.6project.mybatis.version>
<project.mybatis-spring.version>2.0.6project.mybatis-spring.version>
<project.junit.version>4.12project.junit.version>
<project.json.version>2.12.1project.json.version>
<project.pageHelper.version>5.1.2project.pageHelper.version>
properties>
<dependencies>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>${project.lombok.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>${project.druid.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${project.spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${project.spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>${project.spring.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${project.slf4j.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${project.mysql.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${project.mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>${project.mybatis-spring.version}version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>${project.junit.version}version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>${project.json.version}version>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>${project.pageHelper.version}version>
dependency>
dependencies>
druid.url=jdbc:mysql://192.168.47.129:3306/ssm_db?useUnicode=true&serverTimezone=Asia/Shanghai&useSSL=true
druid.username=root
druid.password=123
log4j.rootLogger=debug,Console,Logfile
#Console output
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm:ss} [%t] %rms (%-5p) [%c] -%l-- {%m}%n
log4j.appender.Logfile=org.apache.log4j.FileAppender
log4j.appender.Logfile.File=D:/logs/mybatis.log
log4j.appender.Logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.Logfile.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm:ss} [%t] %rms (%-5p) [%c] -%l-- {%m}%n
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
<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_3_1.xsd" version="3.1">
<display-name>ssm-studentdisplay-name>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring/mybatis/spring-*.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>springDispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring/mvc/springmvc-*.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springDispatcherServletservlet-name>
<url-pattern>/*url-pattern>
servlet-mapping>
web-app>
<context:component-scan
base-package="com.ithouke.ssm.controller">context:component-scan>
<mvc:resources location="static/" mapping="static/**">mvc:resources>
<mvc:annotation-driven>mvc:annotation-driven>
<context:component-scan
base-package="com.ithouke.ssm">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
context:component-scan>
<context:property-placeholder
location="classpath:spring/mybatis/config/druid.properties" />
<bean id="druidDataSource"
class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${druid.url}">property>
<property name="username" value="${druid.username}">property>
<property name="password" value="${druid.password}">property>
bean>
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="druidDataSource">property>
<property name="typeAliasesPackage"
value="com.ithouke.ssm.entity">property>
<property name="mapperLocations"
value="classpath:mapper/*.mapper.xml">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ithouke.ssm.mapper">property>
<property name="sqlSessionFactoryBeanName"
value="sqlSessionFactory">property>
bean>
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="druidDataSource">property>
bean>
<tx:annotation-driven
transaction-manager="txManager" />
做到这里,基本上的配置已经完成。
这次我们来做一个学生信息管理系统的一个小模块——对学生信息进行增删改查
编写代码之前我们要创建数据库以及表,博主用的是linux里面的数据库,以前的文章里面有写在linux中安装docker,以及在docker安装mysql,感兴趣的可以看一下。
import java.util.Date;
import org.apache.ibatis.type.Alias;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Alias("Student") //别名
@Data //get,set方法
@AllArgsConstructor //全参构造方法
@NoArgsConstructor //无参构造方法
public class Student {
private Integer id;
private String name ;
private Integer age;
private Date birth;
}
import java.util.List;
import com.ithouke.ssm.entity.Student;
public interface IStudentMapper {
void save(Student student);
void delete(int id);
void update(Student student);
List<Student> findAll();
}
<mapper namespace="com.ithouke.ssm.mapper.IStudentMapper">
<resultMap type="Student" id="studentMap">
<id property="id" column="stu_id" />
<result property="name" column="stu_name" />
<result property="age" column="stu_age" />
<result property="birth" column="stu_birth" />
resultMap>
<insert id="save">
INSERT INTO student_tab(stu_name,stu_age,stu_birth)
VALUES(#{name},#{age},#{birth})
insert>
<delete id="delete">
DELETE FROM student_tab WHERE stu_id = #{id}
delete>
<update id="update">
UPDATE student_tab
<set>
<if test="name != null">
stu_name=#{name},
if>
<if test="age != null">
stu_age=#{age},
if>
<if test="birth != null">
car_birth=#{birth},
if>
set>
WHERE stu_id = #{id}
update>
<select id="findAll" resultMap="studentMap">
SELECT * FROM student_tab
select>
mapper>
此时mybatis的部分已经完成(重点就是接口的编写和xml文件的配置)
import java.util.List;
import com.ithouke.ssm.entity.Student;
public interface IStudentService {
void addStu(Student student);
void deleteStu(int id);
void updateStu(Student student);
List<Student> findAll();
}
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ithouke.ssm.entity.Student;
import com.ithouke.ssm.mapper.IStudentMapper;
import com.ithouke.ssm.service.IStudentService;
@Service
@Transactional
public class StudentServiceImpl implements IStudentService {
@Autowired
private IStudentMapper mapper;
@Override
public void addStu(Student student) {
mapper.save(student);
}
@Override
public void deleteStu(int id) {
mapper.delete(id);
}
@Override
public void updateStu(Student student) {
mapper.update(student);
}
@Override
public List<Student> findAll() {
return mapper.findAll();
}
}
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ithouke.ssm.dto.HttpResp;
import com.ithouke.ssm.entity.Student;
import com.ithouke.ssm.service.IStudentService;
@Controller
@RequestMapping("/api")
public class StudentController {
@Autowired
private IStudentService iss;
@PostMapping("/addStu")
@ResponseBody
public HttpResp addStu(Student student) {
iss.addStu(student);
return new HttpResp(20001, "学生信息添加成功", null, new Date());
}
@DeleteMapping("/deleteStu")
@ResponseBody
public HttpResp deleteStu(int id) {
iss.deleteStu(id);
return new HttpResp(20002, "学生信息删除成功", null, new Date());
}
@PutMapping("/updateStu")
@ResponseBody
public HttpResp updateStu(Student student) {
iss.updateStu(student);
return new HttpResp(20003, "学生信息修改成功", null, new Date());
}
@GetMapping("/findAllStu")
@ResponseBody
public HttpResp findAllStu() {
List<Student> list = iss.findAll();
return new HttpResp(20004, "学生信息查询成功", list, new Date());
}
}
博主用的是postman进行测试后端。
到此时,我们的SSM框架基本成功,项目还不完善,之后博主会在进行完善前端部分以及后续的项目。文章中有任何问题,请在评论区进行留言,博主会一一解答。码字不易,请一键三连哟
关于文章中的注解,之后会有一个详细的文章进行介绍。欢迎阅读