springmvc与mybatis整合代码
时间: 2023-09-02 07:12:22 浏览: 118
SpringMVC mybatis整合实例代码详解
以下是一个简单的Spring MVC和MyBatis的集成示例:
1. 首先,需要在pom.xml文件中添加Spring MVC和MyBatis的依赖:
```xml
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!-- MyBatis-Spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
</dependencies>
```
2. 在web.xml文件中配置DispatcherServlet:
```xml
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
```
3. 创建dispatcher-servlet.xml文件并配置Spring MVC:
```xml
<context:component-scan base-package="com.example.controller" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
```
4. 创建MyBatis的配置文件mybatis-config.xml:
```xml
<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/test" />
<property name="username" value="root" />
<property name="password" value="password" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/ExampleMapper.xml" />
</mappers>
</configuration>
```
5. 创建ExampleMapper.xml文件并配置Mapper:
```xml
<mapper namespace="com.example.mapper.ExampleMapper">
<select id="getExampleById" parameterType="int" resultType="com.example.model.Example">
SELECT * FROM example WHERE id = #{id}
</select>
</mapper>
```
6. 创建ExampleMapper接口:
```java
public interface ExampleMapper {
Example getExampleById(int id);
}
```
7. 创建ExampleController并注入ExampleMapper:
```java
@Controller
public class ExampleController {
@Autowired
private ExampleMapper exampleMapper;
@RequestMapping("/example/{id}")
public String example(@PathVariable int id, Model model) {
Example example = exampleMapper.getExampleById(id);
model.addAttribute("example", example);
return "example";
}
}
```
8. 创建example.jsp文件并使用Model中的数据:
```html
<html>
<head>
<title>Example</title>
</head>
<body>
<h1>Example</h1>
<p>ID: ${example.id}</p>
<p>Name: ${example.name}</p>
<p>Description: ${example.description}</p>
</body>
</html>
```
这就是一个简单的Spring MVC和MyBatis的集成示例,你可以根据自己的需求进行修改和完善。
阅读全文