Spring+SpringMVC+mybatis+5.7MySQL项目搭建

SSM+5.7MySQL项目搭建

  • 1. 创建maven项目
  • 2. 配置项目
  • 3. 配置SpringMVC
  • 4.引入log4j.properties
  • 5. 测试springMVC
  • 6. 引入mybatis
  • 7.测试mybatis

1. 创建maven项目

jdk环境1.8
使用IDE创建maven项目,这里选用官网上的STS
选择创建web项目
Spring+SpringMVC+mybatis+5.7MySQL项目搭建_第1张图片
定义号group id和artifact id之后点击finish即可

2. 配置项目

单机建好的项目, ALT +Enter 快捷键进入配置
Spring+SpringMVC+mybatis+5.7MySQL项目搭建_第2张图片
Spring+SpringMVC+mybatis+5.7MySQL项目搭建_第3张图片
当出现 cannot change version of project facet Dynamic Web Module to 3.1时,先暂时关闭此界面,点击该下拉框,选择filters,按照下图操作。
Spring+SpringMVC+mybatis+5.7MySQL项目搭建_第4张图片
Spring+SpringMVC+mybatis+5.7MySQL项目搭建_第5张图片
之后项目目录下会出现.settings文件, 修改该xml
Spring+SpringMVC+mybatis+5.7MySQL项目搭建_第6张图片
Spring+SpringMVC+mybatis+5.7MySQL项目搭建_第7张图片
可能会出现这种错误
dynamic web moudule 3.1 requires java 1.7 or newer
在这里插入图片描述
这种问题是可以在pom文件build中添加该条信息

 <plugins>
    	
        <plugin>  
            <groupId>org.apache.maven.pluginsgroupId>  
            <artifactId>maven-compiler-pluginartifactId>  
            <version>2.3.2version>  
                <configuration>  
                       <source>1.8source>  
                    <target>1.8target>  
                configuration>  
        plugin>
   plugins>

然后右击项目–>maven–>update project即可
引入相应的包,这里先引入spring核心包,mybatis核心包,日志等pom文件如下

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>ssm.indigroupId>
  <artifactId>ssm1artifactId>
  <packaging>warpackaging>
  <version>0.0.1-SNAPSHOTversion>
  <name>ssm1 Maven Webappname>
  <url>http://maven.apache.orgurl>
  <properties>
		
		<spring.version>4.0.2.RELEASEspring.version>
		
		<mybatis.version>3.2.6mybatis.version>
		
		<slf4j.version>1.7.7slf4j.version>
		<log4j.version>1.2.17log4j.version>
		<tomcat7-version>2.2tomcat7-version>
		<druid-version>1.1.3druid-version>
		<mysql-version>8.0.11mysql-version>
	properties>
	<dependencies>
		
	    <dependency>
	      <groupId>junitgroupId>
	      <artifactId>junitartifactId>
	      <version>3.8.1version>
	      <scope>testscope>
	    dependency>
		
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-coreartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-webartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-oxmartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-txartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-jdbcartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-webmvcartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-aopartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-context-supportartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-testartifactId>
			<version>${spring.version}version>
		dependency>
		
		
		<dependency>
			<groupId>org.mybatisgroupId>
			<artifactId>mybatisartifactId>
			<version>${mybatis.version}version>
		dependency>
		
		<dependency>
			<groupId>org.mybatisgroupId>
			<artifactId>mybatis-springartifactId>
			<version>1.2.2version>
		dependency>
		
		<dependency>
			<groupId>javaxgroupId>
			<artifactId>javaee-apiartifactId>
			<version>7.0version>
			 <scope>providedscope>
		dependency>
		
		<dependency>
			<groupId>mysqlgroupId>
			<artifactId>mysql-connector-javaartifactId>
			<version>${mysql-version}version>
		dependency>
		
		<dependency>
			<groupId>com.alibabagroupId>
			<artifactId>druidartifactId>
			<version>${druid-version}version>
		dependency>
		
		<dependency>
			<groupId>jstlgroupId>
			<artifactId>jstlartifactId>
			<version>1.2version>
		dependency>
		
		
		<dependency>
			<groupId>log4jgroupId>
			<artifactId>log4jartifactId>
			<version>${log4j.version}version>
		dependency>
		
		
		<dependency>
			<groupId>com.alibabagroupId>
			<artifactId>fastjsonartifactId>
			<version>1.1.41version>
		dependency>
 
		<dependency>
			<groupId>org.slf4jgroupId>
			<artifactId>slf4j-apiartifactId>
			<version>${slf4j.version}version>
		dependency>
 
		<dependency>
			<groupId>org.slf4jgroupId>
			<artifactId>slf4j-log4j12artifactId>
			<version>${slf4j.version}version>
		dependency>
		
		
		
		<dependency>
			<groupId>org.codehaus.jacksongroupId>
			<artifactId>jackson-mapper-aslartifactId>
			<version>1.9.13version>
		dependency>
		
		
		<dependency>
			<groupId>commons-fileuploadgroupId>
			<artifactId>commons-fileuploadartifactId>
			<version>1.3.1version>
		dependency>
		<dependency>
			<groupId>commons-iogroupId>
			<artifactId>commons-ioartifactId>
			<version>2.4version>
		dependency>
		<dependency>
			<groupId>commons-codecgroupId>
			<artifactId>commons-codecartifactId>
			<version>1.9version>
		dependency>
	dependencies>
  <build>
    <finalName>ssm1finalName>
    <plugins>
    	
        <plugin>  
            <groupId>org.apache.maven.pluginsgroupId>  
            <artifactId>maven-compiler-pluginartifactId>  
            <version>2.3.2version>  
                <configuration>  
                       <source>1.8source>  
                    <target>1.8target>  
                configuration>  
        plugin>
   		 
    	<plugin>
    		<artifactId>maven-war-pluginartifactId>
    		<configuration>
    			<version>3.0version>
    		configuration>
    	plugin>
    	
            <plugin>
                <groupId>org.apache.tomcat.mavengroupId>
                <artifactId>tomcat7-maven-pluginartifactId>
                <version>${tomcat7-version}version>
                
                <configuration>
                	<port>8080port>
                configuration>
            plugin>
    plugins>
    
    <resources>
         <resource>
             <directory>src/main/javadirectory>
             <excludes>
                 <exclude>**/*.javaexclude>
             excludes>
         resource>
         <resource>
             <directory>src/main/resourcesdirectory>
             <includes>
                 <include>**/*.*include>
             includes>
        resource>
    resources>
  build>
  
