一、环境搭建
1.1添加依赖包,可以通过properties统一框架版本
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<springversion>5.0.8.RELEASE</springversion>
</properties>
<dependencies>
<!-- 加入ServletAPI -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- MySQL依赖 start -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- 加入MyBatis 依赖 start -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!-- 引入Spring(包含SpringMVC) 依赖 start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${springversion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springversion}</version>
</dependency>
<!-- 引用插件依赖:MyBatis整合Spring,如果mybatis版本在3.4及以上版本
mybatis-spring的版本要在1.3以上 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 德鲁伊数据连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<!-- pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
<!--处理json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<!--javaee-->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!--文件上传下载-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- 分页依赖包-->
</dependencies>
1.2.添加spring配置文件,ssm中可以省略mybatis.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
<!-- 1.配置数据源-->
<bean id="db" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/books?useUnicode=true&characterEncoding=utf-8"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!--2.创建sqlSessionFactory-->
<bean id="fac" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="db"></property>
<property name="configLocation" value="classpath:mybatis.xml"></property> <!--指定mybatis的配置文件路径-->
<property name="mapperLocations" value="classpath:mapper/*.xml"></property><!--指定mybatis的mapper文件路径-->
</bean>
<!--3.创建SqlSessionTemplate,没无参构造-->
<bean class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="fac"></constructor-arg>
</bean>
<!--4.配置事务-->
<bean id="mytx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="db"></property>
</bean>
<tx:annotation-driven transaction-manager="mytx"></tx:annotation-driven>
<!--5.启用springmvc注解-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--6.配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"></property>
</bean>
<!--7.扫描注解包-->
<context:component-scan base-package="com.xzk"></context:component-scan>
<!--8.配置静态资源访问-->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
或者:
<mvc:resources mapping="/css/**" location="/css/"></mvc:resources>
<mvc:resources mapping="/dtree/**" location="/dtree/"></mvc:resources>
<mvc:resources mapping="/Images/**" location="/Images/"> </mvc:resources>
<mvc:resources mapping="/img/**" location="/img/"></mvc:resources>
<mvc:resources mapping="/Script/**" location="/Script/"> </mvc:resources>
<mvc:resources mapping="/Style/**" location="/Style/"></mvc:resources>
</beans>
1.3配置web.xml文件,同时加载spring配置文件
<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_2_5.xsd" version="2.5">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>ssm1</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ssm1</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 处理post乱码-->
<filter>
<filter-name>bb</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>bb</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
1.4创建数据表,添加项目包结构,包括实体类等
给dao,service,web包下使用注解创建对象,给service,web中的属性注入对象
1.4.1表
1.4.2ssm结构
1.4.3实体类
package com.xzk.bean;
import java.sql.Date;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 16:12
* @Modified By:
*/
public class Books {
private int bookId;
private String bookName;
private int issuedCount;
private Date issuedDate;
private int bookStatus;
public Books() {
}
public Books(int bookId, String bookName, int issuedCount, Date issuedDate, int bookStatus) {
this.bookId = bookId;
this.bookName = bookName;
this.issuedCount = issuedCount;
this.issuedDate = issuedDate;
this.bookStatus = bookStatus;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getIssuedCount() {
return issuedCount;
}
public void setIssuedCount(int issuedCount) {
this.issuedCount = issuedCount;
}
public Date getIssuedDate() {
return issuedDate;
}
public void setIssuedDate(Date issuedDate) {
this.issuedDate = issuedDate;
}
public int getBookStatus() {
return bookStatus;
}
public void setBookStatus(int bookStatus) {
this.bookStatus = bookStatus;
}
}
1.4.4 daoimpl实现和dao接口
package com.xzk.dao;
import com.xzk.bean.Books;
import java.util.List;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 16:16
* @Modified By:
*/
public interface BooksDao {
/**
* 获得所以图书信息
* @return 图书集合
*/
List<Books> getAllBooks();
}
package com.xzk.dao.impl;
import com.xzk.bean.Books;
import com.xzk.dao.BooksDao;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 16:16
* @Modified By:
*/
@Repository
public class BooksDaoImpl implements BooksDao {
/**
* 改对象来源于配置文件
*/
@Resource
private SqlSessionTemplate sqlSessionTemplate;
/**
* 获得所以图书信息
*
* @return 图书集合
*/
@Override
public List<Books> getAllBooks() {
return sqlSessionTemplate.selectList("com.xzk.dao.BooksDao.getAllBooks");
}
}
1.4.5service层
使用的注解:@Service ,@AutoWired
接口
package com.xzk.service;
import com.xzk.bean.Books;
import java.util.List;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 16:16
* @Modified By:
*/
public interface BooksService {
/**
* 获得所以图书信息
* @return 图书集合
*/
public List<Books> getAllBooks();
}
实现
package com.xzk.service.impl;
import com.xzk.bean.Books;
import com.xzk.dao.BooksDao;
import com.xzk.service.BooksService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 16:22
* @Modified By:
*/
@Service
public class BooksServiceImpl implements BooksService {
@Resource
BooksDao booksDao;
/**
* 获得所以图书信息
*
* @return 图书集合
*/
@Override
public List<Books> getAllBooks() {
return booksDao.getAllBooks();
}
}
1.4.6 web层
使用的注解:@Controller,@RequestMapping,@AutoWired,@Qualififier(“empBiz”)
package com.xzk.web;
import com.xzk.bean.Books;
import com.xzk.service.BooksService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.nio.channels.FileChannel;
import java.util.List;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 16:24
* @Modified By:
*/
@Controller
public class BooksController {
@Resource
private BooksService booksService;
//匹配请求调取service方法
@RequestMapping("/getAllBooks")
public String getAllBooks(ModelMap map){
List<Books> allBooks = booksService.getAllBooks();
map.addAttribute("bookslist",allBooks);
return "show";
}
}
1.4.7 jsp页面等视图
<html>
<body>
<h2>Hello World!</h2>
<a href="/getAllBooks">getall</a>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/10/22
Time: 17:36
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>show.jsp</h1>
<c:forEach items="${bookslist}" var="book">
${book.bookId}--${book.bookName}
</c:forEach>
</body>
</html>
1.5省略dao的实现类(使用MapperScannerConfifigurer替代SqlSessionTemplate)
dao 层只定义接口,由小树叶创建dao层对象以及扫描mapper文件
注:当添加了spring-jdbc的jar包后,会自动提交事务 .
<!--3.创建SMapperScannerConfigurer,用于省略dao的实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
<property name="sqlSessionFactoryBeanName" value="fac"></property>
<!-- 接口所在位置-->
<property name="basePackage" value="com.xzk.dao"></property>
</bean>
注意:此时也可以测试使用属性文件的方式来加载数据源(支持属性文件链接数据源)
二、 mybatis反向生成工具
2.1添加依赖包
<!-- mybatis反向生成工具依赖包-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
2.2 加载插件:
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<!--配置文件的路径-->
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>
</plugin>
2.3修改配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<!--数据库驱动jar -->
<classPathEntry
location="F:\yhp\jar\mysql驱动\mysql-connector-java-5.0.8-bin.jar" />
<context id="MyBatis" targetRuntime="MyBatis3">
<!--去除注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/chaoshi"
userId="root"
password="123456">
</jdbcConnection>
<!--生成实体类 指定包名 以及生成的地址 (可以自定义地址,但是路径不存在不会自动创建
使用Maven生成在target目录下,会自动创建) -->
<javaModelGenerator targetPackage="com.yhp.bean"
targetProject="F:\yhp\three\workspace\mybatis_001\src\main\java">
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--生成SQLmapper文件 -->
<sqlMapGenerator targetPackage="mapper"
targetProject="F:\yhp\three\workspace\mybatis_001\src\main\resources">
</sqlMapGenerator>
<!--生成Dao文件,生成接口 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.yhp.dao"
targetProject="F:\yhp\three\workspace\mybatis_001\src\main\java">
</javaClientGenerator>
<table tableName="student" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false">
</table>
<table tableName="grade" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false">
</table>
<table tableName="subject" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
local——repository里的地址就是本地仓库的地址,在这1找数据库驱动jar地址
在下图idea的配置中写入mybatis-generator -e
三、训练项目代码
3.1数据库
-- ----------------------------
-- Table structure for bills
-- ----------------------------
DROP TABLE IF EXISTS `bills`;
CREATE TABLE `bills` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`billtime` date NULL DEFAULT NULL,
`typeid` int(11) NULL DEFAULT NULL,
`price` double NULL DEFAULT NULL,
`explains` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of bills
-- ----------------------------
INSERT INTO `bills` VALUES (1, '快递费', '2020-10-06', 1, 66, '邮寄快递费用');
INSERT INTO `bills` VALUES (2, '快递费1', '2020-08-08', 1, 6, '邮寄快递费用');
INSERT INTO `bills` VALUES (3, '快递费2', '2020-10-08', 2, 6, '邮寄快递费用');
INSERT INTO `bills` VALUES (4, '快递费3', '2020-11-08', 2, 6, '邮寄快递费用');
INSERT INTO `bills` VALUES (5, '快递费4', '2020-12-08', 1, 6, '邮寄快递费用');
INSERT INTO `bills` VALUES (6, '卖狗肉', '2020-10-11', 2, 66, '好吃便宜');
-- ----------------------------
-- Table structure for billtype
-- ----------------------------
DROP TABLE IF EXISTS `billtype`;
CREATE TABLE `billtype` (
`id` int(11) NULL DEFAULT NULL,
`billname` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of billtype
-- ----------------------------
INSERT INTO `billtype` VALUES (1, '支出');
INSERT INTO `billtype` VALUES (2, '收入');
INSERT INTO `billtype` VALUES (3, '转账');
INSERT INTO `billtype` VALUES (4, '借出');
INSERT INTO `billtype` VALUES (5, '借入');
INSERT INTO `billtype` VALUES (6, '还入');
SET FOREIGN_KEY_CHECKS = 1;
3.2实体类
package com.xzk.bean;
import java.util.Date;
import java.util.Objects;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 22:43
* @Modified By:
*/
public class Bills {
private Integer id;
private String title;
private Date billTime;
private Integer typeId;
private Double price;
private String explains;
private BillType billType;
public Bills() {
}
public Bills(Integer id, String title, Date billTime, Integer typeId, Double price, String explains, BillType billType) {
this.id = id;
this.title = title;
this.billTime = billTime;
this.typeId = typeId;
this.price = price;
this.explains = explains;
this.billType = billType;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getBillTime() {
return billTime;
}
public void setBillTime(Date billTime) {
this.billTime = billTime;
}
public Integer getTypeId() {
return typeId;
}
public void setTypeId(Integer typeId) {
this.typeId = typeId;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getExplains() {
return explains;
}
public void setExplains(String explains) {
this.explains = explains;
}
public BillType getBillType() {
return billType;
}
public void setBillType(BillType billType) {
this.billType = billType;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bills bills = (Bills) o;
return Objects.equals(id, bills.id) &&
Objects.equals(title, bills.title) &&
Objects.equals(billTime, bills.billTime) &&
Objects.equals(typeId, bills.typeId) &&
Objects.equals(price, bills.price) &&
Objects.equals(explains, bills.explains) &&
Objects.equals(billType, bills.billType);
}
@Override
public int hashCode() {
return Objects.hash(id, title, billTime, typeId, price, explains, billType);
}
@Override
public String toString() {
return "Bills{" +
"id=" + id +
", title='" + title + '\'' +
", billTime=" + billTime +
", typeId=" + typeId +
", price=" + price +
", explains='" + explains + '\'' +
", billType=" + billType +
'}';
}
}
package com.xzk.bean;
import java.util.List;
import java.util.Objects;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 22:43
* @Modified By:
*/
public class BillType {
private Integer id;
private String billName;
private List<Bills> billsList;
public BillType() {
}
public BillType(Integer id, String billName, List<Bills> billsList) {
this.id = id;
this.billName = billName;
this.billsList = billsList;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBillName() {
return billName;
}
public void setBillName(String billName) {
this.billName = billName;
}
public List<Bills> getBillsList() {
return billsList;
}
public void setBillsList(List<Bills> billsList) {
this.billsList = billsList;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BillType billType = (BillType) o;
return Objects.equals(id, billType.id) &&
Objects.equals(billName, billType.billName) &&
Objects.equals(billsList, billType.billsList);
}
@Override
public int hashCode() {
return Objects.hash(id, billName, billsList);
}
@Override
public String toString() {
return "BillType{" +
"id=" + id +
", billName='" + billName + '\'' +
", billsList=" + billsList +
'}';
}
}
3.3dao
package com.xzk.dao;
import com.xzk.bean.Bills;
import java.util.List;
import java.util.Map;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 23:04
* @Modified By:
*/
public interface BillsMapper {
/**
* 更新
*
* @param record
* @return
*/
int updateByPrimaryKey(Bills record);
/**
* 获取所有账单
*
* @param map
* @return 账单集合
*/
List<Bills> selectBills(Map map);
/**
* @param record
* @return
*/
int insert(Bills record);
/**
* @param id
* @return
*/
Bills selectByPrimaryKey(Integer id);
/** 根据主键删除
* @param id
* @return
*/
int deleteByPrimaryKey(Integer id);
}
package com.xzk.dao;
import com.xzk.bean.BillType;
import java.util.List;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 23:05
* @Modified By:
*/
public interface BillTypeMapper {
/**
* 获取所有账单类型
* @return 账单类型集合
*/
List<BillType> selectBillType();
}
<?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.xzk.dao.BillsMapper">
<resultMap id="rs1" type="Bills">
<id property="id" column="id" jdbcType="INTEGER"></id>
<result property="title" column="title" jdbcType="VARCHAR"></result>
<result property="billTime" column="billtime" jdbcType="DATE"></result>
<result property="typeId" column="typeid" jdbcType="INTEGER"></result>
<result property="price" column="price" jdbcType="DOUBLE"></result>
<result property="explains" column="explains" jdbcType="VARCHAR"></result>
<association property="billType" javaType="BillType">
<id property="id" column="id" jdbcType="INTEGER"></id>
<result property="billName" column="billname" jdbcType="VARCHAR"></result>
</association>
</resultMap>
<select id="selectBills" resultMap="rs1" parameterType="map">
SELECT * FROM bills b,billtype t WHERE b.typeid=t.id
<if test="typeId!=-1">
AND t.id=#{typeId}
</if>
<if test="begin!=null and begin!=''">
AND b.billtime>=#{begin}
</if>
<if test="end!=null and end!=''">
AND b.billtime <![CDATA[ <= ]]> #{end}
</if>
</select>
<insert id="insert" parameterType="Bills">
insert into bills (id, title, billtime,
typeid, price, explains
)
values (#{id,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{billTime,jdbcType=DATE},
#{typeId,jdbcType=INTEGER}, #{price,jdbcType=DOUBLE}, #{explains,jdbcType=VARCHAR}
)
</insert>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultType="Bills">
select *
from bills
where id = #{id,jdbcType=INTEGER}
</select>
<update id="updateByPrimaryKey" parameterType="com.xzk.bean.Bills">
update bills
set title = #{title,jdbcType=VARCHAR},
billtime = #{billTime,jdbcType=DATE},
typeid = #{typeId,jdbcType=INTEGER},
price = #{price,jdbcType=DOUBLE},
explains = #{explains,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from bills
where id = #{id,jdbcType=INTEGER}
</delete>
</mapper>
<?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.xzk.dao.BillTypeMapper">
<select id="selectBillType" resultType="BillType">
SELECT * FROM billType
</select>
</mapper>
3.4service
package com.xzk.service;
import com.github.pagehelper.PageInfo;
import com.xzk.bean.Bills;
import java.util.List;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 23:04
* @Modified By:
*/
public interface BillsService {
/**
* 更新
*
* @param record
* @return
*/
int updateByPrimaryKey(Bills record);
/**
* 获取所有账单
*
* @return 账单集合
*/
PageInfo<Bills> selectBills(int typeId, String begin, String end, int index, int size);
/**
* @param record
* @return
*/
int insert(Bills record);
Bills selectByPrimaryKey(Integer id);
/**
* 根据主键删除
*
* @param id
* @return
*/
int deleteByPrimaryKey(Integer id);
}
package com.xzk.service;
import com.xzk.bean.BillType;
import java.util.List;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 23:05
* @Modified By:
*/
public interface BillTypeService {
/**
* 获取所有账单类型
* @return 账单类型集合
*/
List<BillType> selectBillType();
}
package com.xzk.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzk.bean.Bills;
import com.xzk.dao.BillsMapper;
import com.xzk.service.BillsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 23:13
* @Modified By:
*/
@Service
public class BillsServiceImpl implements BillsService {
@Resource
private BillsMapper billsMapper;
/**
* @param record
* @return
*/
@Override
@Transactional
public int insert(Bills record) {
return billsMapper.insert(record);
}
/**
* 获取所有账单
*
* @return 账单集合
*/
@Override
public PageInfo<Bills> selectBills(int typeId, String begin, String end, int index, int size) {
Map map = new HashMap();
map.put("typeId",typeId);
map.put("begin",begin);
map.put("end",end);
//指定分页数据
PageHelper.startPage(index,size);
//查询数据
List<Bills> billsList = billsMapper.selectBills(map);
//创建分页工具类
PageInfo<Bills> pageInfo = new PageInfo<>(billsList);
return pageInfo;
}
}
package com.xzk.service.impl;
import com.xzk.bean.BillType;
import com.xzk.dao.BillTypeMapper;
import com.xzk.service.BillTypeService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 23:14
* @Modified By:
*/
@Service
public class BillTypeServiceImpl implements BillTypeService {
@Resource
private BillTypeMapper billTypeMapper;
/**
* 获取所有账单类型
*
* @return 账单类型集合
*/
@Override
public List<BillType> selectBillType() {
return billTypeMapper.selectBillType();
}
}
3.5controller
package com.xzk.controller;
import com.github.pagehelper.PageInfo;
import com.xzk.bean.BillType;
import com.xzk.bean.Bills;
import com.xzk.service.BillTypeService;
import com.xzk.service.BillsService;
import com.xzk.util.PageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.ManagedBean;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-22 23:20
* @Modified By:
*/
@Controller
public class BillController {
@Resource
private BillTypeService billTypeService;
@Resource
private BillsService billsService;
@RequestMapping("/deleteById")
public void deleteById(int bid, HttpServletResponse response) {
int delete = billsService.deleteByPrimaryKey(bid);
response.setContentType("text/html;charset=utf-8");
try {
PrintWriter writer = response.getWriter();
if (delete > 0){
writer.println("<script>alert('删除成功');location.href='/gettypes'</script>");
return;
}else {
writer.println("<script>alert('删除成功');location.href='/gettypes'</script>");
}
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping("/updateBill")
public String updateBills(Bills bills) {
int update = billsService.updateByPrimaryKey(bills);
if (update > 0) {
return "redirect:/gettypes";
}
return "redirect:/findById?bid=" + bills.getId();
}
@RequestMapping("/findById")
public String findById(int bid, ModelMap map) {
Bills bills = billsService.selectByPrimaryKey(bid);
map.addAttribute("bills", bills);
List<BillType> types = billTypeService.selectBillType();
map.addAttribute("types", types);
return "update";
}
@RequestMapping("/insertBill")
public String insertBill(Bills bills) {
int insert = billsService.insert(bills);
if (insert > 0) {
return "redirect:/gettypes";
}
return "redirect:/getBillType";
}
@RequestMapping("/getBillType")
public String getBillType(ModelMap map) {
List<BillType> billTypes = billTypeService.selectBillType();
map.addAttribute("types", billTypes);
return "add";
}
@RequestMapping("/gettypes")
public String getTypes(ModelMap map) {
PageInfo<Bills> billsList = billsService.selectBills(-1, null, null, 1, PageUtil.PAGESIZE);
List<BillType> billTypeList = billTypeService.selectBillType();
map.addAttribute("info", billsList);
map.addAttribute("billTypeList", billTypeList);
return "show";
}
@RequestMapping("/getAllBills")
public String getAllBills(@RequestParam(defaultValue = "1") Integer index, @RequestParam(defaultValue = "-1") Integer typeId, String begin, String end, ModelMap map) {
PageInfo<Bills> billsPageInfo = billsService.selectBills(typeId, begin, end, index, PageUtil.PAGESIZE);
map.addAttribute("info", billsPageInfo);
List<BillType> billTypeList = billTypeService.selectBillType();
map.addAttribute("billTypeList", billTypeList);
//数据回显
//将模糊查询的值再返回给前台
map.addAttribute("tid", typeId);
map.addAttribute("beginTime", begin);
map.addAttribute("endTime", end);
return "show";
}
}
3.6util
package com.xzk.util;
/**
* @Author: 森哥
* @Description:
* @Date Created in 2020-10-23 17:55
* @Modified By:
*/
public interface PageUtil {
public int PAGESIZE=3;
}
3.7jsp
3.7.1添加
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/10/23
Time: 18:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>记账</h1>
<form action="/insertBill" method="post">
<p>类型:
<c:forEach items="${types}" var="type">
<input type="radio" value="${type.id}" name="typeId">${type.billName}
</c:forEach>
</p>
</p>标题 <input type="text" style="width: 500px" name="title"><p>
<p>日期:<input type="text" name="billTime">金额:<input type="text" name="price"> </p>
<p>说明:<textarea cols="50" rows="4" name="explains"></textarea> </p>
<input type="reset" value="重置">
<input type="submit" value="保存">
</form>
</body>
</html>
3.7.2主页
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/10/22
Time: 23:25
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>记账管理</h1>
<p>
<form action="/getAllBills" method="post">
类型:
<select name="typeId">
<option value="-1">不限</option>
<c:forEach items="${billTypeList}" var="type">
<option value="${type.id}" ${tid==type.id?'selected':''}>${type.billName}</option>
</c:forEach>
</select>
时间:
从<input type="text" name="begin" value="${beginTime}">到<input type="text" name="end" value="${endTime}">
<input type="submit" value="搜索">
</form>
<input type="button" value="记账" onclick="javascript:location.href='/getBillType'">
</p>
<table border="1" width="500">
<tr>
<td>标题</td>
<td>时间</td>
<td>类别</td>
<td>金额</td>
<td>说明</td>
<td>操作</td>
</tr>
<c:if test="${info.list.size()>0}">
<c:forEach items="${info.list}" var="bill">
<tr>
<td>${bill.title}</td>
<td><fmt:formatDate value="${bill.billTime}" pattern="yyyy-MM-dd"></fmt:formatDate></td>
<td>${bill.billType.billName}</td>
<td>
<c:choose>
<c:when test="${bill.billType.billName=='支出' || bill.billType.billName=='借出' || bill.billType.billName=='还出'}">
-${bill.price}
</c:when>
<c:when test="${bill.billType.billName=='收入' || bill.billType.billName=='借入' || bill.billType.billName=='还入'}">
+${bill.price}
</c:when>
<c:otherwise>
${bill.price}
</c:otherwise>
</c:choose>
</td>
<td>${bill.explains}</td>
<td>
<a href="/deleteById?bid=${bill.id}">删除</a>
<a href="/findById?bid=${bill.id}">修改</a></td>
</tr>
</c:forEach>
</c:if>
<c:if test="${info.list.size()==0}">
<tr>
<td colspan="6">
<h3>没有找到任何数据</h3>
</td>
</tr>
</c:if>
<tr>
<td colspan="6">
<a href="/getAllBills?typeId=${tid}&beginTime=${beginTime}&endTime=${endTime}">首页</a>
<a href="/getAllBills?index=${info.prePage==0?1:info.prePage}&typeId=${tid}&beginTime=${beginTime}&endTime=${endTime}">上一页</a>
<a href="/getAllBills?index=${info.nextPage==0?info.pages:info.nextPage}&typeId=${tid}&beginTime=${beginTime}&endTime=${endTime}">下一页</a>
<a href="/getAllBills?index=${info.pages}&typeId=${tid}&beginTime=${beginTime}&endTime=${endTime}">尾页</a>
总页数:${info.pages}
总条数:${info.total}
</td>
</tr>
</table>
</body>
</html>
3.7.3修改
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/10/23
Time: 20:03
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>记账</h1>
<form action="/updateBill" method="post">
<input type="hidden" name="id" value="${bills.id}">
<p>类型:
<c:forEach items="${types}" var="type">
<input type="radio" value="${type.id}" ${type.id==bills.typeId?'checked':''} name="typeId">${type.billName}
</c:forEach>
</p>
</p>标题 <input type="text" style="width: 500px" name="title" value="${bills.title}"><p>
<p>日期:<input type="text" name="billTime" value="<fmt:formatDate value="${bills.billTime}" pattern="yyyy/MM/dd"></fmt:formatDate>">
金额:<input type="text" name="price" value="${bills.price}"> </p>
<p>说明:<textarea cols="50" rows="4" name="explains">${bills.explains}</textarea> </p>
<input type="reset" value="重置">
<input type="submit" value="保存">
</form>
</body>
</html>