大数据 kubeflow Finder 父子元素 string javafx serialization jQuery Mobile java商城源码 pr序列设置哪个好 matlab生成对角矩阵 java上传图片 图片生成链接 python计算器 python生成随机数 python加法 python中的index python函数内定义函数 java什么是多态 java的运行环境 java结束线程 java求阶乘 java语言是什么 java异常 圣剑世界 workflow中文 整站系统 emit vfloppy hexworkshop fireworks8序列号 刷声望 skycc组合营销软件 sdm439 网红照片男 无主之地2联机超时 360越狱版 oracle游标 血dk属性 驱动程序更新
当前位置: 首页 > 学习教程  > 编程语言

SSM框架入门——整合SSM并实现对数据的增删改查功能二(MyBatis采用注解方式)

2020/8/11 20:55:24 文章标签:

跟上一篇博文相似,换汤不换药,这次依然简单地做一个校园管理系统,只基本实现增删改查功能:
在这里插入图片描述
在这里插入图片描述
项目结构:
在这里插入图片描述

一、准备好SSM所需的框架

在这里插入图片描述

二、数据库表结构

表做的比较简单:
在这里插入图片描述

三、在src下创建jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/chapter15?characterEncoding=UTF-8
jdbc.user=root
jdbc.password=123456

四、编写application.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: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">

	<!-- 1、引入外部 properties 文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	<!-- 2、注册数据源 -->
	<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driverClass}" />
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
		<property name="user" value="${jdbc.user}" />
		<property name="password" value="${jdbc.password}" />
	</bean>
	 <!--3、配置Session工厂对象-->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--4、配置扫描的包-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.qfedu.dao"></property>
    </bean>
	<!--5、扫描对应的类 IOC创建对象  -->
	 <!--扫描注解的类-->
    <context:component-scan base-package="com.qfedu.service.impl"></context:component-scan>

</beans>

五、配置SpringMVC-config.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 -->
	<context:component-scan base-package="com.qfedu.controller" />
	<!-- 配置视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="suffix" value=".jsp" />
	</bean>
	<mvc:annotation-driven/>
	<mvc:default-servlet-handler></mvc:default-servlet-handler>
</beans>

六、配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>chapter15</display-name> 
  <!--Spring的配置文件-->
   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application.xml</param-value>
    </context-param>
    <!--Spring的监听器-->
     <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>/WEB-INF/springMVC-config.xml</param-value>
     	 </init-param>
     	<load-on-startup>1</load-on-startup>
	</servlet>
	 <!--访问DispatcherServlet对应的路径-->
	 <servlet-mapping>
	      <servlet-name>springMVC</servlet-name>
	      <url-pattern>/</url-pattern> 
	 </servlet-mapping>
	 <!--编码格式过滤器-->
	  <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--引导页-->
	 <welcome-file-list>
	    <welcome-file>page02.jsp</welcome-file>
	  </welcome-file-list>
</web-app>

七、编写项目代码

1)数据库表映射类school.java:

package com.qfedu.pojo;
public class School {
	private int id;
	private String name;
	private int persons;
	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 int getPersons() {
		return persons;
	}
	public void setPersons(int persons) {
		this.persons = persons;
	}
}

2)操作数据库的接口SchoolDao.java:

package com.qfedu.dao;
import java.util.List;
import org.apache.ibatis.annotations.*;
import com.qfedu.pojo.School;
public interface SchoolDao {
	//新增
	@Insert("insert into t_school(name,persons) values(#{name},#{persons})")
	int insert(School school);
	//查询
	@Select("select * from t_school")
	@ResultType(School.class)
	List<School> selectAll();
	//删除
	@Delete("delete  from t_school where id = #{id}")
	int delete(School school);//void delete(int id);或int delete(int id)也可
	//查找
	@Select("select * from t_school where id=#{id}")
	@ResultType(School.class)
	List<School> selectById(int id);
	//修改
	@Update("update t_school set name=#{name},persons=#{persons} where id=#{id}")
	void update(School school);
	
}

这里采用的是对MyBatis中注解的应用。注意:使用ResultType注解的前提是数据库中的表的字段名称和对应类的属性名称都一致,而且对应的类内部也没有复杂的嵌套关系。
3)业务逻辑层接口SchoolService.java:

package com.qfedu.service;
import java.util.List;
import com.qfedu.pojo.School;
public interface SchoolService {
	int save(School school);
	int del(School school);//void或int del(int id);
	List<School> queryAll();
	List<School> selectById(int id);
	void upd(School school);//或int upd(School school);
}

4)业务逻辑层接口实现类SchoolServiceImpl.java:

