SSM详细的过程,一套就够了
Posted SmallCuteMonkey
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSM详细的过程,一套就够了相关的知识,希望对你有一定的参考价值。
文章目录
- aop笔记
- SpringJDBC:
- Spring事务
- MyBatis笔记:
- SpringMVC笔记:
- SSM环境搭建:
- demo1: 使用SSM实现用的的登录和注册功能:
- demo2: 实现查询所有学生信息功能
- demo3: 使用PageHelper实现分页功能
- demo4: 实现学生信息的增删改查功能
- demo5: 使用拦截器实现用户未经登录不能访问主逻辑功能
- demo6: 实现用户头像的上传下载功能:
- demo7: 实现登录页面的国际化显示:
- SpringBoot环境搭建:
- SpringBoot+MyBatis实现增删改查
- Vue语法:
- 使用VUE搭建前端页面,实现前后端对接:
aop笔记
1. 通过xml配置aop
- 创建maven web工程
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ufDvBT1t-1629529406417)(image\\1.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8Y03l9aW-1629529406421)(image\\2.png)]
-
pom.xml文件导入依赖
<!-- 从这开始 --> <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> <!-- spring版本号 --> <spring.version>4.3.14.RELEASE</spring.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.7.22</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- spring --> <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> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.13</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</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-expression</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument-tomcat</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-jms</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</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-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis 包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!--mybatis spring 插件 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.45</version> </dependency> <!-- 上传下载 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>8.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>8.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.1</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- pagehelper分页插件 --> <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/com.github.jsqlparser/jsqlparser --> <dependency> <groupId>com.github.jsqlparser</groupId> <artifactId>jsqlparser</artifactId> <version>0.9.5</version> </dependency> <!-- poi上传下载组件 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.14-beta1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.14-beta1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14-beta1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans --> <dependency> <groupId>org.apache.xmlbeans</groupId> <artifactId>xmlbeans</artifactId> <version>2.6.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> </dependencies> <!-- 到这结束 -->
- 编写相应的javaBean类
package com.zjj.pojo;
public class Printer {
public void print(){
System.out.println("打印机正在打印。。。。。");
}
}
package com.zjj.pojo;
public class Logger {
public void loggerBefore(){
System.out.println("方法开始执行了。。。。。");
}
public void loggerAfter(){
System.out.println("方法执行完毕了。。。。。");
}
}
package com.zjj.pojo;
import java.util.Date;
public class Timer {
Date date=new Date();
public void showTime(){
System.out.println("当前时间是: "+date);
}
}
4. 创建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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
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-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<!--基于xml方式来实现aop配置-->
<bean id="p" class="com.zjj.pojo.Printer"></bean>
<bean id="log" class="com.zjj.pojo.Logger"></bean>
<bean id="time" class="com.zjj.pojo.Timer"></bean>
<!--aop配置-->
<aop:config>
<!--配置切入点-->
<aop:pointcut id="addMethods" expression="execution(* com.zjj.pojo.*.*(..) )"/>
<!--配置切面1 order 优先级 值越小 优先级越高-->
<aop:aspect id="t" ref="time" order="1">
<aop:before method="showTime" pointcut-ref="addMethods"></aop:before>
<aop:after method="showTime" pointcut-ref="addMethods"></aop:after>
</aop:aspect>
<!--配置切面2 order 优先级 值越小 优先级越高-->
<aop:aspect id="l" ref="log" order="2">
<aop:before method="loggerBefore" pointcut-ref="addMethods"></aop:before>
<aop:after method="loggerAfter" pointcut-ref="addMethods"></aop:after>
</aop:aspect>
</aop:config>
</beans>
5. 测试相应代码 ,单元测试
import com.zjj.pojo.Printer;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAop1 {
@Test
public void test1(){
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
Printer printer= (Printer) ctx.getBean("p");
printer.print();
}
}
2. 通过注解配置aop
-
创建maven web工程 同上
-
在pom.xml文件里面引入依赖 同上
-
编写相应的javaBean类
package com.zjj.pojo; import org.springframework.stereotype.Component; @Component public class Printer { public void print(){ System.out.println("打印机正在打印。。。。。"); } }
package com.zjj.pojo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
@Aspect
@Order(2)
public class Timer {
Date date=new Date();
@Around("execution(* com.zjj.pojo.*.*(..))")
public void showTime(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("开始时间是: "+date);
joinPoint.proceed();//在此方法上面的逻辑之前Before 之后的逻辑之后After
System.out.println("结束时间是: "+date);
}
}
package com.zjj.pojo;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Aspect
@Order(1)
public class Logger {
@Before("execution(* com.zjj.pojo.*.*(..))")
public void loggerBefore(){
System.out.println("方法开始执行了。。。。。");
}
@After("execution(* com.zjj.pojo.*.*(..))")
public void loggerAfter(){
System.out.println("方法执行完毕了。。。。。");
}
}
-
创建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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" 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-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <!--配置组件扫描器--> <context:component-scan base-package="com.zjj"/> <!--配置aop相应的注解支持--> <aop:aspectj-autoproxy/> </beans>
-
测试相应代码 ,单元测试
import com.zjj.pojo.Printer;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAop2 {
@Test
public void test2(){
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
Printer printer = ctx.getBean(Printer.class);
printer.print();
}
}
=========================================================================================================
SpringJDBC:
正常jdbc连接数据库流程:
- 注册驱动 修建仓库
- 获取连接 修路
- 获取Statement或者PreparedStatement对象 造车
- 执行sql操作 拉货
- 处理结果集 查询的时候会有结果集 卸货
- 关闭资源 车毁了,路砸了
spring框架: http://www.spring.io
使用spring data jdbc流程:
-
创建maven web project
-
pom.xml文件导入相关依赖
-
创建application.xml文件 spring配置文件
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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" 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-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <!--驱动名--> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <!--url--> <property name="url" value="jdbc:mysql://localhost:3306/b?characterEncoding=utf-8&useSSL=true"/> <!--用户名--> <property name="username" value="root"/> <!--密码--> <property name="password" value="123456"/> </bean> <!--配置JDBC模板--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <!--配置组件扫描器--> <context:component-scan base-package="com.zjj"/> </beans>
-
创建实体类,dao层代码,service层代码,编写相应逻辑
User:
package com.zjj.pojo; public class User { Long id; String username; String password; Integer isAdmin; public User() { } public User(Long id, String username, String password, Integer isAdmin) { this.id = id; this.username = username; this.password = password; this.isAdmin = isAdmin; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } 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 getIsAdmin() { return isAdmin; } public void setIsAdmin(Integer isAdmin) { this.isAdmin = isAdmin; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\\'' + ", password='" + password + '\\'' + ", isAdmin=" + isAdmin + '}'; } }
UserDao:
package com.zjj.dao; import com.zjj.pojo.User; import java.util.List; public interface UserDao { public List<User> queryAll(); public User queryOneById(Long id); public void addOne(User user); public void updateOne(User user); public void deleteOneById(Long id); }
-
dao实现类里面 注入 JdbcTemplate
UserDaoImpl:
package com.zjj.dao.impl; import com.zjj.dao.UserDao; import com.zjj.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Map; @Repository public class UserDaoImpl implements UserDao { @Autowired private JdbcTemplate jdbcTemplate; /* 查询 : query() 查询所有 queryForObject() 查询单个 update() 增删改 */ @Override public List<User> queryAll() { String sql="select * from tb_user"; //将查询出来的结果集合pojo实体类对应 RowMapper<User> rowMapper=new BeanPropertyRowMapper<>(User.class); return jdbcTemplate.query(sql, rowMapper); } @Override public User queryOneById(Long id) { String sql="select * from tb_user where id=?"; //将查询出来的结果集合pojo实体类对应 RowMapper<User> rowMapper=new BeanPropertyRowMapper<>(User.class); //参数可变参数 和sql语句占位符个数及位置保持一致 return jdbcTemplate.queryForObject(sql, rowMapper, id); } @Override public void addOne(User user) { String sql="INSERT INTO `tb_user` (`id`, `username`, `password`, `isadmin`) VALUES (?, ?, ?, ?)"; jdbcTemplate.update(sql,user.getId(),user.getUsername(),user.getPassword(),user.getIsAdmin()); } @Override public void updateOne(User user) { String sql="UPDATE `tb_user` SET `username`=?, `password`=?, `isadmin`=? WHERE (`id`=?)"; jdbcTemplate.update(sql,user.getUsername(),user.getPassword(),user.getIsAdmin(),user.getId()); } @Override public void deleteOneById(Long id) { String sql="delete from tb_user where id=?"; jdbcTemplate.update(sql,id); } }
-
实现增删改查相应操作
UserService:
package com.zjj.service;
import com.zjj.pojo.User;
import java.util.List;
public interface UserService {
public void queryAll();
public void queryOneById(Long id);
public void addOne(User user);
public void updateOne(User user);
public void deleteOneById(Long id);
}
UserServiceImpl:
package com.zjj.service.impl;
import com.zjj.dao.UserDao;
import com.zjj.pojo.User;
import com.zjj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public void queryAll() {
List<User> users = userDao.queryAll();
System.out.println(users);
}
@Override
public void queryOneById(Long id) {
User user = userDao.queryOneById(id);
System.out.println(user);
}
@Override
public void addOne(User user) {
userDao.addOne(user);
}
@Override
public void updateOne(User user) {
userDao.updateOne(user);
}
@Override
public void deleteOneById(Long id) {
userDao.deleteOneById(id);
}
}
7.单元测试
package test;
import com.zjj.pojo.User;
import com.zjj.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test1 {
@Test
public void testQueryAll(){
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService= ctx.getBean(UserService.class);
userService.queryAll();
}
@Test
public void testQueryOne(){
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService= ctx.getBean(UserService.class);
userService.queryOneById(1L);
}
@Test
public void testAddOne(){
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService= ctx.getBean(UserService.class);
User user=new User(7L,"曹浩","111111",1);
//注意主键 不能重复 唯一非空
userService.addOne(user);
}
@Test
public void testUpdateOne(){
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService= ctx.getBean(UserService.class);
User user=new User(7L,"孙权","222222",0);
//注意主键 不能重复 唯一非空
userService.updateOne(user);
}
@Test
public void testDeleteOne(){
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService= ctx.getBean(UserService.class);
//注意主键 不能重复 唯一非空
userService.deleteOneById(7L);
}
}
增加AOP切入功能:
在service层增删改查逻辑里面切入时间日志:
-
编写切面类
package com.zjj.pojo; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; import java.util.Date; @Component @Aspect public class Logger { Date date=new Date(); @Around("execution(* com.zjj.service.impl.*.*(..))") public void logger(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("开始执行时间是: "+date); joinPoint.proceed(); System.out.println("执行结束时间是: "+date); } }
-
配置切面注解支持
<!--aop注解支持--> <aop:aspectj-autoproxy/>
-
测试调用
@Test public void testQueryAll(){ ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService= ctx.getBean(UserService.class); userService.queryAll(); }
-
运行结果
开始执行时间是: Mon Mar 29 11:21:56 CST 2021 [User{id=1, username='张三', password='123456', isAdmin=0}, User{id=2, username='李四2', password='111111', isAdmin=1}, User{id=3, username='wangwu', password='111111', isAdmin=0}, User{id=5, username='武松', password='7843784', isAdmin=1}, User{id=6, username='武松', password='7843784', isAdmin=1}] 执行结束时间是: Mon Mar 29 11:21:56 CST 2021
Spring事务
事务概念:
一系列操作指令的集合,组成一个事务。成功同时成功,有一个不成功就都不成功。
特征:
数据库事务 transanction 正确执行的四个基本要素。
ACID: 原子性(Atomicity)、一致性(Correspondence)、隔离 性(Isolation)、持久性(Durability)。
(1)原子性:整个事务中的所有操作,要么全部完成,要么全部不完成,不可能停滞在中间某个环节。事务在执行过程中发生错误,会被回滚(Rollback)到事务开始前的状态,就像这个事务从来没有执行过一样。
(2)一致性:在事务开始之前和事务结束以后,数据库的完整性约束没有被破坏。
(3)隔离性:隔离状态执行事务,使它们好像是系统在给定时间内执行的唯一操作。如果有两个事务,运行在相同的时间内,执行 相同的功能,事务的隔离性将确保每一事务在系统中认为只有该事务在使用系统。这种属性有时称为串行化,为了防止事务操作间的混淆, 必须串行化或序列化请 求,使得在同一时间仅有一个请求用于同一数据。
(4)持久性:在事务完成以后,该事务所对数据库所作的更改便持久的保存在数据库之中,并不会被回滚。
两种实现方式:
基于xml方式实现声明式事务
-
pom文件里面添加事务的依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency>
-
在xml配置文件配置事务的相关配置
applicationContext.xml
<!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置事务的通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- 配置事务的属性 isolation:用于指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。 propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。 read-only:用于指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写。 timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位。 rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值。表示任何异常都回滚。 no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。 --> <tx:attributes> <tx:method name="*" propagation="REQUIRED" read-only="false"/> <tx:method name="add*" propagation="REQUIRED" read-only="false"/> <tx:method name="update*" propagation="REQUIRED" read-only="false"/> <tx:method name="query*" propagation="SUPPORTS" read-only="true"></tx:method> </tx:attributes> </tx:advice> <!-- 配置aop--> <aop:config> <!-- 配置切入点表达式--> <aop:pointcut id="pt1" expression="execution(* com.zjj.service.impl.*.*(..))"></aop:pointcut> <!--建立切入点表达式和事务通知的对应关系 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor> </aop:config>
-
UserServiceImpl里面编写方法
@Override public void addTwo() { User user1=new User(7L,"张飞","123456",1); User user2=new User(1L,"刘备","123456",0); userDao.addOne(user1);//正常可以执行成功 userDao.addOne(user2);//主键重复 必定添加失败 报错 //由于切入了事务,user1和user2都一起失败 事务 要么一起成功 要么一起失败 }
-
Test单元测试
@Test public void testAddTwo(){ ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService= ctx.getBean(UserService.class); userService.addTwo(); }
最终结果user1和user2都没有添加成功,因为user2失败,所以一起失败! 事务要么一起成功,要么一起失败
基于注解方式来实现声明式事务
-
pom.xml文件引入spring-tx依赖 同上
-
在applicatiionContext.xml文件里面配置事务管理器及事务的注解支持
<!--注解方式配置事务--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--配置事务的注解驱动--> <tx:annotation-driven transaction-manager="transactionManager"/>
-
在要事务操作的类上面配置注解
UserServiceImpl
@Service @Transactional public class UserServiceImpl implements UserService { ... }
-
单元测试调用
@Test public void testAddTwo(){ ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService= ctx.getBean(UserService.class); userService.addTwo(); }
结果同上,全部没有添加进去,因为事务 一起失败
MyBatis笔记:
什么是MyBatis?
- 基于java的数据库持久化框架。 使用java开发,做数据持久化。
- 它是一个轻量级,半自动的orm持久化框架。一个轻量级,一个orm框架(Hibernate)数据库表和对象映射。
- 通过映射xml来完成数据操作。在映射文件里面写sql语句
ORM: Object Relation Mapping 对象关系映射
mybatis环境搭建:
使用maven工程,mybatis是对jdbc的封装
0. 数据库表
1. 创建maven project
2. pom.xml 文件里面引入 mybatis和mysql依赖
<dependencies>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
3. 创建实体类, dao接口
User:
package com.zjj.pojo;
public class User {
private Long id;
private String username;
private String password;
private Integer isadmin;
public User() {
}
public User(Long id, String username, String password, Integer isadmin) {
this.id = id;
this.username = username;
this.password = password;
this.isadmin = isadmin;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 getIsadmin() {
return isadmin;
}
public void setIsadmin(Integer isadmin) {
this.isadmin = isadmin;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\\'' +
", password='" + password + '\\'' +
", isadmin=" + isadmin +
'}';
}
}
UserDao:
package com.zjj.dao;
import com.zjj.pojo.User;
public interface UserDao {
public User findUserById(Long id);
}
4. 创建并配置mybatis配置文件
需要先引入mybatis-3-config.dtd文件
settings---->Schemas and DTDs------>右边点击 + 新建 ------>弹框 uri 输入 http://mybatis.org/dtd/mybatis-3-config.dtd file 选择本机mybatis-3-config.dtd文件 ---->apply—>ok
创建数据库连接的properties文件 db.properties,配置数据库连接相关信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/b?characterEncoding=utf-8&userSSL=false
jdbc.username=root
jdbc.password=123456
创建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>
<!-- 加载属性文件 -->
<properties resource="db.properties">
<!--properties中还可以配置一些属性名和属性值 -->
</properties>
<!-- 全局配置参数,需要时再设置 -->
<!-- http://www.mybatis.org/mybatis-3/zh/configuration.html -->
<!-- 别名定义 -->
<typeAliases>
<package name="com.zjj.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<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>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
5. 创建并配置mybatis映射文件
UserMapper.xml
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zjj.dao.UserDao">
<select id="findUserById" resultType="User" parameterType="long">
select * from tb_user where id=#{id}
</select>
</mapper>
6. 单元测试调用
package test;
import com.zjj.dao.UserDao;
import com.zjj.pojo.User;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class Test1 {
@Test
public void testQueryOne() throws IOException {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession session = sqlSessionFactory.openSession();
UserDao userDao= session.getMapper(UserDao.class);
User user = userDao.findUserById(1L);
System.out.println(user);
session.close();
}
}
MyBatis配置文件:
类型别名(typeAliases)
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。例如:
<typeAliases>
<typeAlias alias="User" type="com.zjj.pojo.User"/>
<typeAlias alias="Student" type="com.zjj.pojo.Student"/>
</typeAliases>
当这样配置时,User可以用在任何使用 com.zjj.pojo.User 的地方。
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
<typeAliases>
<package name="com.zjj.pojo"/>
</typeAliases>
Mappers 映射文件(映射文件路径)
Mapper配置的几种方法:
第一种(常用)
如:
第二种
使用完全限定路径
如:
第三种
使用mapper接口类路径
如:
注意:此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。
第四种(推荐)
注册指定包下的所有mapper接口
如:
注意:此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。
MyBatis映射文件:
Insert:
MySQL、SQL Server等数据库的表格可以采用自动递增的字段作为主键。
有时可能需要使用这个刚刚产生的主键,用以关联其他业务
UserMaper.xml
<!-- 添加一个用户,成功后将主键值回填给id(User类的属性)-->
<insert id="addUser" parameterType="User" keyProperty="id" useGeneratedKeys="true">
INSERT INTO tb_user ( `username`, `password`, `isadmin`) VALUES ( #{username}, #{password}, #{isadmin})
</insert>
Test测试类:
@Test
public void testInsert() throws IOException {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession session = sqlSessionFactory.openSession(true);
UserDao userDao= session.getMapper(UserDao.class);
User user=new User("关羽","123456",1);
userDao.addUser(user);
System.out.println(user);
session.close();
}
基于xml的映射和基于接口方式的映射:
基于xml方式映射:
直接定位到xml映射文件里面的某个标签
@Test
public void test1() throws IOException {
//加载配置文件 并读取 通过IO流
//1. 获取输入流
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession session = sqlSessionFactory.openSession();
//namespace.id
/*
selectOne() 查询单个
selectList() 查询所有
insert() 添加
update() 修改
delete() 删除
*/
User u = session.selectOne("com.zjj.dao.UserDao.queryUserById", 1L);
System.out.println(u);
session.close();
}
基于接口方式来映射:
//基于接口方式来映射
@Test
public void test2() throws IOException {
//加载配置文件 并读取 通过IO流
//1. 获取输入流
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession session = sqlSessionFactory.openSession();
//获取接口对象
UserDao userDao = session.getMapper(UserDao.class);
User user = userDao.queryUserById(2L);
System.out.println(user);
session.close();
}
mybatis单表增删改查:
-
工程结构,配置信息同上
-
UserDao接口里面增删改查方法
UserDao:
package com.zjj.dao; import com.zjj.pojo.User; import java.util.List; public interface UserDao { //查询单个 public User queryUserById(Long id); //查询所有 public List<User> queryAllUsers(); //添加 public void addUser(User user); //添加,并获取添加之后的自增的主键Id public void addUser2(User user); //修改 public void updateUser(User user); //删除 public void deleteUserById(Long id); }
-
UserMapper.xml映射文件里面配置增删改查映射
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace 值必须和接口路径保持一致--> <mapper namespace="com.zjj.dao.UserDao"> <!-- id值必须和接口里面的方法名保持一致 --> <select id="queryUserById" parameterType="long" resultType="User"> select * from tb_user where id= #{id} </select> <!--查询所有 --> <select id="queryAllUsers" resultType="User"> select * from tb_user </select> <!-- 添加,,并获取添加之后的自增的主键Id --> <insert id="addUser2" parameterType="User" keyProperty="id" useGeneratedKeys="true"> INSERT INTO tb_user ( `username`, `password`, `isadmin`) VALUES ( #{username},#{password} ,#{isadmin} ) </insert> <!-- 添加 --> <insert id="addUser" parameterType="User"> INSERT INTO tb_user ( `username`, `password`, `isadmin`) VALUES ( #{username},#{password} ,#{isadmin} ) </insert> <!--修改--> <update id="updateUser" parameterType="User"> UPDATE tb_user SET username=#{username}, `password`=#{password}, `isadmin`=#{isadmin} WHERE (`id`= #{id}); </update> <!-- 删除 --> <delete id="deleteUserById" parameterType="long"> delete from tb_user where id=#{id} </delete> </mapper>
-
单元测试测试调用
package test; import com.zjj.dao.UserDao; import com.zjj.pojo.User; 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 org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; public class Test1 { //基于xml方式来映射 @Test public void test1() throws IOException { //加载配置文件 并读取 通过IO流 //1. 获取输入流 InputStream in = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); SqlSession session = sqlSessionFactory.openSession(); //namespace.id /* selectOne() 查询单个 selectList() 查询所有 insert() 添加 update() 修改 delete() 删除 */ User u = session.selectOne("com.zjj.dao.UserDao.queryUserById", 1L); System.out.println(u); session.close(); } //基于接口方式来映射 @Test public void test2() throws IOException { //加载配置文件 并读取 通过IO流 //1. 获取输入流 InputStream in = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); SqlSession session = sqlSessionFactory.openSession(); //获取接口对象 UserDao userDao = session.getMapper(UserDao.class); User user = userDao.queryUserById(2L); System.out.println(user); session.close(); } @Test public void testQueryAll() throws IOException { //加载配置文件 并读取 通过IO流 //1. 获取输入流 InputStream in = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); SqlSession session = sqlSessionFactory.openSession(); //获取接口对象 UserDao userDao = session.getMapper(UserDao.class); List<User> users = userDao.queryAllUsers(); System.out.println(users); session.close(); } @Test public void testInsert() throws IOException { //加载配置文件 并读取 通过IO流 //1. 获取输入流 InputStream in = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); //sqlSessionFactory.openSession(true); 设置自动提交 SqlSession session = sqlSessionFactory.openSession(true); //获取接口对象 UserDao userDao = session.getMapper(UserDao.class); User user=new User("吕布","123456",1); userDao.addUser(user); //增删改会对数据库里面的数据发生改变,必须提交事务 //session.commit();//手动提交 session.close(); } @Test public void testInsert2() throws IOException { //加载配置文件 并读取 通过IO流 //1. 获取输入流 InputStream in = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); //sqlSessionFactory.openSession(true); 设置自动提交 SqlSession session = sqlSessionFactory.openSession(true); //获取接口对象 UserDao userDao = session.getMapper(UserDao.class); User user=new User("马超","123456",1); userDao.addUser2(user); System.out.println(user); //增删改会对数据库里面的数据发生改变,必须提交事务 //session.commit();//手动提交 session.close(); } @Test public void testUpdate() throws IOException { //加载配置文件 并读取 通过IO流 //1. 获取输入流 InputStream in = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); //sqlSessionFactory.openSession(true); 设置自动提交 SqlSession session = sqlSessionFactory.openSession(true); //获取接口对象 UserDao userDao = session.getMapper(UserDao.class); User user=new User(1L,"貂蝉","123456",1); userDao.updateUser(user); //增删改会对数据库里面的数据发生改变,必须提交事务 //session.commit();//手动提交 session.close(); } @Test public void testDelete() throws IOException { //加载配置文件 并读取 通过IO流 //1. 获取输入流 InputStream in = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); //sqlSessionFactory.openSession(true); 设置自动提交 SqlSession session = sqlSessionFactory.openSession(true); //获取接口对象 UserDao userDao = session.getMapper(UserDao.class); userDao.deleteUserById(11L); //增删改会对数据库里面的数据发生改变,必须提交事务 //session.commit();//手动提交 session.close(); } }
使用ResultMap标签解决属性名和字段名冲突不一致的情形:
-
创建数据库表tb_stu表:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-A4SrvNtV-1629529406423)(image\\tb_stu.png)]
-
Student实体类
package com.zjj.pojo; import java.util.Date; public class Student { private Integer stuId; private String stuName; private Date birthday; private String address; public Student() { } public Student(Integer stuId, String stuName, Date birthday, String address) { this.stuId = stuId; this.stuName = stuName; this.birthday = birthday; this.address = address; } public Integer getStuId() { return stuId; } public void setStuId(Integer stuId) { this.stu
以上是关于SSM详细的过程,一套就够了的主要内容,如果未能解决你的问题,请参考以下文章
备战八月,Nginx最细最权威面试题,秒杀全网 有这套就够了!(精心整理)