Loading

Spring SpringMvc Mybatis Maven整合

Spring SpringMvc Mybatis 整合

1. 创建Maven项目,pom.xml,导入依赖
 <properties>
        <project-build-sourceEncode>UTF-8</project-build-sourceEncode>
        <java-compiler-source>1.8</java-compiler-source>
        <java-compiler-target>1.8</java-compiler-target>
    </properties>


    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        
        <!-- 导入SSM需要的jar -->
        <!-- MyBatis Generator -->
        <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>

        <!-- Spring MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

        <!-- Spring单元测试 -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.7.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- Spring JDBC -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

        <!-- Spring 面向切面 -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

        <!-- MyBatis -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>

        <!-- MyBatis 整合 Spring 的包 -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- 数据库连接池、驱动 -->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/jstl/jstl -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- servlet API包 -->
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- 单元测试包 -->
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <!-- json -->
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

        <!-- 阿里巴巴 druid 数据源  -->
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>


        <!--处理JSON格式数据-->
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
	 <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

然后在 resources 目录下创建项目需要的xml配置文件

2. applicationContext-dao.xml

Dao层,mybatis整合spring,通过spring管理 SqlSessionFactory、mapper代理对象。

这里用的是阿里的连接池,当然也可以用c3p0,个人建议用阿里

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

    <!-- 加载数据库连接信息 database.properties-->
    <context:property-placeholder location="classpath:database.properties"/>

    <!-- 配置数据源 dbcp连接池 -->
    <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}"/>
        <property name="maxActive" value="10"/>
        <property name="minIdle" value="5"/>
    </bean>

    <!-- 创建sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 所有Sql 映射文件路径 -->
        <property name="mapperLocations">
            <value>classpath:mapper/*.xml</value>
        </property>
        <!--为所有sql标签 返回值 设置别名-->
        <property name="typeAliasesPackage" value="cn.wengzi.ssm.entity.Student"></property>
    </bean>

    <!-- 自动扫描 将Mapper接口生成代理注入到Spring -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- value 的包名 就是所有dao接口的包名 -->
        <property name="basePackage" value="cn.wengzi.ssm.repository"/>
    </bean>
</beans>
2.1 database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/student?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=xxx
3. ApplicationContext-service

service层

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

    <!--
        Spring容器可以自动去扫描base-pack所指定的包或其子包下面的java类文件,
        如果扫描到有@Component、@Controller、@Service 、@Repository等注解修饰的Java类,
        则将这些类注册为spring容器中的bean。
    -->
    <context:component-scan base-package="cn.wengzi.ssm.service"/>

</beans>
4. ApplicationContext-tx.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"
>
    <!-- Spring声明式事务-->
    <!-- 配置事物管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置哪些方法需要添加什么事务-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--Spring 事务的传播机制-->
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="upd*" propagation="REQUIRED"/>
            <tx:method name="del*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <!-- 配置切点 -->
        <aop:pointcut expression="execution(* cn.wengzi.ssm.service.*.*(..))" id="pointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>

</beans>
5. SpringMvc.xml

Springmvc整合spring框架,由springmvc管理controller

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

    <!--开启Controller包的注解
        注意:如果扫描所有包,此标签必须写在SpringMvc-config.xml中
    -->
    <context:component-scan base-package="cn.wengzi.ssm.controller"/>
    <!-- 针对静态资源不会进行拦截  .css .js  .jpg..... -->
    <mvc:default-servlet-handler/>
    <!-- 会自动的去查找最新的处理器映射器 和处理器适配器并进行配置 -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                        <property name="dateFormat">
                            <bean class="java.text.SimpleDateFormat">
                                <!--处理JSON返回的日期格式-->
                                <constructor-arg type="java.lang.String" value="yyyy-MM-dd"/>
                            </bean>
                        </property>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--配置视图解析器-->
    <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>-->

</beans>
6. Log4j.properties
log4j.rootLogger=error,CONSOLE,A
log4j.addivity.org.apache=false
 
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=error
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} -%-4r [%t] %-5p  %x - %m%n
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.Encoding=gbk
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
 
 
log4j.appender.A=org.apache.log4j.DailyRollingFileAppender  
log4j.appender.A.File=${catalina.home}/logs/FH_log/PurePro_
log4j.appender.A.DatePattern=yyyy-MM-dd'.log'
log4j.appender.A.layout=org.apache.log4j.PatternLayout  
log4j.appender.A.layout.ConversionPattern=[FH_sys]  %d{yyyy-MM-dd HH\:mm\:ss} %5p %c{1}\:%L \: %m%n
7. Web.xml

前面配置的xml文件,需要在在Web.xml中配置,随着tomcat启动通过监听器将配置文件加载,

初始化Spring Ioc容器。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!--加载所有Spring配置文件-->
        <param-value>classpath:ApplicationContext-*.xml</param-value>
    </context-param>
    <listener>
        <!--配置Spring-web.jar提供的监听器,此监听器可以在服务器启动时初始化Ioc容器-->
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--拦截器 解决乱码-->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--配置DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--加载SpringMvc-config.xml-->
            <param-value>classpath:SpringMvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <!--所有请求都被SpringMvc拦截-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
8. 编写代码
8.1 实体类
package cn.wengzi.ssm.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.io.Serializable;
import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student implements Serializable {
    private Integer id;
    private String name;
    private Integer age;
    private Date birthday;
}
8.2 DAO层
package cn.wengzi.ssm.repository;


import cn.wengzi.ssm.entity.Student;

import java.util.List;

public interface StudentRepository {
    List<Student> findAll();

    Student findById(Integer id);

    int addStudent(Student student);

    int updStudent(Student student);

    int delStudent(Integer id);
}
8.3 Service层
package cn.wengzi.ssm.service;

import cn.wengzi.ssm.entity.Student;

import java.util.List;

public interface StudentService {
    List<Student> findAll();

    Student findById(Integer id);

    int addStudent(Student student);

    int updStudent(Student student);

    int delStudent(Integer id);
}
package cn.wengzi.ssm.service.impl;

import cn.wengzi.ssm.entity.Student;
import cn.wengzi.ssm.repository.StudentRepository;
import cn.wengzi.ssm.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentRepository studentRepository;

    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    public Student findById(Integer id) {
        return studentRepository.findById(id);
    }

    public int addStudent(Student student) {
        return studentRepository.addStudent(student);
    }

    public int updStudent(Student student) {
        return studentRepository.updStudent(student);
    }

    public int delStudent(Integer id) {
        return studentRepository.delStudent(id);
    }
}
8.3 Sql映射文件
<?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="cn.wengzi.ssm.repository.StudentRepository">

    <select id="findAll" resultType="Student">
        select * from student
    </select>

    <select id="findById" parameterType="java.lang.Integer" resultType="Student">
        select * from student where id = #{id}
    </select>

    <insert id="addStudent" parameterType="Student">
        insert into student(name,age,birthday) values (#{name},#{age},#{birthday})
    </insert>

    <update id="updStudent" parameterType="Student">
        update student set name = #{name},age = #{age},birthday = #{birthday} where id = #{id}
    </update>

    <delete id="delStudent" parameterType="java.lang.Integer">
        delete from student wehere id = #{id}
    </delete>
</mapper>
8.3 handler
package cn.wengzi.ssm.controller;

import cn.wengzi.ssm.entity.Student;
import cn.wengzi.ssm.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * created Arley 19/8/10
 */
@RestController
@RequestMapping(value = "/student")
public class StudentHandler {

    @Autowired
    private StudentService studentService;

    @ResponseBody
    @GetMapping(value = "/findAll")
    public List<Student> findAll() {
        return studentService.findAll();
    }

    @ResponseBody
    @GetMapping(value = "findById/{id}")
    public Student findById(@PathVariable("id") Integer id) {
        return studentService.findById(id);
    }

}

到此,Spring、SpringMvc及MyBatis整合就结束了。
项目地址 :https://github.com/wengzi/spring-mybatis

If you’re going to reuse code, you need to understand that code!
posted @ 2020-02-23 21:48  不颓废青年  阅读(256)  评论(0编辑  收藏  举报