spring mvc整合mybaitis和log4j
在上一篇博客中,我介绍了在mac os上用idea搭建spring mvc的maven工程,但是一个完整的项目肯定需要数据库和日志管理,下面我就介绍下spring mvc整合mybatis和log4j
一、先把需要用到的jar包配置到pom.xml上(主要是mybaitis和mysql驱动包)
<!-- 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.35</version> </dependency> <!-- mybatis 核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <!--jdbc数据源--> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!--jdbc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.0.4.RELEASE</version> </dependency>
二、配置spring管理数据源,可以新建一个spring-datasource.xml
<!-- 配置数据源 采用dbcp的方式 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${september.mysql.driver}" /> <property name="url" value="${september.mysql.url}" /> <property name="username" value="${september.mysql.username}" /> <property name="password" value="${september.mysql.password}" /> <!-- 数据里连接池的一些属性 --> <property name="initialSize" value="${september.dc.initialSize}" /> <property name="minIdle" value="${september.dc.minIdle}" /> <property name="maxActive" value="${september.dc.maxActive}" /> <property name="maxIdle" value="${september.dc.maxIdle}" /> <property name="maxWait" value="${september.dc.maxWait}" /> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mybatis/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zwt.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 配置Spring的事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
三、新建一个september.properties文件来配置数据源属性值
#mysql setting
september.mysql.driver=com.mysql.jdbc.Driver
september.mysql.url=jdbc:mysql://127.0.0.1:3306/september
september.mysql.username=root
september.mysql.password=123456
#定义初始连接数
september.dc.initialSize=1
#定义最大连接数
september.dc.maxActive=20
#定义最大空闲
september.dc.maxIdle=20
#定义最小空闲
september.dc.minIdle=1
#定义最长等待时间
september.dc.maxWait=60000
四、我们需要修改下工程的目录结构,如图(dao,service,controller,entity,common 各模块的功能应该不用我介绍了),spring文件夹applicationContext.xml是管理所有spring配置文件的入口
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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd" default-autowire="byName"> <!-- 引入配置文件 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="ignoreResourceNotFound" value="false" /> <property name="ignoreUnresolvablePlaceholders" value="true" /> <property name="locations"> <list> <value>classpath:stepmber.properties</value> </list> </property> </bean> <import resource="beans/spring-mvc.xml"/> <import resource="beans/spring-datasource.xml"/> </beans>
五、以上四步我们就把spring管理mybatis的功能整合进来了,然后我们写个demo来测试一下配置是否正确,在mysql建立一张user表,我们在mybatis配置的路径(resource的mybaties)下新建userMapper.xml,写一个sql查询语句
userMapp.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.zwt.dao.UserDao"> <!--对应DAO的目录--> <select id="findByUserAndPass" resultType="com.zwt.entity.User"> SELECT id, username,password from user where username =#{username} and password =#{password} limit 1; </select> </mapper>
六、然后写entity,dao和service和controller代码进行测试
User.java
package com.zwt.entity; /** * Created by zhangwentao on 2017/4/13. */ public class User { private Integer id; private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
UserDao.java(方法名必须和mybatis定义的方法名一致)
package com.zwt.dao; import com.zwt.entity.User; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; /** * Created by zhangwentao on 2017/4/13. */ public interface UserDao { public User findByUserAndPass(@Param("username") String username,@Param("password")String password); }
UserService.java
@Service("userService") public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public User findByUserAndPass(String username, String password) { return userDao.findByUserAndPass(username,password); } }
UserController.java
@RequestMapping("/login") public String login(HttpServletRequest request){ String userName=request.getParameter("username"); String password=request.getParameter("password"); User user= userService.findByUserAndPass(userName,password); System.out.print(user!=null?"用户id:"+user.getId():"用户不存在"); return user!=null?"index":"error"; }
七、我们的编码编码工作已经完成,然后启动Tomcat开始测试
测试结果成功,说明我们已经成功整合了mybatis,拍手庆祝下
八、整合完mybatis后,我们再把日志(log4j)整理添加进去,首先在web.xml监听log4j
<context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <!-- 加载Spring框架中的log4j监听器Log4jConfigListener --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>
配置log4j.properties
#Root Category
log4j.rootLogger=INFO,stdout,D,E
#Console
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
#DEBUG
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ${catalina.base}/logs/debug.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
#ERROR
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =${catalina.base}/logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
#IBATIS Category
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=INFO
#WS Logger for reporting
log4j.logger.WS=INFO,WS
log4j.appender.WS=org.apache.log4j.DailyRollingFileAppender
log4j.appender.WS.File=${catalina.base}/logs/ws.log
log4j.appender.WS.layout=org.apache.log4j.PatternLayout
log4j.appender.WS.DatePattern ='.'yyyy-MM-dd
log4j.appender.WS.layout.ConversionPattern=%d-[ws] %p %t %c - %m%n
#Other Logger
log4j.logger.org.springframework=INFO
log4j.logger.com.ibatis.db=INFO
log4j.logger.net.sf.json=ERROR
log4j.logger.org.apache.cxf=DEBUG,WS
运行后,我们可以在${catalina.base}/logs/目录下找到日志文件,说明我们的日志配置成功!详细配置属性含义请参考:http://www.cnblogs.com/pigtail/archive/2013/02/16/2913195.html
小结:今天分享的是spring 整合mybatis和log4j,这个在我们实际项目中是必不可少的环节,配置按照教程一步步来是很容易的。到这里,我们其实可以真正开始开发一个项目了,下一篇,我会介绍git的使用教程(版本管理和分支)