project>

3. 配置SpringMVC

Spring+SpringMVC+mybatis+5.7MySQL项目搭建_第8张图片

创建spring-mvc.xml配置文件


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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.xsd
	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
	
	
	<context:annotation-config/>
	
	<context:component-scan base-package="com.indi"/>
	
	<mvc:annotation-driven/>
	
	
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"  />
		<property name="suffix" value=".jsp"  />
	bean>
	
beans>

配置web.xml文件


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>ssm1display-name>
  
  
  <servlet>
  	<servlet-name>springmvcservlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
  	
  	<init-param>
  		<param-name>contextConfigLocationparam-name>
  		<param-value>classpath:spring-*.xmlparam-value>
  	init-param>
  servlet>
  
  
  <servlet-mapping>
  	<servlet-name>springmvcservlet-name>
  	<url-pattern>/url-pattern>
  servlet-mapping>
  
  
  <filter>
  	<filter-name>CharacterEncodingFilterfilter-name>
  	<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
  	<init-param>
  		<param-name>encodingparam-name>
  		<param-value>UTF-8param-value>
  	init-param>
  filter>
  
  
  <filter-mapping>
  	<filter-name>CharacterEncodingFilterfilter-name>
  	<url-pattern>/*url-pattern>
  filter-mapping>
  
  
  <welcome-file-list>
    <welcome-file>index.jspwelcome-file>
  welcome-file-list>
web-app>

创建controller

package com.indi.controller;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class TestController {

	@RequestMapping("/index")
	public String  index() {
		
		return "fail";
	}
	
	@RequestMapping("/index2")
	public String  index2() {
		
		return "index2";
	}
	
	
}

创建index2.jsp
Spring+SpringMVC+mybatis+5.7MySQL项目搭建_第9张图片



index2

4.引入log4j.properties

log4j.rootLogger=DEBUG,stdout
 
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}  %l: %m %x %n 
#日志文件输出到指定位置
log4j.appender.logfile.File=D:/project/wsglxt/logs/log.txt
log4j.appender.logfile.Append=true 
log4j.appender.logfile.MaxFileSize=5MB
log4j.appender.logfile.MaxBackupIndex=30
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=[%-5p]%d{yyyy-MM-dd HH:mm:ss}  %l: %m %x %n
 
log4j.logger.org.springframework=ERROR
log4j.logger.org.springframework.web=DEBUG
log4j.logger.org.springframework.web.servlet.handler=debug
log4j.logger.org.mybatis=INFO
log4j.logger.org.apache.ibatis.logging.jdbc=DUBUG
log4j.logger.org.apache.ibatis.logging.jdbc= debug
log4j.logger.com.github=ERROR

5. 测试springMVC

这里使用Tomcat7 插件进行运行,右击项目,debug as —》maven build, 进行以下配置即可
Spring+SpringMVC+mybatis+5.7MySQL项目搭建_第10张图片
然后在浏览器中输入网址http://localhost:8080/ssm1/,显示如下
Spring+SpringMVC+mybatis+5.7MySQL项目搭建_第11张图片
Spring+SpringMVC+mybatis+5.7MySQL项目搭建_第12张图片

6. 引入mybatis

在resource目录下创建jdbc.properties文件

jdbc.url=jdbc:mysql://localhost/ssm_test?useSSL=false&serverTimezone = UTC&
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
##mysql5.7以下用此驱动
#jdbc.driverClassName=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://127.0.0.1/3306/information_schema?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc.username=*****
jdbc.password=******
jdbc.initialSize=10
jdbc.minIdle=10
jdbc.maxActive=50
jdbc.maxWait=60000
j

创建spring-mybatis.xml


<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:p="http://www.springframework.org/schema/p" 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.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
	
	
	<context:property-placeholder location="classpath:/jdbc.properties"/>

	
	<bean id="dataSource" 
		class="com.alibaba.druid.pool.DruidDataSource" 	init-method="init">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		
		<property name="initialSize" value="${jdbc.initialSize}" />
		<property name="minIdle" value="${jdbc.minIdle}" />
		<property name="maxActive" value="${jdbc.maxActive}" />
		<property name="maxWait" value="${jdbc.maxWait}" />
		<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />
		<property name="validationQuery" value="${jdbc.validationQuery}" />
		<property name="testWhileIdle" value="${jdbc.testWhileIdle}" />
		<property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
		<property name="testOnReturn" value="${jdbc.testOnReturn}" />
		<property name="poolPreparedStatements" value="${jdbc.poolPreparedStatements}" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="${jdbc.maxPoolPreparedStatementPerConnectionSize}" />
	bean>
	
	
	<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		
		<property name="dataSource" ref="dataSource" />
		
		<property name="mapperLocations" value="classpath:com/indi/mapping/*Mapper.xml" />
	bean>
	
	
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		
		<property name="basePackage" value="com.indi.dao" />
		
		<property name="sqlSessionFactoryBeanName" value="sessionFactory" />
	bean>
	
	
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    bean>
    
    <tx:annotation-driven transaction-manager="transactionManager" />
	
beans>

7.测试mybatis

创建实体类

public class User {

	private Integer id;
	private String userName;
	private String sex;
	private Integer age;
	private String email;

创建dao

package com.indi.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.indi.entity.User;

@Repository
public interface UserDao {
	List selectAll();
	
	int deleteById(int id);
}

创建mapper文件




<mapper namespace="com.indi.dao.UserDao">

	<resultMap type="com.indi.entity.User" id="userResultMap">
		<id column="id" property="id"/>
		<result column="user_name" property="userName"/>
		<result column="sex" property="sex"/>
		<result column="age" property="age"/>
		<result column="email" property="email"/>
	resultMap>
	
	
	<select id="selectAll" resultMap="userResultMap">
		select id,user_name,sex,age,email from users
	select>
	
	<delete id="deleteById" parameterType="java.lang.Integer">
		delete from users where id=#{id}
	delete>
mapper>

执行以下sql

DROP TABLE  IF EXISTS users ;
CREATE TABLE users (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `user_name` VARCHAR(40) NOT NULL,
  `sex` VARCHAR(255) NOT NULL,
  `age` INT(4) NOT NULL,
  `email` VARCHAR(60) ,
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

INSERT INTO users (user_name,sex,age,email) VALUES ('张三','男',18,'[email protected]'),('李四','男',19,'[email protected]');

SELECT id,user_name,sex,age,email FROM users;

进行Junit测试

package com.indi.user.test;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.indi.dao.UserDao;
import com.indi.entity.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:spring-*.xml")
public class UserTest {
	
	@Autowired
	UserDao userDao;
	
	@Test
	public void testUserDao() {
		List users = userDao.selectAll();
		users.forEach(user->System.out.println(user));
	}

}

可以查看输出结果
在这里插入图片描述
整合SSM到此结束!

你可能感兴趣的:(java,ssm,5.7mysql,ssm)