MyBatis整合Spring和SpringMVC,需要按照以下步骤进行操作:
- 添加依赖
在项目的pom.xml中添加MyBatis、Spring和SpringMVC的依赖:
<dependencies>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.10</version>
</dependency>
<!-- SpringMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.10</version>
</dependency>
</dependencies>
- 配置数据库连接和mybatis
在项目的src/main/resources目录下创建mybatis-config.xml文件,配置数据源和MyBatis的相关信息。例如:
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
- 配置Spring
在项目的src/main/resources目录下创建 ApplicationContext.xml,配置Spring的相关信息,例如:
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" 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}"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
- 配置SpringMVC
在项目的src/main/resources目录下创建spring-mvc.xml文件,配置SpringMVC的相关信息,例如:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.example.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
- 编写代码
在这里,我们假设已经有了一个名为User的实体类和对应的UserMapper接口以及UserMapper.xml文件。
首先,在UserMapper.xml中定义对User实体类的一些操作。例如:
<?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.example.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.entity.User">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="INTEGER"/>
</resultMap>
<select id="getUserById" resultMap="BaseResultMap">
select * from user where id=#{id}
</select>
<select id="getAllUsers" resultMap="BaseResultMap">
select * from user
</select>
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into user(name,age) values(#{name},#{age})
</insert>
<update id="updateUser">
update user set name=#{name},age=#{age} where id=#{id}
</update>
<delete id="deleteUserById">
delete from user where id=#{id}
</delete>
</mapper>
然后,在UserMapper接口中定义对User实体类的具体操作。例如:
public interface UserMapper {
User getUserById(Long id);
List<User> getAllUsers();
void insertUser(User user);
void updateUser(User user);
void deleteUserById(Long id);
}
最后,在UserController中编写具体的业务逻辑和相关的视图。例如:
@Controller
@RequestMapping("/User")
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ModelAndView getUserById(@PathVariable("id") Long id) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("UserDetail");
User user = userMapper.getUserById(id);
modelAndView.addObject("user", user);
return modelAndView;
}
@RequestMapping(value = "/All", method = RequestMethod.GET)
public ModelAndView getAllUsers() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("UserList");
List<User> users = userMapper.getAllUsers();
modelAndView.addObject("users", users);
return modelAndView;
}
@RequestMapping(value = "/Add", method = RequestMethod.GET)
public ModelAndView addUser() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("AddUser");
return modelAndView;
}
@RequestMapping(value = "/Create", method = RequestMethod.POST)
public String createUser(User user) {
userMapper.insertUser(user);
return "redirect:/User/All";
}
@RequestMapping(value = "/Edit/{id}", method = RequestMethod.GET)
public ModelAndView editUser(@PathVariable("id") Long id) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("EditUser");
User user = userMapper.getUserById(id);
modelAndView.addObject("user", user);
return modelAndView;
}
@RequestMapping(value = "/Update", method = RequestMethod.PUT)
public String updateUser(User user) {
userMapper.updateUser(user);
return "redirect:/User/All";
}
@RequestMapping(value = "/Delete/{id}", method = RequestMethod.DELETE)
public String deleteUser(@PathVariable("id") Long id) {
userMapper.deleteUserById(id);
return "redirect:/User/All";
}
}
- 配置web.xml
<servlet>
<servlet-name>dispatcherServlet</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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- 测试
现在,可以使用浏览器测试了。