概述
代码实现
//@Transactional(rollbackFor = FileNotFoundException.class,noRollbackFor = ArithmeticException.class)
@Transactional(rollbackFor = Exception.class)
@Override
public void addUser(User inputUser) throws Exception {
System.out.println("UserServiceImpl addUser");
userDao.addUser(inputUser);
//运行时异常,会回滚
System.out.println(1 / 0);
//编译期异常
//new FileInputStream("a");
}
隔离级别
代码实现
@Transactional(isolation = Isolation.REPEATABLE_READ)
@Override
public void addUser(User inputUser) throws Exception {
System.out.println("UserServiceImpl addUser");
userDao.addUser(inputUser);
//运行时异常,会回滚
System.out.println(1 / 0);
//编译期异常
//new FileInputStream("a");
}
@Transactional(isolation = Isolation.REPEATABLE_READ)
@Override
public List selectUserList() throws Exception {
List userList = userDao.selectUserList();
userList = userDao.selectUserList();
return userList;
}
需求
REQUIRED
//事务管理员
@Transactional(isolation = Isolation.REPEATABLE_READ)
@Override
public List<User> selectUserList() throws Exception {
List<User> userList = userDao.selectUserList();
userList = userDao.selectUserList();
return userList;
}
//事务协调员
@Transactional(propagation = Propagation.REQUIRED)
@Override
public void addLog(String content) throws Exception {
logDao.addLog(content);
System.out.println(1 / 0);
}
注意事项
概述
开发步骤
①引入相关依赖
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
<junit.version>4.13.2junit.version>
<lombok.version>1.18.22lombok.version>
<spring.version>5.3.13spring.version>
<dbutils.version>1.7dbutils.version>
<druid.version>1.2.8druid.version>
<mysql.version>5.1.48mysql.version>
<mybatis.version>3.5.7mybatis.version>
<mybatis-spring.version>2.0.6mybatis-spring.version>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>${junit.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>${lombok.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-expressionartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jclartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>${mybatis-spring.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>${druid.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
dependencies>
②定义service及其实现子类
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<User> selectUserList() throws Exception {
return userDao.selectUserList();
}
}
③定义dao及其实现子类
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Override
public List<User> selectUserList() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> userList = sqlSession.selectList("selectUserList");
sqlSession.close();
return userList;
}
}
④编写spring-core.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"
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">
<context:component-scan base-package="com.atguigu">context:component-scan>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="configLocation" value="SqlMapConfig.xml">property>
bean>
<context:property-placeholder location="jdbc.properties">context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driverClass}">property>
<property name="url" value="${url}">property>
<property name="username" value="${user}">property>
<property name="password" value="${password}">property>
bean>
beans>
⑤代码测试
public class UserController {
public static void main(String[] args) throws Exception {
//Spring容器初始化
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-core.xml");
UserService userService = applicationContext.getBean(UserService.class);
List<User> userList = userService.selectUserList();
System.out.println("userList = " + userList);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-core.xml")
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void selectUserList() throws Exception {
List<User> userList = userService.selectUserList();
System.out.println("userList = " + userList);
}
}
存在问题
概述
优化一
@Repository
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
//给UserDaoImpl的父类SqlSessionDaoSupport注入SqlSessionFactory对象
@Autowired
@Override
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
super.setSqlSessionFactory(sqlSessionFactory);
}
@Override
public List<User> selectUserList() throws Exception {
List<User> userList = getSqlSession().selectList("selectUserList");
return userList;
}
}
优化二
public class BaseDao extends SqlSessionDaoSupport {
@Autowired
@Override
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
super.setSqlSessionFactory(sqlSessionFactory);
}
}
@Repository
public class UserDaoImpl extends BaseDao implements UserDao {
@Override
public List<User> selectUserList() throws Exception {
List<User> userList = getSqlSession().selectList("selectUserList");
return userList;
}
}
概述
开发步骤
①定义service接口及其实现子类
②定义dao接口
③编写spring-core.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"
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">
<context:component-scan base-package="com.atguigu">context:component-scan>
<bean class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.atguigu.mapper.UserMapper">property>
<property name="sqlSessionFactory" ref="sqlSessionFactory">property>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="configLocation" value="SqlMapConfig.xml">property>
bean>
<context:property-placeholder location="jdbc.properties">context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driverClass}">property>
<property name="url" value="${url}">property>
<property name="username" value="${user}">property>
<property name="password" value="${password}">property>
bean>
beans>
④代码测试
存在问题
概述
代码实现
<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">
<context:component-scan base-package="com.atguigu">context:component-scan>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.atguigu.mapper">property>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="configLocation" value="SqlMapConfig.xml">property>
bean>
<context:property-placeholder location="jdbc.properties">context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driverClass}">property>
<property name="url" value="${url}">property>
<property name="username" value="${user}">property>
<property name="password" value="${password}">property>
bean>
beans>
开发步骤
①引入相关依赖
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.2.7version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>1.7.32version>
dependency>
②编写logback.xml
<configuration debug="true">
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%npattern>
encoder>
appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
root>
<logger name="java.sql">
<level value="debug"/>
logger>
<logger name="org.apache.ibatis">
<level value="info"/>
logger>
<logger name="com.atguigu.controller.UserController">
<level value="debug"/>
logger>
configuration>
③代码测试
public class UserController {
public static Logger logger = LoggerFactory.getLogger(UserController.class);
public static void main(String[] args) throws Exception {
//Spring容器初始化
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-core.xml");
UserService userService = applicationContext.getBean(UserService.class);
List<User> userList = userService.selectUserList();
logger.debug("userList : " + userList);
}
}
开发步骤
①引入相关依赖
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>5.2.1version>
dependency>
②编写UserService
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public PageInfo<User> selectUserListByPage(Integer currentPage, Integer pageSize) throws Exception {
PageHelper.startPage(currentPage,pageSize);
List<User> userList = userMapper.selectUserList();
return new PageInfo<>(userList);
}
}
③编写SqlMapConfig.xml
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="reasonable" value="true"/>
plugin>
plugins>
开发步骤
①编写spring-core.xml
<tx:annotation-driven transaction-manager="transactionManager">tx:annotation-driven>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
②编写UserService
@Transactional
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void addUser(User inputUser) throws Exception {
userMapper.addUser(inputUser);
System.out.println(1 / 0);
}
@Override
public List<User> selectUserList() throws Exception {
return userMapper.selectUserList();
}
@Override
public PageInfo<User> selectUserListByPage(Integer currentPage, Integer pageSize) throws Exception {
PageHelper.startPage(currentPage, pageSize);
List<User> userList = userMapper.selectUserList();
return new PageInfo<>(userList);
}
}
需求
开发步骤
①创建web项目
②Spring整合MyBatis
③编写UserController
@WebServlet("/selectUserList")
public class UserController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//初始化Spring容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-core.xml");
UserService userService = applicationContext.getBean(UserService.class);
try {
//使用Spring容器中的UserService对象
List<User> userList = userService.selectUserList();
System.out.println("userList = " + userList);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
存在问题
概述
解决方案
代码实现
public class MyContextLoaderListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
//项目启动,初始化Spring容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-core.xml");
sce.getServletContext().setAttribute("applicationContext", applicationContext);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
//项目销毁
}
}
<listener>
<listener-class>com.atguigu.listenter.MyContextLoaderListenerlistener-class>
listener>
@WebServlet("/selectUserList")
public class UserController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//初始化Spring容器
//ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-core.xml");
ApplicationContext applicationContext = (ApplicationContext) getServletContext().getAttribute("applicationContext");
UserService userService = applicationContext.getBean(UserService.class);
try {
//使用Spring容器中的UserService对象
List<User> userList = userService.selectUserList();
System.out.println("userList = " + userList);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
存在问题
概述
代码实现
<web-app>
<display-name>Archetype Created Web Applicationdisplay-name>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-core.xmlparam-value>
context-param>
<listener>
<listener-class>com.atguigu.listenter.MyContextLoaderListenerlistener-class>
listener>
web-app>
public class MyContextLoaderListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
//获取contextConfigLocation全局变量的值=spring-core.xml
String contextConfigLocation = sce.getServletContext().getInitParameter("contextConfigLocation");
//项目启动,初始化Spring容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(contextConfigLocation);
sce.getServletContext().setAttribute("applicationContext", applicationContext);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
//项目销毁
}
}
public class MyApplicationContextUtils {
public static ApplicationContext getApplicationContext(ServletContext servletContext){
return (ApplicationContext) servletContext.getAttribute("applicationContext");
}
}
@WebServlet("/selectUserList")
public class UserController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//初始化Spring容器
//ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-core.xml");
ApplicationContext applicationContext = MyApplicationContextUtils.getApplicationContext(getServletContext());
UserService userService = applicationContext.getBean(UserService.class);
try {
//使用Spring容器中的UserService对象
List<User> userList = userService.selectUserList();
System.out.println("userList = " + userList);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
存在问题
概述
开发步骤
①引入相关依赖
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
②编写web.xml
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-core.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
③编写UserController
@WebServlet("/selectUserList")
public class UserController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
UserService userService = applicationContext.getBean(UserService.class);
try {
//使用Spring容器中的UserService对象
List<User> userList = userService.selectUserList();
System.out.println("userList = " + userList);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
注意事项
t.ContextLoaderListener
③编写UserController
@WebServlet("/selectUserList")
public class UserController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
UserService userService = applicationContext.getBean(UserService.class);
try {
//使用Spring容器中的UserService对象
List<User> userList = userService.selectUserList();
System.out.println("userList = " + userList);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
注意事项