spring,springMvc和mybatis整合配置

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring,springMvc和mybatis整合配置相关的知识,希望对你有一定的参考价值。

一,配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>mvc03</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
        /WEB-INF/classes/applicationContext.xml
        </param-value>
    </context-param>
    <servlet>
        <servlet-name>mvc03</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
              /WEB-INF/classes/mySpring-servlet.xml
          </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc03</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

二,在WEB-INF创建classes文件,里面放各种配置,包括:

2.1:mySpring-servlet.xml

<?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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/mvc   
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

    <mvc:annotation-driven />
    
    <context:component-scan base-package="com.wode.controller" />
        
    <!-- ViewResolver视图解析器 用于将返回的ModelAndView对象进行分离 -->
    <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>


</beans>

2.2 applicationContext.xml

<?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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.2.xsd">
    <!--启用自动扫描 -->
    <context:component-scan base-package="com.wode" />
    <aop:aspectj-autoproxy />
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/j116?useUnicode=true&amp;characterEncoding=UTF-8" />
        <property name="username" value="root" />
        <property name="password" value="admin" />
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:SqlMapConfig.xml" />
    </bean>
    <!-- mappers -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wode.mapper"></property>
    </bean>
</beans>

2.3 SqlMapConfig.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>
    <typeAliases>
        <package name="com.wode.pojo"/>
    </typeAliases>
</configuration>

3:在lib中导入核心jar包:

4:在src下创建相应的包和类:

技术分享

5:创建Bean对象

package com.wode.pojo;

import java.io.Serializable;

public class User implements Serializable{
    private int userId;
    private String userName;
    private String userPwd;
    private int userType;
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserPwd() {
        return userPwd;
    }
    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }
    public int getUserType() {
        return userType;
    }
    public void setUserType(int userType) {
        this.userType = userType;
    }
    
}

6:创建UserMapper.java

package com.wode.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import com.wode.pojo.User;
@Repository
public interface UserMapper {
    public void addUser(@Param("user")User user);
    public int delById(@Param("id")int id);
    public int updateUserById(@Param("name")String name);
    public User getUserById(@Param("id")int id);
    public List<User> getAllUser();
}

7:创建UserMapper.xml

<?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.wode.mapper.UserMapper">
 <resultMap id="userMap" type="User" >
      <id property="userId" column="user_id" javaType="int"></id>   
      <result property="userName" column="user_name" javaType="java.lang.String"/>
      <result property="userPwd" column="user_pwd" javaType="java.lang.String"/>
      <result property="userType" column="user_type" javaType="int"/>
  </resultMap>


    <insert id="addUser" parameterType="User" keyProperty="user.userId" useGeneratedKeys="true">
        insert into users values(null,#{user.userName},#{user.userPwd},#{user.userType})
    </insert>
    <!-- 得到刚才插入数据库自增长的主键值 -->
    <delete id="delById" parameterType="Integer">
        delete from users where user_id=#{id}
    </delete>
    <update id="updateUserById"  parameterType="String">
    <!-- id为1的数据的名字改为用户需要的 -->
        update users set user_name=#{name} where user_id=1
    </update>
    
    <select id="getUserById" parameterType="Integer" resultMap="userMap" >
        select * from users where user_id=#{id}
    </select>
    <select id="getAllUser"  resultMap="userMap" >
        select * from users 
    </select>

</mapper>

8:创建UserService.java

package com.wode.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.wode.mapper.UserMapper;
import com.wode.pojo.User;

@Service
public class UserService {
    @Resource(name="userMapper")
    private  UserMapper mapper;
    public void login(String name,String pwd){
        System.out.println("数据库查询了"+name+" "+pwd);
    }
    public void addUser(User user){
        System.out.println(user.getUserName()+" "+user.getUserPwd());
        mapper.addUser(user);
    }
}

9:创建UserController.java

package com.wode.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.wode.pojo.User;
import com.wode.service.UserService;

@Controller
public class UserController {
    @Resource
    private UserService service;
    @RequestMapping("regist.do")
    public String login(User user){
        service.addUser(user);
        return "success";
    }
}

10:创建日志切面

package com.wode.log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component("userLogger")
@Aspect
public class UserLogger {
    
    @Pointcut("execution(* com.wode.service.UserService.*(..))")
    public void pointCut(){}
    
    @Before("pointCut()")
    public int testLogger(JoinPoint jpt) throws Throwable{
        System.out.println("前置记录日志");
        return 1;
    }
}

 

以上是关于spring,springMvc和mybatis整合配置的主要内容,如果未能解决你的问题,请参考以下文章

Spring和mybatis整合 org.mybatis.spring.mapper.MapperScannerConfigurer

ssm 框架实现增删改查CRUD操作(Spring + SpringMVC + Mybatis 实现增删改查)

Spring - SpringMVC - MyBatis

SpringMVC学习--springmvc和mybatis整合

SpringMVC——Spring整合Mybatis和SpringMVC

eclipse如何搭建springmvc +mybatis