How to use Mybatis to integrate Spring method sharing
This article mainly introduces the example code of Mybatis integrating Spring. Friends who need it can refer to
other tools or technologies needed:
Project management tools : Maven
Front-end WEB display: JSP
Other frameworks: Spring, Spring MVC
Database : Derby
Create a new Maven Web project
Maven Dependencies:
<!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.0.0.RELEASE</version> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.10</version> </dependency> <!-- Logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.6</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.6.6</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.6</version> <scope>runtime</scope> </dependency> <!-- @Inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.7</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.1</version> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> <scope>test</scope> </dependency> <!-- Derby --> <dependency> <groupId>org.apache.derby</groupId> <artifactId>derby</artifactId> <version>10.10.2.0</version> </dependency> <dependency> <groupId>org.apache.derby</groupId> <artifactId>derbyclient</artifactId> <version>10.10.2.0</version> </dependency>
SQL table creation and data insertion
CREATE TABLE USER_TEST_TB( ID INT PRIMARY KEY, USERNAME VARCHAR(20) NOT NULL, PASSWORD VARCHAR(20) NOT NULL, NICKNAME VARCHAR(20) NOT NULL ); INSERT INTO USER_TEST_TB VALUES(1,'1st','111','Jack'); INSERT INTO USER_TEST_TB VALUES(2,'2nd','222','Rose'); INSERT INTO USER_TEST_TB VALUES(3,'3rd','333','Will');
web.xml (under scr/main/webapp/WEB-INF)
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" 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_2_5.xsd"> <!-- Spring 的配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/*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> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
appServlet-servlet.xml (Spring’s Servlet configuration file scr/main/webapp /WEB-INF)
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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"> <!-- 开启Annotation支持 --> <annotation-driven /> <!-- Spring的渲染层配置 --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <!-- Spring的Annotation默认扫描包 --> <context:component-scan base-package="com.bjpowernode.practice" /> <!-- 引入其他Spring配置文件 --> <beans:import resource="classpath:applicationContext.xml" /> </beans:beans>
JSP file
show.jsp(src/main/webapp/WEB-INF/views目录下) <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!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=ISO-8859-1"> <title>Show All Users</title> <style type="text/css"> *{ margin: 0px; padding: 0px; } </style> </head> <body> <table border="1px" bordercolor="green"> <thead> <tr> <th>USER_NAME</th> <th>PASSWORD</th> <th>NICK_NAME</th> <th>EDIT</th> <th>DELETE</th> </tr> <c:forEach items="${users}" var="user" varStatus="status"> <tr> <td>${user.username}</td> <td>${user.password}</td> <td>${user.nickname}</td> <td><a href="update/${user.id}" rel="external nofollow" >edit</a></td> <td><a href="delete/${user.id}" rel="external nofollow" >delete</a></td> </tr> </c:forEach> </thead> </table> <a href="insert" rel="external nofollow" >Add new User</a> </body> </html>
update.jsp(src/main/webapp/ WEB-INF/views directory)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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=ISO-8859-1"> <title>Update Profile</title> </head> <body> <form action="${user.id}" method="post"> User ID:${user.id}<br> Username:<input type="text" name="username" value="${user.username}"/><br> Password:<input type="text" name="password" value="${user.password}"/><br> Nickname:<input type="text" name="nickname" value="${user.nickname}"/><br> <input type="submit" value="submit"> </form> </body> </html>
insert.jsp(src/main/webapp/WEB-INF/views directory)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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=ISO-8859-1"> <title>Insert Profile</title> </head> <body> <form action="" method="post"> User Id:<input type="text" name="id"><br> Username:<input type="text" name="username" /><br> Password:<input type="text" name="password"/><br> Nickname:<input type="text" name="nickname"/><br> <input type="submit" value="submit"> </form> </body> </html>
applicationContext.xml (Spring’s Application configuration file is in the src/main/resources directory)
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/lang http://www.springframework.org/schema/lang/spring-lang-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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd"> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.bjpowernode.practice" /> <property name="sqlSessionFactoryBeanName" value="derbySqlSessionFactory" /> </bean> <!-- 配置Derby驱动数据源 --> <bean id="derbyDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver" /> <property name="url" value="jdbc:derby://localhost:1527/freud;create=true" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" name="derbySqlSessionFactory"> <property name="dataSource" ref="derbyDataSource" /> <property name="mapperLocations" value="classpath*:com/freud/practice/*Mapper.xml" /> </bean> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="derbyDataSource" /> </bean> <!-- 开启基于注解的事务 --> <tx:annotation-driven /> </beans>
Java file
UserController.Java (in the src/main/java/com.bjpowernode.practice.controller directory)
package com.bjpowernode.practice.controller; import com.bjpowernode.practice.User; import com.bjpowernode.practice.UserMapper; import java.util.List; 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.servlet.config.annotation.EnableWebMvc; @EnableWebMvc @Controller public class UserController { @Autowired private UserMapper userMapper; /** * * 获得所有的User信息 * * @param model * @return */ @RequestMapping(value = {"/", ""}, method = RequestMethod.GET) public String getAllUser(Model model) { List<User> users = userMapper.getUsers(); System.out.println("Show all user size:" + users.size()); model.addAttribute("users", users); return "show"; } /** * * INSERT的GET请求,跳转到Insert的View即insert.jsp * * @return */ @RequestMapping(value = {"/insert", ""}, method = RequestMethod.GET) public String insertUser() { return "insert"; } /** * * INSERT的POST请求,执行插入操作并返回ShowAll页面 * * @param user * @return */ @RequestMapping(value = {"/insert", ""}, method = RequestMethod.POST) public String insertUserPOST(User user) { userMapper.insertUser(user); return "redirect:/"; } /** * * UPDATE的GET请求,跳转到update的View即update.jsp * * @param id * @param model * @return */ @RequestMapping(value = {"/update/{id}", ""}, method = RequestMethod.GET) public String updateUser(@PathVariable String id, Model model) { model.addAttribute("user", userMapper.getUser(Integer.valueOf(id))); return "update"; } /** * * UPDATE的POST请求,执行更新操作并返回ShowAll页面 * * @param id * @param user * @return */ @RequestMapping(value = {"/update/{id}", ""}, method = RequestMethod.POST) public String updateUserPOST(@PathVariable String id, User user) { userMapper.updateUser(user); return "redirect:/"; } /** * * 通过Id删除USER * * @param id * @return */ @RequestMapping(value = {"/delete/{id}", ""}, method = RequestMethod.GET) public String deleteUser(@PathVariable int id) { userMapper.deleteUser(id); return "redirect:/"; } }
User.java (in the src/main/java/com. bjpowernode.practice)
package com.bjpowernode.practice; /** * * User 对象。 * * @author Freud Kang * */ public class User { private Integer id; private String username; private String password; private String nickname; public Integer getId() { return id; } public void setId(Integer 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; } }
UserMapper.java(in the src/main/java/com.bjpowernode.practice directory)
package com.bjpowernode.practice; import java.util.List; public interface UserMapper { /** * * 获得所有User * * @return */ public List<User> getUsers(); /** * * 通过Id获得User * * @param id * @return */ public User getUser(int id); /** * * 插入User * * @param user */ public void insertUser(User user); /** * * 更新User * * @param user */ public void updateUser(User user); /** * * 通过Id删除User * * @param userId */ public void deleteUser(int userId); }
UserMapper.xml (mybatis mapper configuration file, in the src/main/java/com.bjpowernode.practice directory)
<?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.bjpowernode.practice.UserMapper"> <!-- 查询 --> <select id="getUsers" resultType="com.bjpowernode.practice.User"> select * from USER_TEST_TB </select> <!-- 查询 --> <select id="getUser" resultType="com.bjpowernode.practice.User"> select * from USER_TEST_TB where ID=#{id} </select> <!-- 插入 --> <insert id="insertUser"> insert into USER_TEST_TB values(#{id},#{username},#{password},#{nickname}) </insert> <!-- 更改 --> <update id="updateUser"> update USER_TEST_TB set USERNAME = #{username}, PASSWORD = #{password}, NICKNAME = #{nickname} where ID = #{id} </update> <!-- 删除 --> <delete id="deleteUser"> delete from USER_TEST_TB where ID=#{id} </delete> </mapper>
Summarize
The above is the detailed content of How to use Mybatis to integrate Spring method sharing. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

