【Mybatis学习】利用SpringBoot搭建SSM框架

来源:互联网 发布:淘宝消费贷款怎么申请 编辑:程序博客网 时间:2024/05/16 19:45

使用SpringBoot技术搭建SSM框架

1.新建SpringBoot-Maven项目

下图为新建项目后创建的包结构。


2.配置文件application.properties、pom.xml

分别定义dataSource数据源、mybatis扫描包位置、freemarker配置、默认访问页面位置等。
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8spring.datasource.username=wszspring.datasource.password=wszspring.datasource.driver-class-name=com.mysql.jdbc.Drivermybatis.type-aliases-package=com.wsz.mybatis.domainmybatis.mapper-locations=classpath:mapper/*.xmlspring.freemarker.template-loader-path=classpath:/templates/spring.freemarker.cache=falsespring.freemarker.charset=utf-8spring.freemarker.check-template-location=truespring.freemarker.content-type=text/htmlspring.freemarker.expose-request-attributes=truespring.freemarker.expose-spring-macro-helpers=truespring.freemarker.request-context-attribute=requestspring.freemarker.suffix=.html


<?xml version="1.0" encoding="UTF-8"?><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><groupId>com.wsz</groupId><artifactId>spring-mybatis</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>spring-mybatis</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.8.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.1</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>


3.Java文件


3.1实体类Student

package com.wsz.mybatis.domain;import lombok.Getter;import lombok.Setter;import java.io.Serializable;/** * @Author wsz * @Des: * @Date: 2017/11/14 */public class Student implements Serializable {    @Setter    @Getter    private int id;    @Setter    @Getter    private String username;    @Setter    @Getter    private String realName;    @Setter    @Getter    private int age;    @Setter    @Getter    private String des;}



3.2Mapper接口及方法

package com.wsz.mybatis.dao;import com.wsz.mybatis.domain.Student;import org.apache.ibatis.annotations.Mapper;import org.springframework.stereotype.Repository;import java.util.List;/** * @Author wsz * @Des: * @Date: 2017/11/14 */@Repository@Mapperpublic interface StudentDao {    List<Student> findAll();    Student findOne(int id);    Student findByUsername(String username);    List<Student> findByRealname(String realname);    int saveStudent(Student student);    int batchSaveStudent(List<Student> students);    int updateStudent(Student student);    int deleteUser(int id);    int batchDeleteStudent(List<Integer> ids);}

3.3Service及实现

package com.wsz.mybatis.service;import com.wsz.mybatis.domain.Student;import java.util.List;public interface StudentService {    List<Student> findAll();    Student findOne(int id);    Student findByUsername(String username);    List<Student> findByRealname(String realname);    int saveStudent(Student student);    int batchSaveStudent(List<Student> students);    int updateStudent(Student student);    int deleteUser(int id);    int batchDeleteStudent(List<Integer> ids);}

package com.wsz.mybatis.service.impl;import com.wsz.mybatis.dao.StudentDao;import com.wsz.mybatis.domain.Student;import com.wsz.mybatis.service.StudentService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;/** * @Author wsz * @Des: * @Date: 2017/11/14 */@Servicepublic class StudentServiceImpl implements StudentService{    @Autowired    private StudentDao studentDao;    @Override    public List<Student> findAll() {        return studentDao.findAll();    }    @Override    public Student findOne(int id) {        return studentDao.findOne(id);    }    @Override    public Student findByUsername(String username) {        return studentDao.findByUsername(username);    }    @Override    public List<Student> findByRealname(String realname) {        return studentDao.findByRealname(realname);    }    @Override    public int saveStudent(Student student) {        return studentDao.saveStudent(student);    }    @Override    public int batchSaveStudent(List<Student> students) {        return studentDao.batchSaveStudent(students);    }    @Override    public int updateStudent(Student student) {        return studentDao.updateStudent(student);    }    @Override    public int deleteUser(int id) {        return studentDao.deleteUser(id);    }    @Override    public int batchDeleteStudent(List<Integer> ids) {        return studentDao.batchDeleteStudent(ids);    }}

3.4控制类Controller

package com.wsz.mybatis.controller;import com.wsz.mybatis.domain.Student;import com.wsz.mybatis.service.StudentService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import java.util.List;/** * @Author wsz * @Des: * @Date: 2017/11/14 */@Controllerpublic class StudentController {    private final static String MODELPATH = "/";    @Autowired    private StudentService studentService;    @RequestMapping("index")    public ModelAndView index(){        ModelAndView model = new ModelAndView();        List<Student> students = studentService.findAll();        model.addObject("list",students);        model.setViewName(MODELPATH+"index");        return model;    }    @RequestMapping("addForm")    public ModelAndView addForm(){        ModelAndView model = new ModelAndView();        model.setViewName(MODELPATH+"addForm");        return model;    }    @RequestMapping("saveStudent")    public String saveStudent(Student student){        int save =  studentService.saveStudent(student);        System.out.println(save);        return "redirect:/index";    }    @RequestMapping("deleteStudent")    public String deleteStudent(int id){        int i = studentService.deleteUser(id);        if(i>0){            System.out.println("删除成功");        }else{            System.out.println("删除失败");        }        return "redirect:/index";    }    @RequestMapping("updateForm")    public ModelAndView updateForm(int id){        ModelAndView model = new ModelAndView();        Student student = studentService.findOne(id);        model.addObject("student",student);        model.setViewName(MODELPATH+"updateForm");        return model;    }    @RequestMapping("updateStudent")    public String updateStudent(Student student){        int save =  studentService.updateStudent(student);        System.out.println(save);        return "redirect:/index";    }    @RequestMapping("searchStudent")    public ModelAndView searchStudent(String realname){        ModelAndView model = new ModelAndView();        List<Student> list =  studentService.findByRealname(realname);        model.addObject("list",list);        model.setViewName(MODELPATH+"index");        return model;    }}


