之前利用IDEA成功在本地搭建好SSM的开发环境,并进行运行能够访问到指定的页面,今天继续继续完善,利用SSM实现增删改查,进一步学习SSM框架的组成及功能实现(拖了好久才抽时间整理这个)。
现在说明下,每个平台都会有角色控制表,这里新增一个角色表,使用了MySQL数据库存储数据。本次目标,利用SSM框架开发实现对平台角色表进行增删改查,下面进入正题,如果不熟悉如何搭建SSM应用,请参考上篇【从0到N】IDEA从0到1一步一步搭建SSM项目。
首先是进行数据表的设计及创建,SQL如下:
CREATE TABLE `oz_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '角色编号',
`rolename` varchar(50) NOT NULL COMMENT '角色名称',
`status` varchar(1) DEFAULT '1' COMMENT '状态',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2020000011 DEFAULT CHARSET=utf8;
下面进入正题:
整体目录结构如下:
第一步,配置数据库连接
在resources目录下新增数据库信息配置文件db.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
第二步,在配置文件applicationContext.xml增加数据源连接信息
<!--配置数据源-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
第三步,进入正式编码,先写dto层,创建Role.java
package com.onezero.zeromanage.dto;
public class Role {
private String id;
private String roleName;
private String status;
public Role(){
}
public void setId(String id) {
this.id = id;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public void setStatus(String status) {
this.status = status;
}
public String getId() {
return id;
}
public String getRoleName() {
return roleName;
}
public String getStatus() {
return status;
}
}
第四步,写service层,写service的接口RoleService
因为我们本次要实现增删改查,所以在这里要实现所有的新增、更新、删除、查询操作。
package com.onezero.zeromanage.service;
import com.onezero.zeromanage.dto.Role;
import java.util.List;
public interface RoleService {
//List
List<Role> selectAll();
//select
Role selectById(String id);
//insertRole
boolean insertRole(Role role);
//updateRole
boolean updateRole(Role role);
//deleteRole
boolean deleteRole(String id);
}
第五步,写service继承接口实现类
本步则是在上一步实现的接口基础上,编写每一个具体的实现类,这里要调用mapper的接口
package com.onezero.zeromanage.service.impl;
import com.onezero.zeromanage.dto.Role;
import com.onezero.zeromanage.mapper.RoleMapper;
import com.onezero.zeromanage.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Override
public List<Role> selectAll(){
return roleMapper.selectAll();
}
//select
@Override
public Role selectById(String id) {
return roleMapper.selectById(id);
}
//insertRole
public boolean insertRole(Role role){
boolean addResult = roleMapper.addRole(role);
return addResult;
}
//updateRole
public boolean updateRole(Role role){
boolean updResult = roleMapper.updateRole(role);
return updResult;
}
//deleteRole
public boolean deleteRole(String id){
boolean delResult = roleMapper.deleteRole(id);
return delResult;
}
}
第六步,mapper层实现,mapper层接口
package com.onezero.zeromanage.mapper;
import com.onezero.zeromanage.dto.Role;
import java.util.List;
public interface RoleMapper {
List<Role> selectAll();
//selectById
Role selectById(String id);
//insertRole
boolean addRole(Role role);
//updateRole
boolean updateRole(Role role);
//deleteRole
boolean deleteRole(String id);
}
第七步,具体数据库操作的实现
通过mapper的接口调用这个文件中具体对应的SQL,实现对数据的增删改查。
注:<resultMap>中<result>标签中对应的字段column对应SQL查询结果对应的字段名称,property属性则对应在dto层定义的变量名称,会将查询的值赋值给该变量。
<?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.onezero.zeromanage.mapper.RoleMapper">
<resultMap id="roleRes" type="com.onezero.zeromanage.dto.Role">
<id column="id" property="id"></id>
<result column="rolename" property="roleName"></result>
<result column="status" property="status"></result>
</resultMap>
<select id="selectAll" resultMap="roleRes">
select id,rolename,status from oz_role
</select>
<select id="selectById" resultMap="roleRes">
select id,rolename,status from oz_role where id = #{id}
</select>
<insert id="addRole" parameterType="com.onezero.zeromanage.dto.Role">
insert into oz_role (rolename)value(#{roleName})
</insert>
<update id="updateRole" parameterType="com.onezero.zeromanage.dto.Role">
update oz_role set rolename = #{roleName},status = #{status} where id = #{id}
</update>
<delete id="deleteRole" parameterType="String">
delete from oz_role where id = #{id}
</delete>
</mapper>
第八步,controller类的实现
外部请求进来会先经过controller层,对URL进行判断处理后会请求对应的service层
package com.onezero.zeromanage.controller;
import com.onezero.zeromanage.dto.Role;
import com.onezero.zeromanage.service.RoleService;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class RoleController {
@Autowired
private RoleService roleService;
//selectAll
@RequestMapping(value = "/role")
@ResponseBody
public List<Role> getRoles(){
List<Role> Roles = roleService.selectAll();
return Roles;
}
//selectRoleById
@RequestMapping(value="/getRole",method = RequestMethod.POST)
@ResponseBody
public Role getRoleById(String id){
Role selectRole = roleService.selectById(id);
return selectRole;
}
//InsertRole
@RequestMapping(value = "/addUpdateRole",method = RequestMethod.POST)
@ResponseBody
public String addRole(@RequestParam(value = "id",required=false)String id, Role role){
boolean addStt = false;
boolean updStt = false;
if(id==null || "".equals(id)){
addStt = roleService.insertRole(role);
if(addStt){
return "addSuccess";
}else{
return "addfail";
}
}else{
updStt = roleService.updateRole(role);
if(updStt){
return "updSuccess";
}else{
return "updfail";
}
}
}
//deleteRole
@RequestMapping(value="/deleteRole",method = RequestMethod.POST)
@ResponseBody
public String deleteRole(String id){
boolean delStt = roleService.deleteRole(id);
if(delStt){
return "delSuccess";
}else{
return "delfail";
}
}
}
最后,进行配置文件的补充说明:
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: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">
<!--扫描service和dto-->
<context:component-scan base-package="com.onezero.zeromanage.service.impl"/>
<context:component-scan base-package="com.onezero.zeromanage.service"/>
<context:component-scan base-package="com.onezero.zeromanage.dto"/>
<!--spring和mybatis-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--配置数据源-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--扫描mapper-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.onezero.zeromanage.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
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>
<!--配置mapper地址-->
<mappers>
<package name="com.onezero.zeromanage.mapper"></package>
</mappers>
</configuration>
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"
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
">
<!--扫描controller,修改为自己写的controller-->
<context:component-scan base-package="com.onezero.zeromanage.controller"/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".html"/>
</bean>
<!--静态资源交给default-servlet处理-->
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<!--对象转json-->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--增加配置-->
<!--字符编码过滤器-->
<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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--启动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>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--增加配置-->
</web-app>
pom.xml
<?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>zero</groupId>
<artifactId>zero</artifactId>
<version>1.0-SNAPSHOT</version>
<!--新增配置-->
<properties>
<spring.version>4.3.18.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--servlet&jsp-->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-servlet-api -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>8.5.33</version>
</dependency>
<!--Spring与Mybatis集成-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.43</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--dataSource连接池-->
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.5.0</version>
</dependency>
<!--对象转json-->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
</dependencies>
<build>
<finalName>zero</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>6</source>
<target>6</target>
</configuration>
</plugin>
</plugins>
</build>
<!--新增配置-->
</project>
对于具体配置,可以查看具体的代码,已经上传了git,具体地址如下:
如果有疑问,可以在底下评论,对于本文不足的地方,也可指出,让我们共同进步!