MyBatisGenerator is a code generation tool officially provided by MyBatis, which can help developers quickly generate JavaBeans, Mapper interfaces and XML mapping files that conform to the database table structure. In the process of using MyBatisGenerator for code generation, the setting of configuration parameters is crucial. This article will start from the perspective of configuration parameters and deeply explore the functions of MyBatisGenerator.

Detailed explanation of MyBatis one-to-many query configuration: To solve common associated query problems, specific code examples are required. In actual development work, we often encounter situations where we need to query a master entity object and its associated multiple slave entity objects. In MyBatis, one-to-many query is a common database association query. With correct configuration, the query, display and operation of associated objects can be easily realized. This article will introduce the configuration method of one-to-many query in MyBatis, and how to solve some common related query problems. It will also

Analysis of MyBatis' caching mechanism: The difference and application of first-level cache and second-level cache In the MyBatis framework, caching is a very important feature that can effectively improve the performance of database operations. Among them, first-level cache and second-level cache are two commonly used caching mechanisms in MyBatis. This article will analyze the differences and applications of first-level cache and second-level cache in detail, and provide specific code examples to illustrate. 1. Level 1 Cache Level 1 cache is also called local cache. It is enabled by default and cannot be turned off. The first level cache is SqlSes

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? During the development process, efficient data access has always been one of the focuses of programmers. For persistence layer frameworks like MyBatis, caching is one of the key methods to improve data access efficiency. MyBatis provides two caching mechanisms: first-level cache and second-level cache. The first-level cache is enabled by default. This article will introduce the mechanism of MyBatis first-level cache in detail and provide specific code examples to help readers better understand

As network technology continues to develop, database attacks are becoming more and more common. SQL injection is one of the common attack methods. Attackers enter malicious SQL statements into the input box to perform illegal operations, causing data leakage, tampering or even deletion. In order to prevent SQL injection attacks, developers must pay special attention when writing code, and when using an ORM framework such as MyBatis, they need to follow some best practices to ensure the security of the system. 1. Parameterized query Parameterized query is the anti-

MyBatis is an excellent persistence layer framework. It supports database operations based on XML and annotations. It is simple and easy to use. It also provides a rich plug-in mechanism. Among them, the paging plug-in is one of the more frequently used plug-ins. This article will delve into the principles of the MyBatis paging plug-in and illustrate it with specific code examples. 1. Paging plug-in principle MyBatis itself does not provide native paging function, but you can use plug-ins to implement paging queries. The principle of paging plug-in is mainly to intercept MyBatis
