Spring+SpringMvc+Mybatis整合小Demo

原始方式整合SSM

不使用spring-mybatis包

项目内容

整合ssm完成对account表新增和查询的操作 

项目大体结构

Spring+SpringMvc+Mybatis整合小Demo_第1张图片

 创建mavenWeb项目 

pom文件中引入依赖

spring核心、aspectj(aop)、spring-jdbc(jdbcTemplate)、spring-tx(事务)、

数据源:mysql、c3p0、mybatis       mybatis-spring(spring整合mybatis)

junit、spring-tst、

servlet、jsp、jstl、

lombok、

spring-webmvc(springMvc依赖)

    
        
            org.springframework
            spring-context
            5.0.5.RELEASE
        
        
            org.aspectj
            aspectjweaver
            1.9.5
        
        
            org.springframework
            spring-jdbc
            5.0.5.RELEASE
        
        
            org.springframework
            spring-tx
            5.0.5.RELEASE
        
        
            mysql
            mysql-connector-java
            5.1.8
        
        
            com.mchange
            c3p0
            0.9.5.5
        
        
            org.mybatis
            mybatis
            3.5.13
        
        
            org.mybatis
            mybatis-spring
            2.0.5
        
        
            junit
            junit
            4.12
            test
        
        
            org.springframework
            spring-test
            5.0.5.RELEASE
        
        
            javax.servlet
            javax.servlet-api
            3.0.1
            provided
        
        
            javax.servlet.jsp
            jsp-api
            2.2
            provided
        
        
            jstl
            jstl
            1.2
        
        
            org.projectlombok
            lombok
            1.18.12
        
        
            org.springframework
            spring-webmvc
            5.0.5.RELEASE
        
    

resource下log4j.properties文件

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=info, stdout

resource下jdbc.properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/jdbc
jdbc.username=root
jdbc.password=root123

spring核心配置:

resource下applicationContext.xml


    

数据库数据表

Spring+SpringMvc+Mybatis整合小Demo_第2张图片

 com.kdy.domain

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account {
    private int id;
    private String name;
    private double money;
}

com.kdy.mapper中AccountMapper接口

public interface AccountMapper {
    //保存账户数据
    @Insert("insert into `account` values(#{id},#{name},#{money})")
    public void save(Account account);
    //查询账户数据
    @Select("select * from `account`")
    public List findAll();

}

resource下com.kdy.mapper中AccountMapper.xml




resource下mybatis-config.xml




    
    
    
    
        
        
        
    
    
    
        
            
            
                
                
                
                
                
                
            
        
    
    
    
        
        
    