package com.qfedu.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qfedu.dao.SchoolDao;
import com.qfedu.pojo.School;
import com.qfedu.service.SchoolService;
@Service
public class SchoolServiceImpl implements SchoolService{
	@Autowired
	private SchoolDao dao;
	@Override
	public int save(School school) {
		return dao.insert(school);
	}
	@Override
	public List<School> queryAll() {
		return dao.selectAll();
	}
	@Override
	public int del(School school) {
		return dao.delete(school);
	}  /*
	public void或int del(int id){
	       this.dao.delete(id)
	   }
	   */
	@Override
	public List<School> selectById(int id){
		return dao.selectById(id);
	}
	@Override
	public void upd(School school) {
		this.dao.update(school);
	}
	/* 或  public int upd(School school){
	 *     return dao.update(school);
	 *      }
	 * 
	 * */
}

5)控制器类SchoolController.java:

package com.qfedu.controller;
import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.qfedu.pojo.School;
import com.qfedu.service.SchoolService;
@Controller
public class SchoolController {
	@Autowired
	private SchoolService schoolService;
	//新增
	@RequestMapping(value="/schooladd",method=RequestMethod.POST)
	public String save(School school,Model model) {
		if(schoolService.save(school)>0) {
			return "page02";
		}else {
			model.addAttribute("msg", "服务器异常,新增学校信息有误");
			return "page01";
		}
	}
	//查询
	@RequestMapping(value="/schoolall",method=RequestMethod.GET)
	public String all(Model model) {
		model.addAttribute("schools", schoolService.queryAll());//page02<c:forEach items="${schools }" var="s">中“items="${schools}"”
		return "page02";
	}
	@RequestMapping("/del")
	public String del(@Param("id") School school) {   //public String del(@Param("id") int id){
		schoolService.del(school);        //schoolService.del(id)
		return "forward:schoolall";
	}
	@RequestMapping("/selectById")
	public ModelAndView selectById(@Param("id") Integer id) {
		ModelAndView mav = new ModelAndView("toSel");
		List<School> li=schoolService.selectById(id);
		mav.addObject("l",li); //“l”对应toSel.jsp中<c:forEach>标签的items="${l}"
		return mav;
	}
	
	@RequestMapping("/toUpd")
	public String toUpd(School school) {
		schoolService.upd(school);
		return "forward:schoolall";
		
	}
}

6)jsp页面:
page01.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增学校</title>
</head>
<body>
<div>
<label style="color: red;">${msg}</label>
<form action="schooladd" method="post">
	<label>校名:</label><input name="name"><br/>
	<label>人数:</label><input name="persons"><br/>
	<input type="submit" value="新增学校">
</form>
</div>
</body>
</html>

page02.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>学校列表</title>
</head>
<body>
<div>
<h2>学校列表</h2>
<h6><a href="schoolall">刷新</a></h6>

<table border="1">
<tr>
	<th>序号</th>
	<th>校名</th>
	<th>人数</th>
	<th>操作</th>
</tr>
<c:forEach items="${schools }" var="s">
	<tr>
		<td align="center">${s.id }</td>
		<td align="center">${s.name }</td>
		<td align="center">${s.persons }</td>
		<td align="center"><input type="button" value="删除"  onclick="toDel(${s.id})"/></td>		
	</tr>
</c:forEach>
</table>
<form action="selectById" method="post">
<table>
<tr>
<td>
请输入要查找的序号:<input type="text" name="id"></td>
<td>
<input type="submit" value="查找">     <!--   -->
</td>
</tr>
</table>
<a href="page01.jsp">新增学校</a>
</form>
</div>
</body>
</html>
<script>
function toDel(id){
	location.href="del?id="+id;
}
</script>

toSel.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
        <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="toUpd" method="get">
<table border="0">
<tr>
	<td>序号</td>
	<td>校名</td>
	<td>人数</td>
	<td>操作</td>
</tr>
<c:forEach items="${l}" var="l">
	<tr>
		<td align="center"><input type="text" value="${l.id }" name="id" disabled="disabled"><input type="hidden" name="id" value="${l.id }"/></td>
		<td align="center"><input type="text" value="${l.name }" name="name"></td>
		<td align="center"><input type="text" value="${l.persons}" name="persons"> </td>
		<td align="center"><input type="submit" value="修改" />
	</tr>
</c:forEach>
</table>
</form>
</body>
</html>


上一篇–MyBatis采用XML方式


本文链接: http://www.dtmao.cc/news_show_100439.shtml

附件下载

相关教程

    暂无相关的数据...

共有条评论 网友评论

验证码: 看不清楚?