原创转载请注明出处:http://agilestyle.iteye.com/blog/2377160
Project Directory
Maven Dependency
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.fool.ms</groupId> <artifactId>mybatis-spring</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>mybatis-spring Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.8.RELEASE</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.8.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.8.1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.5</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.42</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>8080</port> <path>/ms</path> </configuration> </plugin> </plugins> </build> </project>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <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>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
root-context.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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <context:component-scan base-package="org.fool.ms"/> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp.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> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="mapperLocations" value="classpath:org/fool/ms/dao/*.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="org.fool.ms.dao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven transaction-manager="txManager"/> </beans>
servlet-context.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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 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"> <mvc:annotation-driven/> <mvc:resources location="/resources/" mapping="/resources/**"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <context:component-scan base-package="org.fool.ms.controller"/> </beans>
src/main/resources
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> <settings> <setting name="cacheEnabled" value="true"/> <setting name="useGeneratedKeys" value="true"/> <setting name="defaultExecutorType" value="REUSE"/> <setting name="lazyLoadingEnabled" value="true"/> <setting name="defaultStatementTimeout" value="25000"/> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <typeAliases> <typeAlias type="org.fool.ms.domain.User" alias="user"/> </typeAliases> </configuration>
jdbc.properties
jdbc.databaseName=test jdbc.driverClassName = com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/${jdbc.databaseName}?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=123456
schema.sql
drop table if exists t_user; create table t_user ( id int(11) not null auto_increment, username varchar(20) not null, password varchar(20) not null, nickname varchar(20) not null, email varchar(30) not null, primary key(id) ); insert into t_user(username, password, nickname, email) values("mybatis", "mybatis", "mybatis", "mybatis@mvc.org"); insert into t_user(username, password, nickname, email) values("mybatis", "mybatis", "mybatis", "mybatis@mvc.org"); insert into t_user(username, password, nickname, email) values("mybatis", "mybatis", "mybatis", "mybatis@mvc.org"); insert into t_user(username, password, nickname, email) values("mybatis", "mybatis", "mybatis", "mybatis@mvc.org"); insert into t_user(username, password, nickname, email) values("mybatis", "mybatis", "mybatis", "mybatis@mvc.org");
src/main/java
User.java
package org.fool.ms.domain; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; public class User { private int id; private String username; private String password; private String nickname; private String email; public User() { } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
UserDAO.java
package org.fool.ms.dao; import org.fool.ms.domain.User; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserDAO { User getUser(int id); int deleteUser(int id); int insertUser(User user); int updateUser(User user); List<User> findUsers(); }
user.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="org.fool.ms.dao.UserDAO"> <select id="getUser" parameterType="int" resultType="user"> SELECT id, username, password, nickname, email FROM t_user WHERE id = #{id} </select> <delete id="deleteUser" parameterType="int"> DELETE FROM t_user WHERE id = #{id} </delete> <insert id="insertUser" parameterType="user"> INSERT INTO t_user(username, password, nickname, email) VALUES(#{username}, #{password}, #{nickname}, #{email}) </insert> <update id="updateUser" parameterType="user"> UPDATE t_user <set> <if test="username != null">username = #{username}, </if> <if test="password != null">password = #{password}, </if> <if test="nickname != null">nickname = #{nickname}, </if> <if test="email != null">email = #{email}</if> </set> WHERE id = #{id} </update> <select id="findUsers" resultType="user"> SELECT id, username, password, nickname, email FROM t_user </select> </mapper>
UserService.java
package org.fool.ms.service; import org.fool.ms.domain.User; import java.util.List; public interface UserService { User getUser(int id); int insertUser(User user); int deleteUser(int id); int updateUser(User user); List<User> findUsers(); }
UserServiceImpl.java
package org.fool.ms.service.impl; import org.fool.ms.dao.UserDAO; import org.fool.ms.domain.User; import org.fool.ms.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class UserSeviceImpl implements UserService { @Autowired private UserDAO userDAO; @Override @Transactional(propagation = Propagation.SUPPORTS) public User getUser(int id) { return this.userDAO.getUser(id); } @Override @Transactional(propagation = Propagation.REQUIRED) public int insertUser(User user) { return this.userDAO.insertUser(user); } @Override @Transactional(propagation = Propagation.REQUIRED) public int deleteUser(int id) { return this.userDAO.deleteUser(id); } @Override @Transactional(propagation = Propagation.REQUIRED) public int updateUser(User user) { return this.userDAO.updateUser(user); } @Override @Transactional(propagation = Propagation.SUPPORTS) public List<User> findUsers() { return this.userDAO.findUsers(); } }
UserController.java
package org.fool.ms.controller; import org.fool.ms.domain.User; import org.fool.ms.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") @ResponseBody public User getUser(@PathVariable int id) { return userService.getUser(id); } @GetMapping("/users") public String list(Model model) { model.addAttribute("users", userService.findUsers()); return "user/list"; } @GetMapping("/add") public String add(@ModelAttribute("user") User user, Model model) { return "user/add"; } @PostMapping("/add") public String add(@Validated User user, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return "user/add"; } userService.insertUser(user); return "redirect:/user/users"; } @GetMapping("/{id}/update") public String update(@PathVariable int id, Model model) { model.addAttribute("user", userService.getUser(id)); return "user/update"; } @PostMapping("/{id}/update") public String update(@PathVariable int id, @Validated User user, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return "user/update"; } userService.updateUser(user); return "redirect:/user/users"; } @GetMapping("/{id}/delete") public String delete(@PathVariable int id) { userService.deleteUser(id); return "redirect:/user/users"; } }
src/main/webapp
add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <head> <title>user add</title> </head> <body> <form:form method="post" modelAttribute="user"> <table width="800" align="center" border="1"> <tr> <td>username:</td> <td><form:input path="username"/> <form:errors path="username"/> </td> </tr> <tr> <td>password:</td> <td><form:password path="password"/> <form:errors path="password"/> </td> </tr> <tr> <td>nickname:</td> <td><form:input path="nickname"/> <form:errors path="nickname"/> </td> </tr> <tr> <td>email:</td> <td><form:input path="email"/> <form:errors path="email"/> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="add"/> </td> </tr> </table> </form:form> </body> </html>
list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>user list</title> </head> <body> <table width="700" align="center" border="1"> <c:forEach items="${users}" var="user"> <tr> <td><a href="${user.id }">${user.id}</a></td> <td>${user.username}</td> <td>${user.password}</td> <td>${user.nickname}</td> <td>${user.email}</td> <td> <a href="${user.id }/update">update</a> <a href="${user.id }/delete">delete</a> </td> </tr> </c:forEach> </table> </body> </html>
update.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <head> <title>user update</title> </head> <body> <form:form method="post" modelAttribute="user"> <table width="800" align="center" border="1"> <tr> <td>Username:</td> <td><form:input path="username" readonly="true"/></td> </tr> <tr> <td>Password:</td> <td><form:password path="password"/> <form:errors path="password"/> </td> </tr> <tr> <td>Nickname:</td> <td> <form:input path="nickname"/> <form:errors path="nickname"/> </td> </tr> <tr> <td>Email:</td> <td><form:input path="email"/> <form:errors path="email"/> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="update"/> </td> </tr> </table> </form:form> </body> </html>
index.jsp
<% response.sendRedirect("user/users"); %>
Test
tomcat7:run
http://localhost:8080/ms/user/users
http://localhost:8080/ms/user/1
http://localhost:8080/ms/user/2/update
http://localhost:8080/ms/user/2/delete
http://localhost:8080/ms/user/add
相关推荐
这个"SpringBoot+MybatisCRUD 整合案例"是为初学者设计的,旨在帮助他们快速掌握这两个流行的框架的结合使用。 首先,我们需要在项目中引入Spring Boot和MyBatis的依赖。在`pom.xml`文件中,我们需要添加以下Maven...
然后,配置Mybatis的SqlSessionFactory,定义Mapper接口和XML映射文件,实现数据的CRUD操作。接着,利用Spring MVC的DispatcherServlet、Controller和视图解析器,设定路由规则,处理HTTP请求,并返回相应的视图。在...
Spring 和 MyBatis 集成后,可以发挥各自的优势,Spring 负责业务逻辑的组织和管理,MyBatis 负责数据的CRUD操作。通常,我们会使用 Spring 的 DataSource、TransactionManager 配合 MyBatis 进行数据访问,实现事务...
这个接口通常会包含CRUD(Create, Read, Update, Delete)的基本方法,如`insert`, `update`, `delete`, `selectById`, `selectAll`等。这些方法可以通过Mybatis的注解或XML配置来绑定SQL语句。 2. **动态SQL**: ...
在IT行业中,Spring和MyBatis是两个非常重要的框架,它们分别用于企业级应用的依赖管理和持久层操作。Spring是一个全面的后端开发框架,它提供了IoC(Inversion of Control,控制反转)和AOP(Aspect Oriented ...
通过这个Demo,你可以学习如何将Spring MVC与MyBatis结合,实现CRUD(创建、读取、更新、删除)操作。例如,如何定义Mapper接口和XML映射文件,编写Controller处理HTTP请求,如何配置Spring MVC和MyBatis的整合,...
在IT行业中,SpringMyBatis框架的使用是构建高效、可维护性高的Web应用程序的关键技术之一。本项目“SpringMyBatis - 预约接种”显然涉及到的是使用这两个技术来开发一个预约接种服务,这可能是一个医疗信息化系统的...
**Spring整合Mybatis原理分析** 在Java Web开发中,Spring框架以其强大的依赖注入和面向切面编程能力,成为了事实上的核心框架。Mybatis则是一个轻量级的持久层框架,它简化了数据库操作,提供了直观的SQL映射。将...
Spring作为一款强大的轻量级框架,提供了依赖注入、AOP(面向切面编程)等功能,而MyBatis-Plus则是在MyBatis的基础上进行扩展,简化了常见的CRUD操作,提升了开发效率。下面我们将详细介绍如何将Spring与MyBatis-...
Spring MyBatis 模板是为初学者设计的一个基础项目框架,它整合了Spring和MyBatis两大流行框架,帮助开发者快速搭建一个可运行的Web应用。本文将深入讲解Spring MyBatis集成的关键知识点,包括Spring框架的核心概念...
Struts、Spring 和 MyBatis 是Java开发领域中三大著名框架,它们的组合常被称为SSM框架,用于构建高效、可扩展的企业级Web应用程序。在这个项目中,它们被用来实现一个基本的增删改查(CRUD)功能,这是任何数据库...
总结来说,"spring mybatis easyui"是一个基础的Java Web开发项目模板,它整合了Spring MVC的控制层、MyBatis的数据访问层和EasyUI的前端展示,实现了Web应用的常见功能,为快速搭建具有分页和CRUD功能的管理界面...
《SSM框架整合详解——基于spring-mybatis-struts2-master的实战分析》 在Java Web开发领域,SSM(Spring、Struts2、MyBatis)框架的组合被广泛使用,因其灵活性和强大的功能而备受青睐。本篇文章将深入探讨这个...
在本教程中,我们将一起探索如何创建并运行你的第一个MyBatis程序,实现CRUD(Create, Read, Update, Delete)操作。这些基本操作是数据库管理的核心,对于任何应用程序来说都是必不可少的。 首先,我们需要理解...
《Spring-MYBatis企业应用实战》是一本深入讲解如何在实际项目中集成并使用Spring和MyBatis框架的书籍。Spring是一个强大的Java应用程序框架,它提供了依赖注入、AOP(面向切面编程)、MVC(模型-视图-控制器)等...
3. 使用MyBatis的XML配置或注解方式编写SQL语句,处理CRUD操作。 4. 实现Spring MVC的拦截器,进行权限控制和日志记录。 5. 集成Spring Data JPA或MyBatis的Mapper,实现更高级的数据访问功能。 6. 整合Spring ...
8. **测试**:编写测试类,验证 Spring 和 MyBatis 的集成是否正常工作,确保 CRUD 操作无误。 通过这种集成方式,开发者可以充分利用 Spring 的依赖注入和事务管理,同时享受 MyBatis 的灵活 SQL 编写和映射。这种...
【自虐1.2】Spring+MyBatis完成CRUD 在本文中,我们将深入探讨如何结合Spring框架和MyBatis轻量级持久层框架来实现数据库的基本操作,包括创建(Create)、读取(Read)、更新(Update)和删除(Delete),简称为...
**MyBatis+Spring 整合 CRUD 操作详解** 在现代Java Web开发中,MyBatis和Spring框架的结合使用非常普遍,它们可以提供高效、灵活的持久层解决方案。MyBatis是一个轻量级的SQL映射框架,它将SQL语句与Java代码分离...