idea+spring4+springmvc+mybatis+maven实现简单增删改查CRUD
在学习spring4+springmvc+mybatis的ssm框架,idea整合简单实现增删改查功能,在这里记录一下。
原文在这里:https://my.oschina.net/finchxu/blog/3007984
工作环境:
- Windows 10
- jdk8(1.8)
- IntelliJ IDEA
- spring 4 和 springMVC
- MySQL 5.7
- maven 3.3
- mybatis 3.4
- DBCP
- Tomcat 8.5
项目上传到了Github方便查看:https://github.com/finch-xu/springbook 有用的话欢迎加星。
页面演示:
首先新建项目
如图所示新建maven的webapp
建数据库和数据表
CREATE DATABASE books;
CREATE TABLE `bookadmin` (
`bid` int(11) NOT NULL AUTO_INCREMENT,
`bn` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`author` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`press` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`bid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
这里是项目目录结构
springbook
├── src
│ └── main
│ ├── java
│ │ └── cn
│ │ └── book
│ │ ├── controller
│ │ │ └── BooksController.java
│ │ ├── mapper
│ │ │ ├── BooksMapper.java
│ │ │ └── BooksMapper.xml
│ │ ├── pojo
│ │ │ └── Bookadmin.java
│ │ └── service
│ │ ├── BooksServiceImpl.java
│ │ └── BooksService.java
│ ├── resources
│ │ ├── applicationContext-dao.xml
│ │ ├── applicationContext-service.xml
│ │ ├── applicationContext-trans.xml
│ │ ├── jdbc.properties
│ │ ├── log4j.properties
│ │ ├── spring-mvc.xml
│ │ └── sqlMapConfig.xml
│ └── webapp
│ ├── index.jsp
│ └── WEB-INF
│ ├── jsp
│ │ ├── listBooks.jsp
│ │ ├── savepage.jsp
│ │ └── updatepage.jsp
│ └── web.xml
pom.xml 找不到的包可以去https://mvnrepository.com/ 这里找,很方便的。
<?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>cn.book</groupId>
<artifactId>spring</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!--<maven.compiler.source>1.8</maven.compiler.source>-->
<!--<maven.compiler.target>1.8</maven.compiler.target>-->
<spring.version>4.3.19.RELEASE</spring.version>
<validator.version>5.2.4.Final</validator.version>
<slf4j.version>1.7.7</slf4j.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
<commons-io.version>2.4</commons-io.version>
<commons-codec.version>1.9</commons-codec.version>
<commons-fileupload.version>1.3.1</commons-fileupload.version>
<commons-beanutils.version>1.9.1</commons-beanutils.version>
</properties>
<dependencies>
<!-- WEB begin -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<!--<scope>provided</scope>-->
</dependency>
<!-- WEB end -->
<!-- SPRING begin -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.esotericsoftware.reflectasm</groupId>
<artifactId>reflectasm</artifactId>
<version>1.09</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- bean validate -->
<!--<dependency>-->
<!--<groupId>org.hibernate</groupId>-->
<!--<artifactId>hibernate-validator</artifactId>-->
<!--<version>${validator.version}</version>-->
<!--</dependency>-->
<!-- SPRING end -->
<!-- AOP begin -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
<!-- AOP end -->
<!-- TEST begin -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- TEST end -->
<!-- LOGGING begin -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- common-logging 实际调用slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- java.util.logging 实际调用slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- LOGGING end -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>${commons-beanutils.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<maxmem>256M</maxmem>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-idea-plugin</artifactId>
<version>2.2</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4.3</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<filesets>
<fileset>
<directory>activemq-data</directory>
</fileset>
</filesets>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.3.1</version>
</plugin>
<plugin>
<artifactId>maven-remote-resources-plugin</artifactId>
<version>1.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.5</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>2.6</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.1.1</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<childDelegation>false</childDelegation>
<useFile>true</useFile>
<failIfNoTests>false</failIfNoTests>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
一定要注意这段内容,在maven打包war时扫描这些xml文件
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
resources
applicationContext-dao.xml 用的dbcp连接池。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 数据库连接池 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 连接池的最大数据库连接数 -->
<property name="maxActive" value="${jdbc.maxActive}" />
<!-- 最大空闲数 -->
<property name="maxIdle" value="${jdbc.maxIdle}" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis核心配置文件 -->
<property name="configLocation" value="classpath:sqlMapConfig.xml" />
<!-- 别名包扫描 -->
<property name="typeAliasesPackage" value="cn.book.pojo" />
</bean>
<!-- 动态代理,第二种方式:包扫描(推荐): -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- basePackage多个包用","分隔 -->
<property name="basePackage" value="cn.book.mapper" />
</bean>
</beans>
applicationContext-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- @Service包扫描器 -->
<context:component-scan base-package="cn.book.service"/>
</beans>
applicationContext-trans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
<tx:method name="query*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!--<!– 切面 –>-->
<!--<aop:config>-->
<!--<aop:advisor advice-ref="txAdvice"-->
<!--pointcut="execution(* cn.book.service.*.*(..))" />-->
<!--</aop:config>-->
</beans>
jdbc.properties 这里要注意应定要加上“jdbc.”的前缀。我用的是mysql5.7所以driver直接这么写就行,如果是mysql6及以上的就不一样了,具体百度吧。
如果遇到什么时区问题,记得在url后边再加上时区设置就行了。
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/books?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=12345678
jdbc.maxActive=10
jdbc.maxIdle=5
spring-mvc.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配置@controller扫描包 -->
<!--<context:component-scan base-package="cn.book.controller" />-->
<context:annotation-config/>
<context:component-scan base-package="cn.book.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置注解驱动,相当于同时使用最新处理器映射跟处理器适配器,对json数据响应提供支持 -->
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
sqlMapConfig.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>
</configuration>
web.xml 这里的最后一部分(有注释的那里)写的是/而不是/*,因为用了后者就把jsp也当静态文件了,访问页面直接显示源代码而不是解析jsp。
<?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">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
<!-- 使用监听器加载Spring配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 解决post乱码问题 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 设置编码参是UTF8 -->
<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>
<!-- 前端控制器 -->
<servlet>
<servlet-name>springmvc-web</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>
</servlet>
<servlet-mapping>
<servlet-name>springmvc-web</servlet-name>
<url-pattern>/</url-pattern><!--这里写的是/而不是/*,因为用了后者就把jsp也当静态文件了-->
</servlet-mapping>
</web-app>
然后就是代码:
Mapper部分:
BooksMapper.xml
<?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="cn.book.mapper.BooksMapper">
<sql id="BASE_TABLE">
bookadmin
</sql>
<sql id="BASE_COLUMN">
bid,bn,author,press
</sql>
<!--<resultMap id="BaseResultMap" type="cn.book.pojo.Bookadmin">-->
<!--<id column="bid" property="bid" jdbcType="INTEGER" />-->
<!--<result column="bn" property="bn" jdbcType="VARCHAR" />-->
<!--<result column="author" property="author" jdbcType="VARCHAR" />-->
<!--<result column="press" property="press" jdbcType="VARCHAR" />-->
<!--</resultMap>-->
<insert id="insert" parameterType="Bookadmin">
INSERT INTO
<include refid="BASE_TABLE"/>
<trim prefix="(" suffix=")" suffixOverrides=",">
bn,author,
<if test="press != null">
press,
</if>
</trim>
<trim prefix="VALUES(" suffix=")" suffixOverrides=",">
#{bn,jdbcType=VARCHAR},#{author,jdbcType=VARCHAR},
<if test="press != null">
#{press,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="getBookByBid" resultType="Bookadmin">
select bid,bn,author,press from bookadmin where bid = #{bid}
</select>
<select id="list" resultType="Bookadmin">
select * from bookadmin
</select>
<update id="update" parameterType="Bookadmin">
update
<include refid="BASE_TABLE"/>
set bn = #{bn},author = #{author},press = #{press}
where bid = #{bid}
</update>
<delete id="delete" parameterType="Bookadmin">
delete
from
<include refid="BASE_TABLE"/>
where bid = #{bid}
</delete>
<!--resultType="Bookadmin"-->
</mapper>
BooksMapper.java
package cn.book.mapper;
import cn.book.pojo.Bookadmin;
import java.util.List;
public interface BooksMapper{
List<Bookadmin> list();
int insert(Bookadmin record);
int update(Bookadmin b);
int delete(Bookadmin bid);
Bookadmin getBookByBid(Integer bid);
}
POJO实体
Bookadmin.java
package cn.book.pojo;
public class Bookadmin {
Integer bid;
String bn;
String author;
String press;
public Integer getBid() {
return bid;
}
public void setBid(Integer bid) {
this.bid = bid;
}
public String getBn() {
return bn;
}
public void setBn(String bn) {
this.bn = bn;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPress() {
return press;
}
public void setPress(String press) {
this.press = press;
}
}
service部分
BooksService.java
package cn.book.service;
import cn.book.pojo.Bookadmin;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface BooksService {
List<Bookadmin> list();
int insertBook(Bookadmin bookadmin);
int update(Bookadmin b);
int deleteBookByBid(Bookadmin bid);
Bookadmin getBookByBid(int bid);
}
BooksServiceImpl.java
package cn.book.service;
import cn.book.mapper.BooksMapper;
import cn.book.pojo.Bookadmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BooksServiceImpl implements BooksService {
@Autowired
private BooksMapper booksMapper;
// 列出数据
@Override
public List<Bookadmin> list(){
List<Bookadmin> list = this.booksMapper.list();
return list;
}
// 插入数据
@Override
public int insertBook(Bookadmin bookadmin){
return booksMapper.insert(bookadmin);
}
// 更新数据
@Override
public int update(Bookadmin b){
return booksMapper.update(b);
}
// 删除数据
@Override
public int deleteBookByBid(Bookadmin bid){
return booksMapper.delete(bid);
}
@Override
public Bookadmin getBookByBid(int bid){
return booksMapper.getBookByBid(bid);
}
}
Controller部分
BooksController.java
package cn.book.controller;
import cn.book.pojo.Bookadmin;
import cn.book.service.BooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
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.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("/a")
public class BooksController {
@Autowired
BooksService booksService;
//列出数据表格
// 设置listBooks页面(list第一种写法)
@RequestMapping("/listBooks")
public ModelAndView listBooks(){
ModelAndView mav = new ModelAndView();
List<Bookadmin> bb = booksService.list();
mav.addObject("bb",bb);
mav.setViewName("listBooks");
return mav;
}
// list的第二种写法
// @RequestMapping("/listBooks")
// public String listBooks(Model model){
// List<Bookadmin> bb = booksService.list();
// model.addAttribute("bb",bb);
// return "listBooks";
// }
// 添加数据(两部分)
// 第一步:跳转到这里并添加图书信息,点击添加按钮就执行下边第二段代码
@RequestMapping("/addBooks0")
public String addBooks0(){
return "savepage";
}
// 第二步:把下边的页面数据返回给后端,再跳转到listBooks页面
@RequestMapping(value = "/addBooks",method = RequestMethod.POST)
public String addBooks(Bookadmin bookadmin){
booksService.insertBook(bookadmin);
return "redirect:listBooks";
}
// 修改数据(两部分)
// 第一步:更新图书,先通过bid找到图书,并列在/updatepage/{bid}页面上,
@RequestMapping("/updatepage/{bid}")
public String updatepage(@PathVariable("bid") int bid,Model model){
model.addAttribute("bookadmin",booksService.getBookByBid(bid));
return "updatepage";
}
// 第二步:然后修改即可,在这里点更新提交数据给后端
@RequestMapping(value = "/update",method = RequestMethod.POST)
public String update(Bookadmin b){
booksService.update(b);
return "redirect:listBooks";
}
// 删除图书数据
@RequestMapping("/deleteBooksByBid")
public String deleteBooksByBid(Bookadmin bid){
booksService.deleteBookByBid(bid);
return "redirect:listBooks";
}
}
JSP页面
listBooks.jsp 列出所有的图书信息(并且包含添加、修改和删除的功能按钮)
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--^^^^^添加对jstl列表的支持^^^^^--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>listBooks</title>
</head>
<body>
<form>
<table align="center" bgcolor="aqua" border="1" cellpadding="0">
<tr>
<th width="140">图书BID</th>
<th width="140">书名</th>
<th width="140">作者</th>
<th width="140">出版社</th>
<th width="140">修改</th>
<th width="140">删除</th>
</tr>
<c:forEach items="${bb}" var="b"> <%--varStatus="ct"--%>
<tr>
<td>${b.bid}</td>
<td>${b.bn}</td>
<td>${b.author}</td>
<td>${b.press}</td>
<td><a href="${pageContext.request.contextPath}/a/updatepage/${b.bid}">修改</a></td>
<td><a href="${pageContext.request.contextPath}/a/deleteBooksByBid?bid=${b.bid}" onclick='return confirm("确认要删除吗?")'>删除</a></td>
</tr>
</c:forEach>
<%--<td><a href="${pageContext.request.contextPath}/a/addBooks0">添加图书(跳转页面)</a></td>--%>
</table>
</form>
<form id="saveForm" action="${pageContext.request.contextPath}/a/addBooks" method="post">
<table align="center" bgcolor="aqua" border="1" cellpadding="0">
<tr>
<th width="140">书名</th>
<th width="140">作者</th>
<th width="140">出版社</th>
</tr>
<tr>
<td width="140"><input type="text" value="${bookadmin.bn}" name="bn"/></td>
<td width="140"><input type="text" value="${bookadmin.author}" name="author"/></td>
<td width="140"><input type="text" value="${bookadmin.press}" name="press" /></td>
<td width="140"><input type="submit" value="添加" /></td>
</tr>
</table>
</form>
</body>
</html>
savepage.jsp 添加图书并返回到上边的列表页面
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加图书</title>
</head>
<body>
<br/>
<form id="saveForm" action="${pageContext.request.contextPath}/a/addBooks" method="post">
<table align="center" bgcolor="aqua" border="1" cellpadding="0">
<tr>
<td>书名:</td>
<td><input type="text" value="${bookadmin.bn}" name="bn"/></td>
</tr>
<tr>
<td>作者:</td>
<td><input type="text" value="${bookadmin.author}" name="author"/></td>
</tr>
<tr>
<td>出版社:</td>
<td><input type="text" value="${bookadmin.press}" name="press" /></td>
</tr>
<input type="submit" value="添加" />
</table>
</form>
</body>
</html>
updatepage.jsp 更新和修改图书信息
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>更新&修改 图书信息</title>
</head>
<body>
<h2>编辑图书信息!</h2>
<form id="updateForm" action="${pageContext.request.contextPath}/a/update" method="post">
<input type="hidden" value="${bookadmin.bid}" name="bid"/>
<table align="center" bgcolor="aqua" border="1" cellpadding="0">
<tr>
<td>书名:</td>
<td><input type="text" value="${bookadmin.bn}" name="bn"/></td>
</tr>
<tr>
<td>作者:</td>
<td><input type="text" value="${bookadmin.author}" name="author"/></td>
</tr>
<tr>
<td>出版社:</td>
<td><input type="text" value="${bookadmin.press}" name="press"/></td>
</tr>
<input type="submit" value="更新" />
</table>
</form>
</body>
</html>
然后可以在idea里开一个tomcat来启动项目,实现简单的增删改查功能。
访问http://localhost:8080/springbook_war_exploded/a/listBooks就得到页面:
项目上传到了Github方便查看:https://github.com/finch-xu/springbook 有用的话欢迎加星。
转载需注明本文地址:https://my.oschina.net/finchxu/blog/3007984
感谢:
controller的详细讲解:https://www.cnblogs.com/pophope/p/5619504.html
https://blog.csdn.net/Peng_Hong_fu/article/details/53536862
https://www.javatpoint.com/spring-mvc-crud-example
https://www.journaldev.com/3531/spring-mvc-hibernate-mysql-integration-crud-example-tutorial
idea+spring4+springmvc+mybatis+maven实现简单增删改查CRUD的更多相关文章
- MyBatis学习之简单增删改查操作、MyBatis存储过程、MyBatis分页、MyBatis一对一、MyBatis一对多
一.用到的实体类如下: Student.java package com.company.entity; import java.io.Serializable; import java.util.D ...
- maven+springMVC+mybatis+easyUI管理用户增删改查
1.项目演示图 2.项目简单介绍 项目分为两个projectdomain和manager.project结构例如以下图所看到的.当中domain是Maven javaproject主要完毕对数据库的操 ...
- Mybatis实现简单增删改查
Mybatis的简单应用 学习内容: 需求 环境准备 代码 总结: 学习内容: 需求 使用Mybatis实现简单增删改查(以下是在IDEA中实现的,其他开发工具中,代码一样) jar 包下载:http ...
- MyBatis学习系列二——增删改查
目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring 数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改, ...
- Mybatis实现数据的增删改查
Mybatis实现数据的增删改查 1.项目结构(使用maven创建项目) 2.App.java package com.GetcharZp.MyBatisStudy; import java.io.I ...
- ado.net的简单数据库操作(三)——简单增删改查的实际应用
果然,在犯困的时候就该写写博客,写博客就不困了,哈哈! 上篇我记录了自己的SqlHelper的开发过程,今天记录一下如何使用这个sqlhelper书写一个具有简单增删改查的小实例啦. 实例描述:在数据 ...
- Redis:五种数据类型的简单增删改查
Redis简单增删改查例子 例一:字符串的增删改查 #增加一个key为ay_key的值 127.0.0.1:6379> set ay_key "ay" OK #查询ay_ke ...
- 国产化之路-统信UOS + Nginx + Asp.Net MVC + EF Core 3.1 + 达梦DM8实现简单增删改查操作
专题目录 国产化之路-统信UOS操作系统安装 国产化之路-国产操作系统安装.net core 3.1 sdk 国产化之路-安装WEB服务器 国产化之路-安装达梦DM8数据库 国产化之路-统信UOS + ...
- IDEA SpringBoot-Mybatis-plus 实现增删改查(CRUD)
上一篇: IDEA SpringBoot-Mybatis实现增删改查(CRUD) 下一篇:Intellij IDEA 高效使用教程 (插件,实用技巧) 最好用的idea插件大全 一.前言 Mybati ...
随机推荐
- 简易的CSS下拉菜单 - 1
<!DOCTYPE html> <html> <head> <style> body{ margin:0; } .dropmenu{ backgroun ...
- 新版Eclipse找不到Java EE Module Dependencies选项
在 Eclipse Galileo (3.5) 版本或Ganymede (3.4) 等更老的版本中, 你可以使用Java EE Module Dependencies 选项来组织你的项目结构,确保依赖 ...
- Android PullToRefreshListView设置各个item之间的间距
要设置第三方的上拉下载listView的item之间的间距,可以在xml布局文件中的listView节点中设置xml的属性即可: android:divider="#00000000&quo ...
- 51nod 1096 距离之和最小 思维题,求中位数
题目: 在一条直线上,与两个点距离之和最小的点,是怎样的点? 很容易想到,所求的点在这两个已知点的中间,因为两点之间距离最短. 在一条直线上,与三个点距离之和最小的点,是怎样的点? 由两个点的规律,我 ...
- MySQL存储过程和自定义函数、Navicat for mysql、创建存储过程和函数、调用存储过程和函数的区别
1 MySQL存储过程和函数 过程和函数,它们被编译后保存在数据库中,称为持久性存储模块(Persistent Stored Module,PSM),可以反复调用,运行速度快. 1.1 存储过程 存储 ...
- swift学习笔记 - swift中常用关键字
swift中常用关键字 **用作声明的关键字: ** class.deinit.enum.extension.func.import.init.let.protocol.static.struct.s ...
- 《Unix环境高级编程》读书笔记 第3章-文件I/O
1. 引言 Unix系统的大多数文件I/O只需用到5个函数:open.read.write.lseek以及close 本章描述的函数经常被称为不带缓冲的I/O.术语不带缓冲指的是在用户的进程中对其不会 ...
- Python 曲线拟合
#曲线拟合 fig = plt.figure() ax = fig.add_subplot(111)#将画布分割成1行1列,图像画在从左到右从上到下的第1块 ax.plot(Num,a,label=u ...
- finger---用于查找并显示用户信息
finger finger命令用于查找并显示用户信息.包括本地与远端主机的用户皆可,帐号名称没有大小写的差别.单独执行finger指令,它会显示本地主机现在所有的用户的登陆信息,包括帐号名称,真实姓名 ...
- caioj 1158 欧拉函数
直接套模板,这道题貌似单独求还快一些 解法一 #include<cstdio> #include<cctype> #define REP(i, a, b) for(int i ...