Mybatis配置文件目录
mybatis-config.xml(Mybatis核心配置文件)
可以参考官网:Mybatis官网
<?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">
<!--MyBatis 系统的核心设置,包括获取数据库连接实例的数据源(DataSource)以及决定事务作用域和控制方式的事务管理器-->
<!--核心配置文件-->
<configuration>
<!-- 引入外部文件-->
<properties resource="db.properties">
<!-- 可以在标签内增加属性-->
<!-- 当自定义属性和外部文件属性重名,优先引用外部属性-->
</properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<!-- jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false-->
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/xiang/dao/student/StudentMapper.xml"/>
</mappers>
</configuration>
LOG4J.properties(mybatis日志----LOG4J)
### 配置日志级别及appenderName ###
log4j.rootLogger=DEBUG,console,file
### 配置输出信息到控制抬 ###
log4j.appender.console=org.apache.log4j.ConsoleAppender
#默认值是System.out,指定输出控制台。
log4j.appender.console.Target=System.out
log4j.appender.console.Threshold=DEBUG
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=./log/xiang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][yixang:%d{yyyy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
Mybatis中的mapper.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="接口路径">
SQL语句
</mapper>
Mybatis核心工具类(MybatisUtils)
package com.xiang.utils;
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.InputStream;
//SqlSessionFactory SqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static{
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
Mybatis基础图解:
mybatis 缓存图解
mybatis 底层原理图解
Maven 项目配置目录:
Maven核心文件配置(pom.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!--pom文件是Maven的核心文件-->
<!--maven版本文件和头文件-->
<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>
<!-- 这里就是我们刚刚配置的GAV-->
<groupId>org.example.xiang</groupId>
<artifactId>servlet_demo1</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- package:项目打包方式-->
<!-- jar:java应用-->
<!-- war:javaweb应用-->
<packaging>war</packaging>
<name>servlet_demo1 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<!-- 配置-->
<properties>
<!-- 项目默认的编码格式-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 编码版本-->
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<!--项目依赖-->
<dependencies>
<!-- 具体依赖的jar包配置文件-->
<!-- maven高级之处在于它会导入当前jar包所依赖的所有jar包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<!--项目构建用的东西-->
<build>
<finalName>servlet_demo1</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
解决Maven项目资源导出问题
<build>
<!--配置resource防止资源导出失败ExceptionInInitializerError-->
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
Tomcat 配置文件:
<?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_3_1.xsd"
version="3.1"
metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
</web-app>
Smbms 项目web.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_3_1.xsd"
version="3.1"
metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<!--登录验证的servlet-->
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.xiang.servlet.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
<!--登录注销的servlet-->
<servlet>
<servlet-name>LoginOutServlet</servlet-name>
<servlet-class>com.xiang.servlet.user.LoginOutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginOutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
<!--用户密码修改的servlet-->
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.xiang.servlet.user.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/jsp/user.do</url-pattern>
</servlet-mapping>
<!-- 字符编码过滤器-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>com.xiang.filter.characterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--后台界面过滤器-->
<filter>
<filter-name>AdminFilter</filter-name>
<filter-class>com.xiang.filter.AdminFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AdminFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>
<!-- 设置错误页面-->
<error-page>
<error-code>404</error-code>
<location>/errors/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/errors/500.jsp</location>
</error-page>
<!-- 设置默认的Session过期时间;真实业务需求-->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- 设置欢迎页面-->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
Spring 常用配置
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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--此xml配置文件的名字应该为ApplicationContext.xml-->
<!-- 使用spring来创建对象,在spring这些都称为Bean
类型 变量 = new 类型();
bean=对象 new hello();
id 变量名
class:new 的对象类型
property相当于给对象的属性设置一个值
property中的属性ref是引用spring中创建好的对象
value:具体的值,基本数据类型
-->
<bean id="address" class="com.xiang.pojo.Address">
<property name="address" value="changsha"></property>
</bean>
<bean id="student" class="com.xiang.pojo.Student">
<!-- 第一种普通值注入-->
<property name="name" value="m-jiehua"></property>
<!-- 第二种注入,bean注入 ref-->
<property name="address" ref="address"></property>
<!-- 第三种 数组注入-->
<property name="bookes" >
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>三国演义</value>
<value>水浒传</value>
</array>
</property>
<!-- 4 list注入-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>看电影</value>
<value>打篮球</value>
</list>
</property>
<!-- 5 map注入-->
<property name="card">
<map>
<entry key="身份证" value="1231111111111111"></entry>
<entry key="银行卡" value="2222222222222222"></entry>
</map>
</property>
<!-- 6 set注入-->
<property name="games">
<set>
<value>lol</value>
<value>wzry</value>
</set>
</property>
<!-- 7 null注入-->
<property name="wife">
<null></null>
</property>
<!-- 8 properties注入-->
<property name="info">
<props>
<prop key="学号">1234556788</prop>
<prop key="phone">111111111111</prop>
<prop key="father">一</prop>
<prop key="mother">二</prop>
</props>
</property>
</bean>
</beans>
spring容器中IOC对象创建方式
IOC创建对象的方式:
1使用无参构造创造对象。
2假设我们要使用有参构造创建对象。
1.下标赋值
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg index="0" value="7500000"/>
<constructor-arg index="1" value="42"/>
</bean>
2.通过类型创建(不推荐使用)
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg type="int" value="7500000"/>
<constructor-arg type="java.lang.String" value="42"/>
</bean>
3.直接通过参数名来设置
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg name="years" value="7500000"/>
<constructor-arg name="ultimateAnswer" value="42"/>
</bean>
总结:在配置文件加载的时候,容器中管理的对象就已经开始初始化了。
spring中引入注解和AOP在配置文件中
<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://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/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 开启 注解的支持-->
<context:annotation-config></context:annotation-config>
</beans>
动态代理模式
动态生成代理类的万能工具类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//动态代理工具类
public class ProxyInvovationHandler implements InvocationHandler {
//被代理的接口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
}
//处理代理实例,并且返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result =method.invoke(target,args);
return result;
}
}
spring-mybatis整合配置文件
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- DataSource:使用spring的数据源来替换mybatis的配置, c3po dbcp druid
我们这里使用spring提供的JDBC:org.springframework.jdbc.datasource.DriverManagerDataSource
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 重点配置-->
<!-- 这里相当于SqlSessionFactoryBuild-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="mapperLocations" value="classpath:com/xiang/mapper/*.xml"></property>
</bean>
<!-- org.mybatis.spring.SqlSessionTemplate相当于SqlSession
这里只能用构造器注入
SqlSessionTemplate是mybatis-spring的核心
-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
</bean>
<!-- 配置声明式事务:-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 构造器注入 <constructor-arg ref="dataSource" />-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 结合AOP自动织入事务-->
<!-- 配置事务通知-->
<tx:advice id="txAvice" transaction-manager="transactionManager">
<!-- 给那些方法配置事务-->
<!-- 配置事务的传播特性-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.xiang.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAvice" pointcut-ref="txPointCut"></aop:advisor>
</aop:config>
</beans>
有两种整合方式:
1:利用set注入方式
package com.xiang.mapper;
import com.xiang.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper{
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> userList() {
return sqlSession.getMapper(UserMapper.class).userList();
}
public User selectUser(int id) {
return sqlSession.getMapper(UserMapper.class).selectUser(id);
}
}
2.:利用SqlSessionDaoSupport
SqlSessionDaoSupport 是一个抽象的支持类,用来为你提供 SqlSession。调用 getSqlSession() 方法你会得到一个 SqlSessionTemplate,之后可以用于执行 SQL 方法,就像下面这样:
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
public User getUser(String userId) {
return getSqlSession().selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId);
}
}
在这个类里面,通常更倾向于使用 MapperFactoryBean,因为它不需要额外的代码。但是,如果你需要在 DAO 中做其它非 MyBatis 的工作或需要一个非抽象的实现类,那么这个类就很有用了。
SqlSessionDaoSupport 需要通过属性设置一个 sqlSessionFactory 或 SqlSessionTemplate。如果两个属性都被设置了,那么 SqlSessionFactory 将被忽略。
假设类 UserMapperImpl 是 SqlSessionDaoSupport 的子类,可以编写如下的 Spring 配置来执行设置:
<bean id="userDao" class="org.mybatis.spring.sample.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
Thymeleaf maven依赖
<!-- thymeleaf,我们都是基于3.x的版本开发-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
命名空间导入
xmlns:th="http://www.thymeleaf.org"