spring+springmvc+mybatis+junit+log4j集成的案例

mybatis框架 同时被 2 个专栏收录
2 篇文章 0 订阅
1 篇文章 0 订阅

Spring+Springmvc+Mybatis+junit+log4j集成的一个小案例

1.     本文主要内容

搭建一个整合了Spring、SpringMVC和mybatis的项目框架,同时我也添加了一些示例功能在里面,将主要的功能填充起来。

       因为springMVC是基于spring的原因,所以这三个框架整合实际上就是两个框架的整合。

       此外,我还整合了log4j用于日志的输出,整合junit用于单元测试。

2.     搭建springmvc框架

首先是导入相关jar包,这里我使用的maven管理这些jar包,不做解释。我是采用xml配置方式搭建框架。直接代码展示。

3.代码展示

       1).jdbc.properties //数据库连接配置文件,MySQL

#mysql
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/emps?characterEncoding=utf8
jdbc.username=root
jdbc.password=123

       2).applicationContext_User.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context-3.0.xsd
              http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
    <task:annotation-driven />
    <bean id="basePropertyPlaceHolder"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          lazy-init="true">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <value>classpath*:properties/jdbc.properties</value>
            </list>
        </property>
    </bean>
    <!-- mysql configuration -->
    <bean id="baseDataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!-- Transaction management   -->
    <bean id="txManagerUser"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="baseDataSource" />
    </bean>
       <!—SqlSessionFactory -->
    <bean id="sqlSessionFactoryUser" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="baseDataSource" />
        <property name="configLocation" value="classpath:config/Mybatis-Configuration.xml" />
        <property name="mapperLocations" value="classpath*:properties/mapper.xml"/>

    </bean>
    <!-- DAO Mapper  -->
    <bean id="baseMapperUser" class="org.mybatis.spring.mapper.MapperFactoryBean"
          abstract="true" lazy-init="true">
        <property name="sqlSessionFactory" ref="sqlSessionFactoryUser" />
    </bean>
    <bean id="userMapper" parent="baseMapperUser">
        <property name="mapperInterface" value="com.lm.mapping.UserMapper" />
    </bean>

    <!-- Service -->
    <bean id="userService"
          class="com.lm.service.impl.UserServiceImpl">
        <property name="userMapper" ref="userMapper" />
    </bean>

</beans>

       3).Mybatis-Confiuration.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPEconfiguration
        PUBLIC"-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <typeAliases>
        <typeAlias type="com.lm.entity.UserEntity" alias="UserEntity"/>
    </typeAliases>
</configuration>

       4).spring-mvc.xml

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

    <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
    <context:component-scan base-package="com.lm.controller" />
    <mvc:annotation-driven />
    <!-- 避免IE执行AJAX,返回JSON出现下载文件 -->
    <bean id="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
    <bean
            class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
            </list>
        </property>
    </bean>

    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 p:prefix中模板放置路径 -->
    <bean id="velocityConfig"
          class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
        <property name="resourceLoaderPath" value="/WEB-INF/view/" />
        <property name="velocityProperties">
            <props>
                <prop  key="input.encoding">UTF-8</prop>
                <prop  key="output.encoding">UTF-8</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
        <property name="cache" value="true" />
        <property name="prefix" value="" />
        <property name="layoutUrl" value="layout.vm" />
        <property name="suffix" value=".vm" />
        <property name="contentType"><value>text/html;charset=UTF-8</value></property>
    </bean>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/view/" p:suffix=".jsp" />

</beans>

       5).mapper.xml//主要是对数据库的sql语句定义

?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lm.mapping.UserMapper">
    <resultMap id="userEntityMapper" type="UserEntity">
        <id property="userId" column="userId"/>
        <result property="userName" column="userName"/>
        <result property="password" column="password"/>
        <result property="sex" column="sex"/>
        <result property="email" column="email"/>
    </resultMap>
    <select id="getUserEntityById" parameterType="String" resultMap="userEntityMapper">
        SELECT * FROM user WHERE userId = #{userid}
    </select>
    <select id="getUserEntities" resultMap="userEntityMapper">
        select * from user;
    </select>
    <insert id="insertUser" parameterType="userEntity">
       insert into user(userId,userName,password,sex,email)
        values(#{userId},#{userName},#{password},#{sex},#{email})
    </insert>
</mapper>

       6).log4j.properties//日志配置文件

#定义LOG输出级别  
log4j.rootLogger=INFO,Console,File  
#定义日志输出目的地为控制台  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.Target=System.out  
#可以灵活地指定日志输出格式,下面一行是指定具体的格式  
log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  