web.xml




    
    
        contextConfigLocation
        classpath:applicationContext.xml
    

    
    
        org.springframework.web.context.ContextLoaderListener
    

    
    
        CharacterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
    
    
        CharacterEncodingFilter
        /*
    

    
    
        DispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
            
            contextConfigLocation
            classpath:spring-mvc.xml
        
        2
    
    
        DispatcherServlet
        /
    

com.kdy.exception(写着玩的,练习一下spring异常处理)

@Data
@AllArgsConstructor
@NoArgsConstructor
public class AccountException extends Exception {
    String message;
}

com.kdy.resolver(写着玩的,练习一下spring异常处理)

public class MyExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        if (e instanceof ClassCastException){
            modelAndView.addObject("info","类转换异常");
        }else if(e instanceof ArithmeticException){
            modelAndView.addObject("info","除零算数异常");
        }else if(e instanceof FileNotFoundException){
            modelAndView.addObject("info","文件找不到异常");
        }else if(e instanceof NullPointerException){
            modelAndView.addObject("info","空指针异常");
        }else if(e instanceof AccountException){
            AccountException ae=(AccountException) e;
            modelAndView.addObject("info","AccountService的报的异常"+ae.getMessage());
        }
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

webapp下jsp中error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    error


异常页面~

${info}

resource下spring-mvc.xml



    
    
    
    
        
        
    

    
    

    
    

    
    

com.kdy.service.impl

@Service
public class AccountServiceImpl implements AccountService {

    @Override
    public void save(Account account) throws AccountException {
        try {
            //1.加载mybatis核心配置,获取SqlSessionFactory
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //2.获取SqlSession对象,用它来执行sql
            SqlSession sqlSession = sqlSessionFactory.openSession();
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            mapper.save(account);
            sqlSession.commit();
            sqlSession.close();
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            String str = sw.toString();
            throw new AccountException(str);
        }
    }

    @Override
    public List findAll() throws AccountException {
        try {
            //1.加载mybatis核心配置,获取SqlSessionFactory
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //2.获取SqlSession对象,用它来执行sql
            SqlSession sqlSession = sqlSessionFactory.openSession();
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            List accountList = mapper.findAll();
            sqlSession.close();
            return accountList;
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            String str = sw.toString();
            throw new AccountException(str);
        }
    }
}

com.kdy.controller

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    //保存
    @RequestMapping(value = "/save",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String save(Account account) throws AccountException {
        accountService.save(account);
        return "保存成功";
    }

    //查询
    @RequestMapping("/findAll")
    public ModelAndView findAll() throws AccountException {
        List accountList = accountService.findAll();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("accountList",accountList);
        modelAndView.setViewName("index");
        return modelAndView;
    }
}

webapp下jsp下save.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    save


添加账户信息表单

账户名称:
账户金额:

webapp下jsp下index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    index


展示用户数据列表

账户id 账户名称 账户金额
${account.id} ${account.name} ${account.money}

运行tomcat访问http://localhost:8080/SsmModule/jsp/save.jsp

和http://localhost:8080/SsmModule/account/findAll

原始方式整合sping和mybatis的弊端

如service层中的是实现类中的方法
    public void save(Account account) throws AccountException {
            InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
       SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); ... }

每当执行一次controller就会在service层创建一个sqlSessionFactory工厂

虽然可采取servletContextListener监听器将sqlSessionFactory存放servletContext域中

可参考spring博客中最下方集成web环境中的内容

1、web.xml中增加一个全局初始化参数mybatisConfigLocation

    
    
        contextConfigLocation
        classpath:applicationContext.xml
    
    
        mybatisConfigLocation
        mybatis-config.xml
    

2、com.kdy.listener中

@WebListener
public class MybatisLoadListener implements ServletContextListener {

    @SneakyThrows
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        //获取web.xml中配置的application的全局初始化参数:
        String mybatisConfigLocation = servletContext.getInitParameter("mybatisConfigLocation");//其值为applicationContext.xml
        InputStream inputStream = Resources.getResourceAsStream(mybatisConfigLocation);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        servletContext.setAttribute("sqlSessionFactory",sqlSessionFactory);
    }
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }
}

3、com.kdy.util下创建一个工具类

public class MybatisContextUtils {
    public static SqlSessionFactory getSqlSessionFactory(ServletContext servletContext){
        return (SqlSessionFactory)servletContext.getAttribute("sqlSessionFactory");
    }
}

controller中修改接口传递一个参数request,且修改service层入参传递一个servletContext

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    //保存
    @RequestMapping(value = "/save",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String save(HttpServletRequest request,Account account) throws AccountException {
        WebApplicationContext ac1= WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        ServletContext servletContext = ac1.getServletContext();
        accountService.save(account,servletContext);
        return "保存成功";
    }

    //查询
    @RequestMapping("/findAll")
    public ModelAndView findAll(HttpServletRequest request) throws AccountException {
        WebApplicationContext ac1= WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        ServletContext servletContext = ac1.getServletContext();
        List accountList = accountService.findAll(servletContext);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("accountList",accountList);
        modelAndView.setViewName("index");
        return modelAndView;
    }
}
@Service
public class AccountServiceImpl implements AccountService {

    @Override
    public void save(Account account, ServletContext servletContext) throws AccountException {
        try {
            SqlSessionFactory sqlSessionFactory = MybatisContextUtils.getSqlSessionFactory(servletContext);
            //2.获取SqlSession对象,用它来执行sql
            SqlSession sqlSession = sqlSessionFactory.openSession();
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            mapper.save(account);
            sqlSession.commit();
            sqlSession.close();
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            String str = sw.toString();
            throw new AccountException(str);
        }
    }

    @Override
    public List findAll(ServletContext servletContext) throws AccountException {
        try {
            SqlSessionFactory sqlSessionFactory = MybatisContextUtils.getSqlSessionFactory(servletContext);
            //2.获取SqlSession对象,用它来执行sql
            SqlSession sqlSession = sqlSessionFactory.openSession();
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            List accountList = mapper.findAll();
            sqlSession.close();
            return accountList;
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            String str = sw.toString();
            throw new AccountException(str);
        }
    }
}

 运行tomcat访问http://localhost:8080/SsmModule/jsp/save.jsp

和http://localhost:8080/SsmModule/account/findAll

但是这种方式麻烦不说

service层每次还要加上一个servletContext的入参使得controller和service界限模糊不清

所以绝不推荐使用

Spring整合mybatis的方式整合SSM

思路

将session工厂交给spring容器管理,从容器中获得执行操作的Mapper实例即可

将事务的控制(sqlSession.commit和sqlSession.close等)交给spring容器进行声明式事务控制

操作

接着原始方式整合SSM的案例写

如果写了上面监听器抽的步骤先回退到原始方式整合SSM案例

pom文件中引入spring-mybatis的包(上面已经引入了,包中有spring提供的工厂的实现类)

1、resource下的mybatis-config.xml文件删除掉数据源和引入jdbc.properties的内容

2、applicationContext.xml中加上数据源和引入jdbc.properties的内容

接下来让service中的sqlSession交由spring产生

3、applicationContext.xml中配置sqlSessionFactory的bean

接下来mybatis核心配置中mapper映射的加载也可以交由spring托管

4、resource下的mybatis-config.xml文件删除加载映射...

5、applicationContext.xml中配置MapperScannerConfigurer扫描mapper所在的包,并为mapper创建实现类

mybatis-config.xml变为




    
    
        
        
        
    

applicationContext.xml变为


    
    
    
        
        
        
        
    
    
    
        
        
        
    
    
    
    
        
    

使用

只需在用到mapper的地方注入mapper包下的某个mapper接口即可

删除 spring-mvc.xml自定义异常处理器,删MyException,删myExceptionResolver

AccountServiceImpl

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public void save(Account account){
        try {
            accountMapper.save(account);
        } catch (Exception e) {
          e.printStackTrace();
        }
    }

    @Override
    public List findAll(){
        try {
            List accountList = accountMapper.findAll();
            return accountList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

接下来为其加上spring的事务管理

applicationContext.xml中加上配置平台事务管理器、事务的增强和织入



    
    
    
        
        
        
        
    
    
    
        
        
        
    
    
    
    
        
    

    
    
        
    
    
    
        
            
            
            
            
            
        
    
    
    
        
    

运行部署访问即可。

你可能感兴趣的:(小demo,mybatis,spring,mvc,java)