spring+springMVC+mybatis+maven+mysql环境搭建(一)
环境搭建是最基础的,但是发现平时很多时候大家都是ctrl c+ctrl v,这样对于很多细节完全不清楚,来,一起深入了解下
一、准备工作
首先得准备好maven、mysql啥的,这些略。。。
并且mysql中新建表,脚本如下:
db脚本:
CREATE TABLE `t_user` (
`USER_ID` int(11) NOT NULL AUTO_INCREMENT,
`USER_NAME` char(30) NOT NULL,
`USER_PASSWORD` char(10) NOT NULL,
`USER_EMAIL` char(30) NOT NULL,
PRIMARY KEY (`USER_ID`),
KEY `IDX_NAME` (`USER_NAME`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8
dml脚本:
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (1, '林炳文', '1234567@', 'ling20081005@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (2, 'evan', '123', 'fff@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (3, 'kaka', 'cadg', 'fwsfg@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (4, 'simle', 'cscs', 'fsaf@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (5, 'arthur', 'csas', 'fsaff@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (6, '小德', 'yuh78', 'fdfas@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (7, '小小', 'cvff', 'fsaf@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (8, '林林之家', 'gvv', 'lin@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (9, '林炳文Evankaka', 'dfsc', 'ling2008@126.com');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (10, 'apple', 'uih6', 'ff@qq.com');
二、创建maven项目
有关maven基础有疑问的,移步:maven菜鸟教程
注意:需要先配置下maven的本地仓库地址,默认为${user.home}/.m2/repository,修改方法为首先找到maven安装目录/conf/settings,改变<localRepository>的值,然后window-->preference-->maven-->User Settings选中maven安装目录/conf/settings,如下图:
这样maven所下载的jar包全部存放在指定位置,不会默认放在c盘。
前三张图片都是网上盗的,最后一张则是本人项目图片,如下:
注意,创建完项目之后,pom.xml会报错,报错信息为:
报错原因:因为在现在的web项目中,web.xml已经不重要了,但是maven没有跟上这个变化,会提示报错。
解决方法:将红框中的一段加到pom.xml中去,搞定。
最后,需要检查jdk版本,右击项目-->properties-->java compiler
-->java build path
-->project facets
保持jdk版本一致。
三、spring+mybatis整合
1、创建相关包与资源文件
2、pom.xml配置所需依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ty</groupId>
<artifactId>ssm_ty</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- spring版本号 -->
<spring.version>3.2.8.RELEASE</spring.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<!-- junit版本号 -->
<junit.version>4.10</junit.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.1</mybatis.version>
</properties>
<dependencies>
<!-- 添加Spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-context</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-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</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-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!--单元测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<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>${slf4j.version}</version>
</dependency>
<!-- log end -->
<!--spring单元测试依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</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.0</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
</dependencies>
</project>
3、新建相关Java代码
User类:
package com.ty.dto;
/**
* @author Taoyong
* @date 2018年5月20日
* 天下没有难敲的代码!
*/
public class User {
private Integer userId;
private String userName;
private String userPassword;
private String userEmail;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
@Override
public String toString() {
return "User [userId=" + userId + ", userName=" + userName
+ ", userPassword=" + userPassword + ", userEmail=" + userEmail
+ "]";
}
}
UserDao(接口):
package com.ty.dao;
import com.ty.dto.User;
/**
* @author Taoyong
* @date 2018年5月20日
* 天下没有难敲的代码!
*/
public interface UserDao {
public User selectUserById(Integer userId);
}
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">
<!-- namespace必须与dao的名字一致,否则会出现找不到sql语句的错误 -->
<mapper namespace="com.ty.dao.UserDao">
<!--设置dto类和数据库中表的字段一一对应,注意数据库字段和domain类中的字段名称不致,此处一定要!-->
<resultMap id="BaseResultMap" type="com.ty.dto">
<id column="USER_ID" property="userId" jdbcType="INTEGER" />
<result column="USER_NAME" property="userName" jdbcType="CHAR" />
<result column="USER_PASSWORD" property="userPassword" jdbcType="CHAR" />
<result column="USER_EMAIL" property="userEmail" jdbcType="CHAR" />
</resultMap>
<!-- 查询单条记录 -->
<select id="selectUserById" parameterType="int" resultMap="BaseResultMap">
SELECT * FROM t_user WHERE USER_ID = #{userId}
</select>
</mapper>
UserService(接口)
package com.ty.service;
import com.ty.dto.User;
/**
* @author Taoyong
* @date 2018年5月20日
* 天下没有难敲的代码!
*/
public interface UserService {
public User selectUserById(Integer userId);
}
UserServiceImpl
package com.ty.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import com.ty.dao.UserDao;
import com.ty.dto.User;
import com.ty.service.UserService;
/**
* @author Taoyong
* @date 2018年5月20日
* 天下没有难敲的代码!
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public User selectUserById(Integer userId) {
return userDao.selectUserById(userId);
}
}
四、资源配置
1、mybatis-config.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>
</configuration>
2、jdbc.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mysql
username=taoyong
password=123456
3、application.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-3.0.xsd">
<!-- 引入jdbc配置文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/*.properties</value>
<!--要是有多个配置文件,只需在这里继续添加即可 -->
</list>
</property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 使用properties来配置 -->
<property name="driverClassName">
<value>${driverClassName}</value>
</property>
<property name="url">
<value>${url}</value>
</property>
<property name="username">
<value>${username}</value>
</property>
<property name="password">
<value>${password}</value>
</property>
</bean>
<!-- 自动扫描了所有的XxxxMapper.xml对应的mapper接口文件,这样就不用一个一个手动配置Mpper的映射了,只要Mapper接口类和Mapper映射文件对应起来就可以了。 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ty.dao" />
</bean>
<!-- 配置Mybatis的文件 ,mapperLocations配置**Mapper.xml文件位置,configLocation配置mybatis-config文件位置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath*:com/ty/mapper/**/*.xml" />
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
</bean>
<!-- 自动扫描注解的bean -->
<context:component-scan base-package="com.ty.service" />
</beans>
4、配置log4j.properties
log4j.rootLogger=DEBUG,Console,Stdout
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.appender.Stdout = org.apache.log4j.DailyRollingFileAppender
log4j.appender.Stdout.File = E://logs/log.log
log4j.appender.Stdout.Append = true
log4j.appender.Stdout.Threshold = DEBUG
log4j.appender.Stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.Stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
五、单元测试
1、测试基类SpringBaseTest(负责spring与junit的整合,加载application.xml资源文件)
package com.ty.baseTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.ty.service.UserService;
/**
* @author Taoyong
* @date 2018年5月20日
* 天下没有难敲的代码!
*/
//spring整合junit引入配置文件,classpath就是指编译后classes所存放的路径。
@ContextConfiguration(locations = { "classpath:application.xml" })
//使用标准的JUnit @RunWith注释来告诉JUnit使用Spring TestRunner
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringBaseTest extends AbstractJUnit4SpringContextTests {
//使用slf4j在代码中打印日志
protected Logger logger = LoggerFactory.getLogger(getClass());
//测试spring环境是否正常启动
@SuppressWarnings("resource")
@Test
public void testEnv() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:application.xml");
UserService userService = (UserService) applicationContext.getBean("user.service.default");
logger.debug(userService.toString());
}
}
2、UserServiceTest
package com.ty.service;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.ty.baseTest.SpringBaseTest;
import com.ty.dto.User;
/**
* @author Taoyong
* @date 2018年5月20日
* 天下没有难敲的代码!
*/
public class UserServiceTest extends SpringBaseTest {
@Autowired
private UserService userService;
Logger logger = LoggerFactory.getLogger(UserServiceTest.class);
@Test
public void testSelectUserById(){
User user = userService.selectUserById(10);
logger.debug("查找结果" + user);
}
}
这地方查询的时候报错,报错信息如下:
原因:mysql驱动包的版本低了,使用的是mysql-connector-Java-5.1.29.jar,更改为mysql-connector-Java-5.1.32.jar即可。
3、测试结果
这样spring+mybatis的整合就完了,下面一篇接着把springMVC整合进来
posted on 2018-05-20 15:53 阿里-马云的学习笔记 阅读(964) 评论(0) 编辑 收藏 举报