Spring MVC集成MyBatis及参数绑定教程
本教程将基于之前的项目,介绍如何在Spring MVC中集成MyBatis,并演示参数绑定的相关操作。我们将使用MySQL 5.6作为数据库,MyBatis 3.4.4版本。
项目结构调整
首先,对项目文件夹结构进行调整,主要变动如下:
- 将
spring-servlet.xml配置文件移至Java Resources/resources目录下。 - 更新
web.xml文件,使其能够正确加载位于新位置的spring-servlet.xml。
添加依赖与配置
- 添加必要的JAR包:
mybatis-3.4.4.jarmysql-connector-java-5.1.42-bin.jar
- 创建新的文件夹以存放相关配置文件和资源。
- 在
web.xml中配置Servlet拦截器,用于处理静态文件请求。 - 创建MyBatis的配置文件
mybatis.cfg.xml。 - 在控制器(例如
HomeController)中添加处理方法,例如public String Demo(Model model,@PathVariable("id") int id),用于演示参数绑定。
数据库脚本
以下是创建用户表的SQL脚本:
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`account` decimal(10,2) DEFAULT NULL, -- 修正account类型为DECIMAL以匹配Java的Double
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
MyBatis配置详解
MyBatis集成需要以下组件:
- JAR包:
mybatis-3.4.4.jar,mysql-connector-java-5.1.42-bin.jar - 数据库连接属性文件:
mysql.properties - MyBatis主配置文件:
mybatis.cfg.xml
mysql.properties 文件内容:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=
mybatis.cfg.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>
<properties resource="mysql.properties"></properties>
<typeAliases>
<package name="model" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<package name="mapper" />
</mappers>
</configuration>
模型类(Model)
创建名为 UserBean 的模型类,用于映射数据库中的用户表:
package model;
import java.io.Serializable;
public class UserBean implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String userName; // 变量名与数据库列名保持一致或使用驼峰命名法
private String passWord;
private Double accountBalance; // 变量名与数据库列名保持一致或使用驼峰命名法
private String fullName; // 新增字段
public UserBean() {
}
public UserBean(String userName, String passWord, Double accountBalance) {
this.userName = userName;
this.passWord = passWord;
this.accountBalance = accountBalance;
}
public UserBean(Integer id, String userName, String passWord, Double accountBalance) {
this.id = id;
this.userName = userName;
this.passWord = passWord;
this.accountBalance = accountBalance;
}
// Getters and Setters
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 Double getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(Double accountBalance) {
this.accountBalance = accountBalance;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
@Override
public String toString() {
return "UserBean{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", accountBalance=" + accountBalance +
", fullName='" + fullName + '\'' +
'}';
}
}
Mapper文件
创建 UserMapper.xml 文件,定义SQL操作:
<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="mapper.UserMapper">
<resultMap id="userResultMap" type="model.UserBean">
<id column="id" property="id" />
<result column="username" property="userName" />
<result column="password" property="passWord" />
<result column="account" property="accountBalance" />
</resultMap>
<insert id="addUserDetails" parameterType="model.UserBean" useGeneratedKeys="true" keyProperty="id">
INSERT INTO t_user (username, password, account)
VALUES (#{userName}, #{passWord}, #{accountBalance})
</insert>
<update id="updateUserDetails" parameterType="model.UserBean">
UPDATE t_user SET
username = #{userName},
password = #{passWord},
account = #{accountBalance}
WHERE id = #{id}
</update>
<delete id="removeUser" parameterType="int">
DELETE FROM t_user WHERE id = #{userId}
</delete>
<select id="findUserById" parameterType="int" resultMap="userResultMap">
SELECT * FROM t_user WHERE id = #{identifier}
</select>
<select id="findAllUsers" resultMap="userResultMap">
SELECT * FROM t_user
</select>
<select id="findUsersByCriteria" parameterType="map" resultType="model.UserBean">
SELECT * FROM t_user
<where>
<if test="criteriaName != null and criteriaName != ''">
AND username LIKE CONCAT('%', #{criteriaName}, '%')
</if>
<if test="minAccount != null">
AND account > #{minAccount}
</if>
</where>
</select>
</mapper>
Mapper接口
创建 UserMapper 接口,定义与Mapper文件对应的Java方法:
package mapper;
import model.UserBean;
import java.util.List;
import java.util.Map;
public interface UserMapper {
int addUserDetails(UserBean user) throws Exception;
int updateUserDetails(UserBean user) throws Exception;
int removeUser(int userId) throws Exception;
UserBean findUserById(int identifier) throws Exception;
List<UserBean> findAllUsers() throws Exception;
List<UserBean> findUsersByCriteria(Map<String, Object> params) throws Exception;
}
数据库工具类
创建 DBTools 类,用于管理MyBatis的SqlSessionFactory和SqlSession:
package tools;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
public class DBTools {
private static final SqlSessionFactory sqlSessionFactory;
static {
try {
Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
throw new RuntimeException("Error initializing MyBatis SqlSessionFactory", e);
}
}
public static SqlSession getDatabaseSession() {
return sqlSessionFactory.openSession();
}
public static void closeDatabaseSession(SqlSession session) {
if (session != null) {
session.close();
}
}
}
Service层实现
创建 UserService 类,封装数据库操作逻辑:
package service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import mapper.UserMapper;
import model.UserBean;
import tools.DBTools;
public class UserService {
public void addNewUser(UserBean newUser) {
try (SqlSession session = DBTools.getDatabaseSession()) {
UserMapper userMapper = session.getMapper(UserMapper.class);
userMapper.addUserDetails(newUser);
session.commit();
} catch (Exception e) {
System.err.println("Error adding user: " + e.getMessage());
// Consider proper exception handling and rollback if needed
}
}
public void removeExistingUser(int userId) {
try (SqlSession session = DBTools.getDatabaseSession()) {
UserMapper userMapper = session.getMapper(UserMapper.class);
userMapper.removeUser(userId);
session.commit();
} catch (Exception e) {
System.err.println("Error deleting user: " + e.getMessage());
// Consider proper exception handling and rollback if needed
}
}
public UserBean retrieveUserById(int identifier) {
UserBean foundUser = null;
try (SqlSession session = DBTools.getDatabaseSession()) {
UserMapper userMapper = session.getMapper(UserMapper.class);
foundUser = userMapper.findUserById(identifier);
if (foundUser == null) {
System.out.println("User with ID " + identifier + " not found.");
} else {
System.out.println("Found user: " + foundUser);
}
} catch (Exception e) {
System.err.println("Error retrieving user by ID: " + e.getMessage());
}
return foundUser;
}
public List<UserBean> retrieveAllUsers() {
List<UserBean> userList = null;
try (SqlSession session = DBTools.getDatabaseSession()) {
UserMapper userMapper = session.getMapper(UserMapper.class);
userList = userMapper.findAllUsers();
if (userList.isEmpty()) {
System.out.println("No users found in the database.");
} else {
System.out.println("All users:");
for (UserBean user : userList) {
System.out.println(user);
}
}
} catch (Exception e) {
System.err.println("Error retrieving all users: " + e.getMessage());
}
return userList;
}
public void searchUsersByCondition() {
try (SqlSession session = DBTools.getDatabaseSession()) {
UserMapper userMapper = session.getMapper(UserMapper.class);
Map<String, Object> searchParams = new HashMap<>();
searchParams.put("criteriaName", "Test"); // Example: Search for username containing "Test"
searchParams.put("minAccount", 100.0); // Example: Search for accounts greater than 100.0
List<UserBean> results = userMapper.findUsersByCriteria(searchParams);
if (results.isEmpty()) {
System.out.println("No users matched the specified criteria.");
} else {
System.out.println("Users matching criteria:");
for (UserBean user : results) {
System.out.println(user);
}
}
} catch (Exception e) {
System.err.println("Error searching users by criteria: " + e.getMessage());
}
}
}
Spring MVC注解详解
在Spring MVC控制器中,常用的注解包括:
@RequestMapping: 用于将HTTP请求映射到控制器类或方法的特定URL。@RequestParam: 用于绑定请求参数到方法的参数。参数可以来自URL查询字符串、表单数据或请求头。@PathVariable: 用于从URL路径中提取变量值,并将其绑定到方法的参数。
感谢社区的分享,这些资源极大地帮助了学习MVC和MyBatis的过程。