4.resources文件

4.1mapper文件

<?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="com.wsz.mybatis.dao.StudentDao">    <resultMap id="baseMap" type="com.wsz.mybatis.domain.Student">        <result column="id"         property="id"/>        <result column="username"   property="username"/>        <result column="real_name"  property="realName"/>        <result column="age"         property="age"/>        <result column="des"        property="des"/>    </resultMap>    <sql id="baseSql">        id, username, real_name, age, des    </sql>    <select id="findAll" resultMap="baseMap">        select <include refid="baseSql"/>        from t_student    </select>    <select id="findOne" resultMap="baseMap" parameterType="int">        select <include refid="baseSql"/>        from t_student        where id = #{id}    </select>    <select id="findByUsername"  resultMap="baseMap" parameterType="string">        select <include refid="baseSql"/>        from t_student        where username = #{username}    </select>    <select id="findByRealname" resultMap="baseMap" parameterType="string">        select <include refid="baseSql"/>        from t_student        where real_name like  concat('%',#{realname},'%')    </select>    <insert id="saveStudent" parameterType="com.wsz.mybatis.domain.Student" useGeneratedKeys="true" keyColumn="id">        insert into t_student(id, username, real_name, age, des)        values          (#{id},#{username},#{realName},#{age},#{des})    </insert>    <insert id="batchSaveStudent">        insert into t_student(id, username, real_name, age, des)        values          <foreach collection="students" item="item" index="key" open="(" separator="," close=")">              #{item.id},#{item.username},#{item.realName},#{item.age},#{item.des}          </foreach>    </insert>    <update id="updateStudent" parameterType="com.wsz.mybatis.domain.Student">        update t_student        set          <if test="username != null and username != ''">              username = #{username},          </if>          <if test="realName != null and realName != ''">              real_name = #{realName},          </if>          <if test="age != null and age != ''">              age = #{age},          </if>          <if test="des != null and des != ''">              des = #{des}          </if>        where          id = #{id}    </update>    <delete id="deleteUser" parameterType="int">        delete        from t_student        where id = #{id}    </delete>    <delete id="batchDeleteStudent">        delete        from t_student        where id in            <foreach collection="ids" item="item" index="key" open="(" separator="," close=")">                #{item.id}            </foreach>    </delete></mapper>

4.2页面templates

index.html首页面
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <script src="/js/jquery-3.2.1.min.js"></script>    <title>首页面</title></head><body>    <fieldset>        <legend>用户列表</legend>        <table style="width: 500px">            <thead>                <td style="width: 70px;text-align: center">标记</td>                <td style="width: 70px;text-align: center">用户名</td>                <td style="width: 70px;text-align: center">真实姓名</td>                <td style="width: 70px;text-align: center">年龄</td>                <td style="width: 70px;text-align: center">描述</td>                <td style="width: 100px;text-align: center">操作</td>            </thead>            <tbody>                <#if list ??>                    <#list list as item>                        <tr>                            <td style="text-align: center">${item.id!}</td>                            <td style="text-align: left">${item.username!}</td>                            <td style="text-align: left">${item.realName!}</td>                            <td style="text-align: right">${item.age!}</td>                            <td style="text-align: right">${item.des!}</td>                            <td style="text-align: center">                                <a href="/deleteStudent?id=${item.id!}">删除</a>                                <a href="/updateForm?id=${item.id!}">修改</a>                            </td>                        </tr>                    </#list>                </#if>            </tbody>        </table>    </fieldset>    <a href="/addForm">新增</a>       <form action="searchStudent" method="post">        <table>            <tr>                <td>姓名</td>                <td><input  name="realname" type="text"/></td>                <td>                    <input type="submit" value="查询" />                </td>            </tr>        </table>    </form></body></html>

addForm.html新增页面
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body>    <form id="" action="saveStudent" method="post">        <table>            <tr>                <td>用户名</td>                <td><input type="text" name="username"/></td>            </tr>            <tr>                <td>真实名</td>                <td><input type="text" name="realName"/></td>            </tr>            <tr>                <td>年龄</td>                <td><input type="text" name="age"/></td>            </tr>            <tr>                <td>描述</td>                <td><input type="text" name="des"/></td>            </tr>        </table>        <p>            <input type="submit" value="保存">            <input type="reset" value="重置">        </p>    </form></body></html>

updateForm.html更新页面
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><form id="" action="updateStudent" method="post">    <input type="text" hidden="hidden" name="id" value="${student.id!}">    <table>        <tr>            <td>用户名</td>            <td><input type="text" name="username" value="${student.username!}"/></td>        </tr>        <tr>            <td>真实名</td>            <td><input type="text" name="realName" value="${student.realName!}"/></td>        </tr>        <tr>            <td>年龄</td>            <td><input type="text" name="age" value="${student.age!}"/></td>        </tr>        <tr>            <td>描述</td>            <td><input type="text" name="des" value="${student.des!}"/></td>        </tr>    </table>    <p>        <input type="submit" value="保存">        <input type="reset" value="重置">    </p></form></body></html>

5.结果展示






最后附上源码:
https://github.com/BeHappyWsz/spring-mybatis.git
链接:http://pan.baidu.com/s/1bpuEj8b 密码:75nz