表现层web层->业务层service层->持久层dao层->数据库
业务层:spring
表现层:springMVC
持久层:Mybatis
=========================================================================
一关于Spring的配置
1 spring框架中XML文件头部常用配置
spring框架的xml配置文件头部和springmvc的xml配置文件头部是一样的
1-1默认配置(这个是必须要写的)
<?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.xsd">
</beans>
1-2 context配置:扫描注解
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
1-3 AOP配置:切面约束
xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
1-4 TX配置:事务的通知
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
1-5 dubbo配置
xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
http://dubbo.apache.org/schema/dubbo
http://dubbo.apache.org/schema/dubbo/dubbo.xsd
1-6 spring-security配置
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
2基于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.xsd">
<!--把对象的创建交给spring来管理-->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
scope="" init-method="" destroy-method="" >
<property name="" value/ref=""></property>
</bean>
</beans>
3注解的context名称空间的配置
当使用类使用注解,需要让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: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在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为
context名称空间和约束中-->
<context:component-scan base-package="com.itheima"></context:component-scan>
</beans>
4案例:基于XML的IOC案例
4-1Maven
<dependencies>
<dependency>
<!--spring容器-->
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
<dependency>
<!--生产Connection对象的工厂类-->
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
<dependency>
<!--在spring框架中实现事务管理功能-->
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
<dependency>
<!--mysql连接器:帮助java程序操作mysql的驱动程序-->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<!--支持切入点表达式等等-->
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<!--spring整合junit-->
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
4-2 bean.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.xsd">
<!--配置业务层对象(service)-->
<bean id="accountService" class="com.itheima.service.impl.AccountImpl">
<!--注入dao对象:set方法注入-->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置dao对象-->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<!--注入QueryRunner对象-->
<property name="runner" ref="runner"></property>
</bean>
<!--配置QueryRunner对象-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--注入数据源:构造方法注入-->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property>
<property name="user" value="root"></property>
<property name="password" value="密码"></property>
</bean>
</beans>
=========================================================================
二关于springMVC配置
1Maven
<?xml version="1.0" encoding="UTF-8"?>
<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.kaikeba</groupId>
<artifactId>springmvc01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<!--依赖-->
<dependency>
<!--这个jar包中已经包含了spring-context jar包中的所有内容了,所以就不需要再导入spring-context jar包了-->
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
<dependency>
<!-- springMVC底层是封装的servlet,所以这个包必须要导入-->
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope><!--因为servlet在tomcat中已经提供了,这里代表未来打包的时候不会把javax.servlet-api打包进去
如果这个不写的话,未来运行会报错的-->
</dependency>
<dependency>
<!--数据格式转换为json-->
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<!--数据绑定-->
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<!--文件上传-->
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
<build>
<!--插件-->
<plugins>
<plugin><!--maven插件,可以不写-->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<!--这里表示maven插件将运行在jdk11的版本环境下-->
<target>1.8</target>
<source>1.8</source>
</configuration>
</plugin>
<plugin>
<!--tomcat插件-->
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8088</port>
</configuration>
</plugin>
</plugins>
</build>
</project>
2applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--spring的配置文件:除了控制器之外的bean对象都在这里扫描-->
<context:component-scan base-package="com.kkb.dao;com.kkb.service"></context:component-scan>
</beans>
3springmvc.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: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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--springMVC的配置文件:控制器的bean对象都在这里扫描-->
<context:component-scan base-package="com.kkb.controller"></context:component-scan>
<context:component-scan base-package="com.kkb.exceptions"></context:component-scan>
<!--注解驱动配置-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--视图解析器配置-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<!--这里value值为/,是因为文件在webapp这个跟路径下,
如果文件在webapp/jsp目录下,那么value的值为"/jsp/",前面/为根目录,后面jsp/为jsp目录-->
<property name="prefix" value="/"></property>
<!--后缀-->
<property name="suffix" value=".jsp"></property>
</bean>
<!--静态资源的处理-->
<!--<mvc:default-servlet-handler/>-->
<mvc:resources mapping="/images/**" location="/images"></mvc:resources>
<!--配置拦截器-->
<mvc:interceptors>
<!--可以按顺序配置多个拦截器-->
<mvc:interceptor>
<mvc:mapping path="/**"/><!--这里是拦截路径,/**表示拦截所有路径-->
<bean class="com.kkb.interceptor.MyInterceptor" id="myInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**"/><!--这里是拦截路径,/**表示拦截所有路径-->
<bean class="com.kkb.interceptor.MyInterceptor2" id="myInterceptor2"></bean>
</mvc:interceptor>
<mvc:interceptor>
<!--关于文件上传类型限制的拦截器配置-->
<mvc:mapping path="/**"/><!--这里是拦截路径,/**表示拦截所有路径-->
<bean class="com.kkb.interceptor.FileInterceptor" id="fileInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!--文件上传-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--文件上传的大小限制,以字节byte为单位,5M=1024*1024*5 1M=1024KB 1KB=1024B-->
<property name="maxUploadSize" value="5242880"></property><!--如果超出设定的大小就会报错-->
<!--设置默认编码格式-->
<property name="defaultEncoding" value="utf-8"></property>
</bean>
</beans>
4web.xml
<?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">
<!--进行spring的配置-->
<context-param><!--配置文件的上下文参数-->
<!--这里是对spring配置文件的位置进行说明-->
<param-name>contextConfigLocation</param-name><!--contextConfigLocation这个参数是不可以变的-->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<!--监听器-->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--springmvc的前端/核心/中央控制器配置-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name><!--这里叫什么都可以-->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!--如果没有这段代码,那么系统会默认查找WEB-INF文件夹下的名为dispatcherServlet-servlet.xml的配置文件,没有会报错-->
<!--这里查找的文件名为:servlet-name的参数+"-servlet",
比如这里的servlet-name值为springMVC,那么配置文件就是springMVC-servlet.xml-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!--表明创建的对象是不是在容器创建的时候创建,如果没有写就是什么时候用,什么时候创建。写了就是立即创建-->
<!--当有多个servlet时,数值越小优先级越高,当为负数时,就是什么时候用,什么时候创建-->
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<filter>
<!--使用Rest风格的URI 将页面普通的post请求转为指定的delete或者put请求-->
<filter-name>httpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置中文乱码的过滤器-->
<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>
<!--如果你有在servlet中写过编码方式,下面的设置会让那些编码方式都不生效,只有这里的设置生效-->
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern><!--过滤所有的请求-->
</filter-mapping>
</web-app>
=========================================================================
三关于Mybatis
1配置Maven
<?xml version="1.0" encoding="UTF-8"?>
<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.kaikeba</groupId>
<artifactId>mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<!--指定jdk的编译版本-->
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<!--配置jar包-->
<dependencies>
<!--mybatis的支持jar包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!--连接数据库的jar包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<!--日志的支持jar包-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<!-- 测试包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<!--分页查询插件的jar包-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.10</version>
</dependency>
</dependencies>
<build>
<!--插件-->
<plugins>
<!-- 编译器的版本(编译环境)-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!--反向生成的插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<!--mybatis自动生成的Maven插件-->
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<!--配置文件的路径-->
<!-- mybatis-generator-maven-plugin插件需要使用generatorConfig.xml配置文件-->
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<!--引入插件需要应用的jar包-->
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
<!-- 配置映射文件的扫描位置-->
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes> <filtering>false</filtering>
</resource>
</resources>
</build>
</project>
2编写Mybatis的配置文件:mybatis.xml
头信息可以去官网复制:mybatis – MyBatis 3 | 入门
<?xml version="1.0" encoding="UTF-8" ?>
<!--mybatis的头文件-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration:mybatis的全局配置文件-->
<configuration>
<!--mybatis的全局配置文件引入属性文件-->
<properties resource="jdbc.properties"></properties>
<settings>
<!-- 配置日志-->
<setting name="logImpl" value="LOG4J"/>
<!--开启二级缓存-->
<!--是否开启二级缓存,默认false-不开启,true-开启-->
<setting name="cacheEnabled" value="true"/>
</settings>
<!--自定义类型别名-->
<typeAliases>
<package name="com.kkb.pojo"/>
</typeAliases>
<!--配置插件-->
<plugins>
<!--配置分页插件-->
<!--在5.0版本之前使用的是PageHelper,在5.0版本之后使用PageInterceptor-->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--reasonable属性:是分页合理化,默认值为false,
当reasonable值为true时,当输入-1页时会显示第1页,当只有50页,输入60页时,会显示第50页-->
<property name="reasonable" value="true"/>
</plugin>
</plugins>
<!--environments:配置mybatis的环境-->
<environments default="development">
<!--id:自定义的数据源的名称-->
<environment id="development">
<!--transactionManager:事务的类型:JDBC 使用Connection对象的提交和回滚的方法-->
<transactionManager type="JDBC"/>
<!--<transactionManager type="MANAGED"/>-->
<!--dataSource:创建数据源: POOLED方式:表示使用连接池-->
<dataSource type="POOLED">
<!--创建数据源的必备的4大参数:可以从配置文件中读取-->
<!--使用属性文件中的值-->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--在配置文件中注册映射文件-->
<mappers>
<!--注册映射文件-->
<package name="com.kkb.mapper"/>
<package name="org.xzk.pojo"/>
<package name="org.xzk.mapper"/>
</mappers>
</configuration>
url的配置
<property name="url" value="jdbc:mysql://127.0.0.1:3306/数据表名称?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT"/>
3配置jdbc.properties文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
jdbc.username=root
jdbc.password=密码
4配置 接口类和数据库的表的映射文件
<?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">
<!--映射文件 实体类和数据库的表的映射
Mybatis采用的是ORM思想 Object(java对象) Relation(数据表) Mapping(映射)
映射文件就是抽取SQL语句的部分,将SQL语句从代码的硬编码中抽取出来了-->
<!--namespace="完全限定名,实体类的完全限定名"-->
<mapper namespace="com.kkb.mapper.GameRecordMapper">
<!--id是自定义的名称,不能重复;相当于原来的dao中的方法名称
resultType:返回值的类型,如果是集合的时候,写的是集合中的元素的类型
使用要求:实体类中的属性和表当中列名一致
parameterType:表示参数的类型,当参数唯一的时候才使用该属性,可以省略,框架可以自己判定类型
-->
<insert id="add" parameterType="com.kkb.pojo.GameRecord">
<!--selectKey:新增成功后将自增的ID赋值给参数属性
order:AFTER/BEFORE两个取值,表示selectKey中的sql语句在insert语句之前还是之后执行;
keyProperty:表示新增的id值赋值到哪个属性值中;resultType:表示返回值的类型-->
<selectKey order="BEFORE" keyProperty="recordId" resultType="java.lang.String">
select UUID()
</selectKey>
insert into gamerecord(recordId,homeTeamId,score,visitingTeamId)
values (#{recordId},#{homeTeamId},#{score},#{visitingTeamId})
</insert>
<!--id:相当于方法名称;parameterType:表示参数的类型;resultType:返回值的类型-->
<select id="findById" parameterType="java.lang.Integer" resultType="com.kkb.pojo.GameRecord">
select *
from gamerecord
where homeTeamId = #{homeTeamId}
</select>
</mapper>
注意:这里namespace是和映射文件对应的接口类的完全限定名
5MybatisUtil
package com.kkb.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
/**
* 工具类:获取连接和关闭连接
*/
public class MybatisUtil {
private static ThreadLocal<SqlSession> sqlSessionThreadLocal = new ThreadLocal<>();
private static SqlSessionFactory factory;
/**
* 因为创建工厂的过程是比较复杂的,整个过程只需要创建一次工厂即可,所以我们把他提取出来,只在类加载的时候执行一次就可以了
*/
static {
Reader reader = null;
try {
//读取配置文件
//reader = Resources.getResourceAsReader(resource);
reader = Resources.getResourceAsReader("mybatis.xml");
} catch (IOException e) {
e.printStackTrace();
}
//创建工厂
factory = new SqlSessionFactoryBuilder().build(reader);//根据图纸创建了工厂
}
/**
* 获取连接
* @return
*/
public static SqlSession getSqlSession() {
//从ThreadLocal中获取
SqlSession sqlSession = sqlSessionThreadLocal.get();
if (sqlSession == null){
//创建sqlSession
sqlSession = factory.openSession();
//将sqlSession与线程进行绑定
sqlSessionThreadLocal.set(sqlSession);
}
return sqlSession;
}
/**
* 关闭连接
*/
public static void closeSqlSession() {
//从ThreadLocal中获取
SqlSession sqlSession = sqlSessionThreadLocal.get();
if (sqlSession != null){
sqlSession.close();
//将sqlSession从本地线程中移除
sqlSessionThreadLocal.remove();
}
}
}
6配置日志log4j.properties
# Global logging configuration info warning error
log4j.rootLogger=DEBUG,stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
7配置反向生成插件的文件:generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器:标了序号的部分都需要修改为自己的内容 -->
<generatorConfiguration>
<!--1、数据库驱动jar:添加自己的jar路径 -->
<classPathEntry
location="/Users/dylanwang/repository/mysql/mysql-connector-java/8.0.27/mysql-connector-java-8.0.27.jar" />
<!--location="D:\repository\mysql\mysql-connector-java\8.0.23\mysql-connector-java-8.0.23.jar"-->
<context id="MyBatis" targetRuntime="MyBatis3">
<!--去除注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--2、数据库连接 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT"
userId="root"
password="密码">
<!--解决mysql8.0以后重复生成所有表的问题-->
<property name="nullCatalogMeansCurrent" value="true" />
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer;
为 true时把JDBC DECIMAL和NUMERIC类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!--3、生成实体类 指定包名 以及生成的地址 (可以自定义地址,但是路径不存在不会自动创建
使用Maven生成在target目录下,会自动创建) -->
<javaModelGenerator targetPackage="org.xzk.pojo"
targetProject="src/main/java">
<!--targetProject="src\main\resources"-->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--4、生成SQLmapper.xml映射文件 -->
<sqlMapGenerator targetPackage="org.xzk.mapper"
targetProject="src/main/resources">
</sqlMapGenerator>
<!--5、生成Dao(Mapper)接口文件,-->
<javaClientGenerator type="XMLMAPPER"
targetPackage="org.xzk.mapper"
targetProject="src/main/java">
</javaClientGenerator>
<!--6、要生成哪些表(更改tableName和domainObjectName就可以) -->
<!-- tableName:要生成的表名
enableCountByExample:Count语句中加入where条件查询,默认为true开启
enableUpdateByExample:Update语句中加入where条件查询,默认为true开启
enableDeleteByExample:Delete语句中加入where条件查询,默认为true开启
enableSelectByExample:Select多条语句中加入where条件查询,默认为true开启
selectByExampleQueryId:Select单个对象语句中加入where条件查询,默认为true开启
-->
<table tableName="Player">
<property name="useActualColumnNames" value="true"/>
</table>
<table tableName="gameRecord">
<property name="useActualColumnNames" value="true"/>
</table>
<table tableName="Team">
<property name="useActualColumnNames" value="true"/>
</table>
</context>
</generatorConfiguration>
<!--<table tableName="Team"
enableCountByExample="false"
enableUpdateByExample="false"
enableUpdateByPrimaryKey="false"
enableDeleteByExample="false"
enableDeleteByPrimaryKey="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
<property name="useActualColumnNames" value="true"/>
</table>-->
=========================================================================
四SSM整合
1Maven配置
<?xml version="1.0" encoding="UTF-8"?>
<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.kkb</groupId>
<artifactId>myssm_kkb</artifactId>
<version>1.0-SNAPSHOT</version>
<!--补齐打包方式-->
<packaging>war</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<!--SSM整合 spring+springMVC mybatis mysql等 -->
<!-- 集中定义依赖版本号 -->
<spring.version>5.2.13.RELEASE</spring.version>
<mybatis.version>3.5.6</mybatis.version>
<mybatis.spring.version>1.3.3</mybatis.spring.version>
<pagehelper.version>5.1.10</pagehelper.version>
<mysql.version>8.0.23</mysql.version>
<druid.version>1.2.3</druid.version>
<servlet-api.version>4.0.1</servlet-api.version>
<jackson.version>2.9.6</jackson.version>
<log4j.version>1.2.17</log4j.version>
<junit.version>4.12</junit.version>
</properties>
<!--依赖-->
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</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>
<!--事务aop相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mybatis和spring整合需要的jar包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${pagehelper.version}</version>
</dependency>
<!-- MySql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<!-- Jackson Json处理工具包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- log4j :日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- junit:测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!--spring的junit测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--@Resource注解的依赖-->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
<!-- 插件配置 -->
<build>
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会被扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<!-- 设置项目的编译版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- 设置tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<!-- 指定端口 -->
<port>8088</port>
<!-- 请求路径 -->
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
<!--反向生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<!--配置文件的路径-->
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
2mybatis.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>
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<!--spring 接管其他的工作 数据源 映射文件注册 插件-->
</configuration>
3log4j.properties:日志的配置文件
# Global logging configuration info warning error
log4j.rootLogger=DEBUG,stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
4 jdbc.properties:数据库的配置信息
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/myssm_kkb?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
jdbc.username=root
jdbc.password=密码
5spring.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:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd ">
<!--spring整合mybatis的工作:spring接管mybatis的工作:数据源、映射文件注册、插件-->
<!--读取配置文件:jdbc.properties-->
<context:property-placeholder location="classpath*:jdbc.properties"/>
<!--mybatis:创建数据源:在Maven中配置了Druid的数据源,所以这里就用DruidDataSource-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<!--驱动可以省略,代码自动会根据url推断-->
<!--连接数据库的四大参数-->
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--mybatis连接数据库-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--如果有mybatis的单独的配置文件,需要在此引入,如果没有则不需要引入-->
<property name="configLocation" value="classpath:mybatis.xml"/>
<!--数据源的配置-->
<property name="dataSource" ref="dataSource"/>
<!--配置别名-->
<property name="typeAliasesPackage" value="com.kkb.pojo"/>
<!--配置映射文件-->
<!--<property name="mapperLocations" value="com/kkb/mapper/*.xml"/>-->
<!--配置插件-->
<property name="plugins">
<array>
<!--分页插件-->
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<value>
reasonable=true
</value>
</property>
</bean>
</array>
</property>
</bean>
<!-- 统一产生接口的动态代理类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--下面的basePackage属性,表示将来要把哪个包的接口类的动态代理类,spring会帮你一次生成-->
<property name="basePackage" value="com.kkb.mapper"/>
</bean>
<!--通过注解的方式实现事务:spring接管事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--这些包中添加注解之后对象的创建权限就交给spring容器-->
<context:component-scan base-package="com.kkb.mapper,com.kkb.service"/>
</beans>
5springmvc.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: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 ">
<!--springmvc的配置文件:控制器的bean对象都在这里扫描-->
<context:component-scan base-package="com.kkb.controller"/>
<!--注解的驱动-->
<mvc:annotation-driven/>
<!--视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--希望将来所有的页面都放在pages目录下,放的所有的页面的后缀都是.html-->
<property name="prefix" value="/pages/"/>
<property name="suffix" value=".html"/>
</bean>
<!--静态资源处理-->
<mvc:resources mapping="/img/**" location="/img/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/fonts/**" location="/fonts/"/>
<mvc:resources mapping="/static/**" location="/static/"/>
<mvc:resources mapping="/pages/**" location="/pages/"/>
<!--文件上传-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
</beans>
6web.xml
<?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>/pages/index.html</welcome-file>
</welcome-file-list>
<!--spring的配置-->
<!--监听器:ContextLoaderListener-->
<context-param>
<!--contextConfigLocation:表示用于加载 Bean的配置文件
classpath和classpath*区别:
classpath:只会到你的class路径中查找找文件。
classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找。 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--SpringMVC的配置-->
<!--SpringMVC的核心控制器:DispatcherServlet-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 创建前端控制器的时候读取springmvc配置文件启动ioc容器 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:springmvc.xml</param-value>
</init-param>
<!-- Tomcat启动就创建此对象 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 配置拦截路径url,所有请求都会被前端控制器拦截处理 -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- HiddenHttpMethodFilter过滤器:使用Rest风格的URI 将页面普通的post请求转为指定的delete或者put请求
原理:在Ajax中发送post请求后,带_method参数,将其修改为PUT,或者DELETE请求-->
<filter>
<filter-name>httpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--注册字符集过滤器:post请求中文乱码问题的解决方案-->
<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>
<!--强制request使用字符集encoding-->
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<!--强制response使用字符集encoding-->
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
7generatorConfig.xml:反向生成实体类和dao的插件
这里generatorConfig.xml的名字已经在Maven中固定了,所以要修改这个名字的话,也要修改Maven中的配置:在177行‘反向生成插件’中,’配置文件的路径‘下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器:所有标有序号的内容都需要修改为自己的内容或者路径 -->
<generatorConfiguration>
<!--1、数据库驱动jar:添加自己的jar路径 -->
<classPathEntry
location="D:\repository\mysql\mysql-connector-java\8.0.23\mysql-connector-java-8.0.23.jar" />
<context id="MyBatis" targetRuntime="MyBatis3">
<!--去除注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--2、数据库连接 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/myssm_kkb?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT"
userId="root"
password="密码">
<!--解决mysql8.0以后重复生成所有表的问题-->
<property name="nullCatalogMeansCurrent" value="true" />
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer;
为 true时把JDBC DECIMAL和NUMERIC类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!--3、生成实体类 指定包名 以及生成的地址 (可以自定义地址,但是路径不存在不会自动创建
使用Maven生成在target目录下,会自动创建) -->
<javaModelGenerator targetPackage="com.kkb.pojo"
targetProject="src\main\java">
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--4、生成SQLmapper.xml文件 -->
<sqlMapGenerator targetPackage="com.kkb.mapper"
targetProject="src\main\resources">
</sqlMapGenerator>
<!--5、生成Dao(Mapper)文件,生成接口 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.kkb.mapper"
targetProject="src\main\java">
</javaClientGenerator>
<!--6、要生成哪些表(更改tableName和domainObjectName就可以) -->
<!-- tableName:要生成的表名
enableCountByExample:Count语句中加入where条件查询,默认为true开启
enableUpdateByExample:Update语句中加入where条件查询,默认为true开启
enableDeleteByExample:Delete语句中加入where条件查询,默认为true开启
enableSelectByExample:Select多条语句中加入where条件查询,默认为true开启
selectByExampleQueryId:Select单个对象语句中加入where条件查询,默认为true开启
-->
<table tableName="Team">
<property name="useActualColumnNames" value="true"/>
</table>
<table tableName="Player">
<property name="useActualColumnNames" value="true"/>
</table>
<table tableName="game">
<property name="useActualColumnNames" value="true"/>
</table>
<table tableName="GameType">
<property name="useActualColumnNames" value="true"/>
</table>
<table tableName="Admins">
<property name="useActualColumnNames" value="true"/>
</table>
<table tableName="AdminRole">
<property name="useActualColumnNames" value="true"/>
</table>
</context>
</generatorConfiguration>
这里有一条报错是不影响的