#文件大小到达指定尺寸的时候产生一个新的文件  
log4j.appender.File = org.apache.log4j.RollingFileAppender  
#指定输出目录  
log4j.appender.File.File = logs/ssm.log  
#定义文件最大大小  
log4j.appender.File.MaxFileSize = 10MB  
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志  
log4j.appender.File.Threshold = ALL  
log4j.appender.File.layout = org.apache.log4j.PatternLayout  
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n 

       7).Java代码

Controller层部分代码

private UserService userService;
@RequestMapping("/userList")
public String list(ModelMap model) {
    model.put("users", userService.getUserEntities());
    System.out.println(userService.getUserEntities().toString());
    return "list";
}

实体部分代码//setter和getter方法自动生成或者手动生成

private String userId;
private String userName;
private String password;
private String sex;
private String email;

接口代码

public interface UserMapper {
    //根据用户ID获取用户信息
  public  UserEntity getUserEntityById(String userId);
    //获取用户所有的用户信息
   public List<UserEntity> getUserEntities();
    //插入用户信息
   public int insertUser(UserEntity userEntity);
}

service层代码

public interface UserService {
    //根据用户ID获取用户信息
    UserEntity getUserEntityById(String userId);
    //获取用户所有的用户信息
    List<UserEntity> getUserEntities();
    //插入用户信息
    UserEntity insertUserEntity(UserEntity userEntity);
}

serviceImpl代码

public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    public UserMapper getUserMapper() {
        return userMapper;
    }
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    @Override
    public UserEntity getUserEntityById(String userId) {
     return this.userMapper.getUserEntityById(userId);
    }
    @Override
    public List<UserEntity> getUserEntities() {
        return this.userMapper.getUserEntities();
    }
    @Override
    public UserEntity insertUserEntity(UserEntity userEntity) {
        this.userMapper.insertUser(userEntity);
      return getUserEntityById(userEntity.getUserId());
    }
}

测试代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:config/applicationContext_User.xml"})
public class STest {
    Logger log = LoggerFactory.getLogger(this.getClass());

    @Before
    public void before(){
    }

    @org.junit.Test
    public void testShowUser() throws Exception {
       log.info("start");
        ApplicationContext ctx = new ClassPathXmlApplicationContext("config/applicationContext_User.xml");
        UserMapper userMapper  = (UserMapper) ctx.getBean("userMapper");
        List<UserEntity> u =  userMapper.getUserEntities();
        UserEntity us = userMapper.getUserEntityById("2");
        System.out.println(u.toString());
        System.out.println(us.toString());
        log.info("成功");
    }
  @org.junit.Test
  public void addUser(){
        log.info("开始执行插入操作");
        ApplicationContext ctx = new ClassPathXmlApplicationContext("config/applicationContext_User.xml");
        UserMapper userMapper  = (UserMapper) ctx.getBean("userMapper");
        UserEntity user = new UserEntity();
        user.setUserId("10");
        user.setUserName("Tim");
        user.setPassword("12345");
        user.setSex("");
        user.setEmail("920449464@qq.com");
        log.info("插入成功");
       System.out.println(userMapper.insertUser(user));
    }
}

附工程目录以及演示结果,pom.xml的jar包


<properties>
  <!-- spring版本号 -->
  <spring.version>3.2.4.RELEASE</spring.version>
  <org.aspectj.version>1.7.3</org.aspectj.version>
  <!-- mybatis版本号 -->
  <mybatis.version>3.2.4</mybatis.version>
  <!-- log4j日志文件管理包版本 -->
  <slf4j.version>1.6.6</slf4j.version>
  <log4j.version>1.2.12</log4j.version>
</properties>
<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>
  <!-- spring核心包 -->
  <!-- springframe start -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-oxm</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>${org.aspectj.version}</version>
  </dependency>
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>${org.aspectj.version}</version>
  </dependency>

  <dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>2.2.2</version>
  </dependency>
  <dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib-nodep</artifactId>
    <version>2.2.2</version>
  </dependency>
  <!-- mybatis核心包 -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
  </dependency>
  <!-- mybatis/spring包 -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.2</version>
  </dependency>
  <!-- mysql驱动包 -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.29</version>
  </dependency>
  <!-- junit测试包 -->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>
  <!-- 阿里巴巴数据源包 -->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.2</version>
  </dependency>

  <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.1</version>
  </dependency>

  <dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
  </dependency>
  <!-- json数据 -->
  <dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
  </dependency>

  <dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
  </dependency>

  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
  </dependency>

  <dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
  </dependency>
  <dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-tools</artifactId>
    <version>2.0</version>
  </dependency>
  <!-- 日志文件管理包 -->
  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>${log4j.version}</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.2</version>
  </dependency>
  <dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>RELEASE</version>
  </dependency>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>RELEASE</version>
  </dependency>
  <!-- log end -->
</dependencies>


  • 1
    点赞
  • 1
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值