Spring+SpringMVC+MyBatis框架技术精讲与整合案例
时间: 2024-01-24 14:01:36 浏览: 152
Spring+SpringMVC+MyBatis框架技术整合是目前Java企业级应用开发中最为流行的技术组合之一。在这个技术组合中,Spring负责IoC和AOP,SpringMVC则是MVC框架,而MyBatis则是ORM框架。
下面是一个简单的整合案例:
1. 首先,我们需要创建一个Maven项目,并添加Spring、SpringMVC和MyBatis的依赖:
```xml
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
```
2. 接着,我们需要配置Spring、SpringMVC和MyBatis的配置文件。在这里,我们使用注解方式配置Spring和SpringMVC,而使用XML方式配置MyBatis。
Spring配置文件:
```java
@Configuration
@ComponentScan(basePackages = "com.example")
@EnableWebMvc
public class AppConfig {
// ... 配置其他Bean
@Bean
public DataSource dataSource() {
// 配置数据源
return new DriverManagerDataSource();
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
// 配置MyBatis插件
Interceptor[] plugins = {pageHelper()};
sessionFactory.setPlugins(plugins);
// 配置MyBatis映射文件
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath*:mapper/*.xml"));
return sessionFactory.getObject();
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
scannerConfigurer.setBasePackage("com.example.mapper");
scannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
return scannerConfigurer;
}
@Bean
public PageInterceptor pageHelper() {
PageInterceptor pageInterceptor = new PageInterceptor();
Properties properties = new Properties();
properties.setProperty("helperDialect", "mysql");
pageInterceptor.setProperties(properties);
return pageInterceptor;
}
}
```
SpringMVC配置文件:
```java
@Configuration
public class WebConfig implements WebMvcConfigurer {
// ... 配置其他内容
@Bean
public ViewResolver viewResolver() {
// 配置视图解析器
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 配置静态资源
registry.addResourceHandler("/static/**")
.addResourceLocations("/static/");
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
```
MyBatis配置文件:
```xml
<configuration>
<typeAliases>
<!-- 配置别名 -->
<package name="com.example.model"/>
</typeAliases>
<mappers>
<!-- 配置映射文件 -->
<mapper resource="mapper/userMapper.xml"/>
</mappers>
<!-- 配置分页插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="mysql"/>
</plugin>
</plugins>
</configuration>
```
3. 接着,我们需要创建Controller和Mapper接口以及对应的视图和映射文件。这里我们以用户管理为例:
UserController.java:
```java
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model) {
List<User> users = userService.getAllUsers();
model.addAttribute("users", users);
return "user/list";
}
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String addForm() {
return "user/add";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(User user) {
userService.addUser(user);
return "redirect:/user/list";
}
@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public String editForm(@PathVariable("id") Long id, Model model) {
User user = userService.getUserById(id);
model.addAttribute("user", user);
return "user/edit";
}
@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String edit(User user) {
userService.updateUser(user);
return "redirect:/user/list";
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public String delete(@PathVariable("id") Long id) {
userService.deleteUser(id);
return "redirect:/user/list";
}
}
```
UserMapper.java:
```java
public interface UserMapper {
List<User> getAllUsers();
User getUserById(Long id);
void addUser(User user);
void updateUser(User user);
void deleteUser(Long id);
}
```
userMapper.xml:
```xml
<mapper namespace="com.example.mapper.UserMapper">
<resultMap id="userMap" type="com.example.model.User">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="age" column="age" />
</resultMap>
<select id="getAllUsers" resultMap="userMap">
SELECT * FROM user
</select>
<select id="getUserById" resultMap="userMap">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="addUser" 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="deleteUser">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
```
4. 最后,我们需要配置web.xml文件,启动Spring容器和SpringMVC DispatcherServlet。
web.xml:
```xml
<web-app>
<display-name>MyApp</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/config/spring/appConfig.java</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/config/spring/webConfig.java</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
```
这样,我们就完成了Spring+SpringMVC+MyBatis框架技术的整合。在实际开发中,我们可以根据需求进行修改和调整。
阅读全文