ssm框架整合Mybatis(注解)

这篇文章是IDEA版整合ssm框架(Spring+SpringMVC+Mybatis),学生增删改查基础项目。附带源码文章后的Mybatis框架配置(注解方式)。废话不多说,我们开始吧。

配置Mybatis框架

1,编写spring配置文件applicationContext.xml。

  • 配置连接池,连接数据库。
  • 将SqlSessionFactory工厂放到spring容器中
  • 扫描Mybatis的注解,根据自己的dao层包名配置,我这个是dpdd.dao
  • 声明事务管理,因为增删改需要事务管理。
<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--开启注解扫描-->
    <context:component-scan base-package="dpdd">
    </context:component-scan>

    <!--spring配置Mybatis框架-->
    <!--配置连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="root"/>
        <property name="password" value="root"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/school?serverTimezone=UTC"/>
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    </bean>
    
    <!--配置SqlSessionFactory工厂-->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!--扫描dpdd.dao包里所有的Mybatis的注解-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="dpdd.dao"/>
    </bean>
    
    <!--配置spring声明式事务管理-->
    <!--配置事务管理器-->
    <bean id="manager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="manager">
        <tx:attributes>
            <tx:method name="save*" read-only="true"/>
            <tx:method name="delete*" read-only="true"/>
            <tx:method name="update*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    
    <!--配置Aop增强-->
    <aop:config>
        <aop:pointcut id="pt1" expression="execution(* dpdd.service.impl.StudentServiceImpl.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
    </aop:config>
</beans>

2,编写StudentDao类的代码

  • 加上Mybatis的注解和sql语句,
  • 并加上@Repository将StudentDao注入spring容器
package dpdd.dao;
import dpdd.entity.Student;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public interface StudentDao {
    @Select("select * from student")
    List<Student> findAll();

    @Insert("insert into student (name,password) values(#{name},#{password})")
    void insert(Student student);

    @Update("update student set name=#{name},password=#{password} where id=#{id}")
    void update(Student student);

    @Delete("delete from student where id=#{id}")
    void delete(int id);
}

3,编写StudentServiceImpl类的代码

  • 自动注入StudentDao
  • 加上@Service,将StudentServiceImpl注入到容器中
package dpdd.service.impl;
import dpdd.dao.StudentDao;
import dpdd.entity.Student;
import dpdd.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDao studentdao;
    
    @Override
    public List<Student> findAll() {
        return studentdao.findAll();
    }

    @Override
    public void insert(Student student) {
        studentdao.insert(student);
    }

    @Override
    public void update(Student student) {
        studentdao.update(student);
    }

    @Override
    public void delete(int id) {
        studentdao.delete(id);
    }
}

4,编写StudentController类的代码

  • 自动注入了studentServiceImpl
  • 增删查三个方法的返回值,我都设为void,因为我使用了重定向到/stu/findAll, 也就是查询所有的findAll方法。浏览器将会返回list.jsp页面。
package dpdd.controller;
import dpdd.entity.Student;
import dpdd.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/stu")
public class StudentController {

    @Autowired
    private StudentService studentServiceImpl;

    /*查询所有*/
    @RequestMapping("/findAll")
    public String findAll(Model model){
        List<Student> students = studentServiceImpl.findAll();
        model.addAttribute("all",students);
        return "list";
    }
    /*增删查三个方法的返回值,我都设为void,因为我使用了重定向到/stu/findAll,
    也就是查询所有findAll的方法。浏览器将会返回list.jsp页面,*/
    /*新增操作*/
    @RequestMapping("/add")
    public void add(Student student, HttpServletRequest request, HttpServletResponse response) throws IOException {
        /*解决中文乱码*/
        String s = new String(student.getName().getBytes("ISO-8859-1"), "UTF-8");
        student.setName(s);
        studentServiceImpl.insert(student);
        response.sendRedirect(request.getContextPath()+"/stu/findAll");
    }

    /*删除操作*/
    @RequestMapping("/delete")
    public void delete(int id,HttpServletRequest request, HttpServletResponse response) throws IOException {
        studentServiceImpl.delete(id);
        response.sendRedirect(request.getContextPath()+"/stu/findAll");
    }

    /*修改操作*/
    @RequestMapping("/update")
    public void update(Student student, HttpServletRequest request, HttpServletResponse response) throws IOException {
        /*解决中文乱码*/
        String s = new String(student.getName().getBytes("ISO-8859-1"), "UTF-8");
        student.setName(s);
        studentServiceImpl.update(student);
        response.sendRedirect(request.getContextPath()+"/stu/findAll");
    }
}


4,编写index.jsp和pages包里的list.jsp
编写index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
<a href="/stu/findAll">查询所有a><br>

新增:
<form method="post" action="/stu/add">
    姓名:<input type="text" name="name"><br>
    密码:<input type="text" name="password"><br>
    <input type="submit" name="添加">
form><br>

修改:
<form method="post" action="/stu/update">
    id:<input type="text" name="id"><br>
    姓名:<input type="text" name="name"><br>
    密码:<input type="text" name="password"><br>
    <input type="submit" name="修改">
form><br>

删除:
<form method="post" action="/stu/delete">
    删除的id:<input type="text" name="id"><br>
    <input type="submit" name="删除"><br>
form><br>

body>
html>

编写list.jsp:

  • 因为findAll ( )方法把查出的所有学生students,以键值方式存在model里,所以这里用all显示students里的数据。
model.addAttribute("all",students);
  • 记得添加isELIgnored=“false”,支持JSTL表达式语言
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
<h2>操作成功h2>
    ${all}
body>
html>

5,启动服务器时加载spring的配置文件
在测试spring框架时,我们是用下面代码加载applicationContext.xml文件

ApplicationContext config = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

现在我们要使用监听器加载spring配置文件,在tomcat服务器启动时能自动加载。因为Mybatis的配置也在applicationContext.xml里,所以同时也能使Mybatis的配置生效。

编写web.xml文件。



<web-app>
  <display-name>Archetype Created Web Applicationdisplay-name>

  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
  context-param>

  
  <filter>
    <filter-name>characterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>UTF-8param-value>
    init-param>
  filter>

  <filter-mapping>
    <filter-name>characterEncodingFilterfilter-name>
    <url-pattern>/url-pattern>
  filter-mapping>

  
  <servlet>
    <servlet-name>dispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServletservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

web-app>

这样就完成了一个简单的ssm的框架。关于源码我已经放在我的github上了,需要的可以去下载,对你有帮助的话,顺手给个star吧。

源码链接: https://github.com/onesjs/ssm-.git.

有不明白的地方可以评论提出。如果有错误或者不足,欢迎指出批评。我会第一时间修改的。

你可能感兴趣的:(spring,mybatis,mysql,java)