1. 程式人生 > >SpringMVC(二)SpringMVC+MyBatis+Thymeleaf例項

SpringMVC(二)SpringMVC+MyBatis+Thymeleaf例項

SpringMVC例項

本文采用的環境是Spring Boot2+MyBatis+thymeleaf

資料庫建表

CREATE TABLE `t_person` (
  `id` int(12) NOT NULL AUTO_INCREMENT,
  `person_name` varchar(60) NOT NULL,
  `note` varchar(256) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8;

Maven依賴

<?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.lay</groupId> <artifactId
>
mvc</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>mvc</name> <description>Demo project for SpringMVC</description> <parent> <groupId>org.springframework.boot</groupId> <
artifactId
>
spring-boot-starter-parent</artifactId> <version>2.1.0.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-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- dbcp2連線池 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> </dependency> <!-- mabatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- thymeleaf依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- fastJson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastJson</artifactId> <version>1.2.17</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

application.properties配置檔案

#資料庫配置
spring.datasource.url=jdbc:mysql://192.168.3.253:3306/springboot_database?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
# spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#指定資料連線池的型別
spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource
#最大等待連線中的數量,設定0為沒有限
spring.datasource.dbcp2.max-idle=10
#最大連線活動數
spring.datasource.dbcp2.max-total=50
#最大等待毫秒數,單位ms,超過時間會出錯誤資訊
spring.datasource.dbcp2.max-wait-millis=10000
#資料庫連線池初始化連線數
spring.datasource.dbcp2.initial-size=5
#設定預設的隔離級別為讀寫提交
spring.datasource.dbcp2.default-transaction-isolation=2
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html

# mybatis配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package: com.lay.mvc.entity
#駝峰命名轉換
mybatis.configuration.mapUnderscoreToCamelCase=true

#sql日誌
logging.level.com.lay.mvc.dao=trace

實體Entity

package com.lay.mvc.entity;

import com.lay.mvc.enumeration.SexEnum;
import org.apache.ibatis.type.Alias;

/**
 * @Description:
 * @Author: lay
 * @Date: Created in 0:33 2018/11/11
 * @Modified By:IntelliJ IDEA
 */
@Alias("person")
public class Person {


    private static final long serialVersionUID = 3172000990909338544L;

    private Long id = null;

    private String personName = null;

    private String note = null;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }


}

資料訪問層DAO

package com.lay.mvc.dao;

import com.lay.mvc.entity.Person;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Description:
 * @Author: lay
 * @Date: Created in 0:35 2018/11/11
 * @Modified By:IntelliJ IDEA
 */
@Mapper
@Repository
public interface PersonDao {

    //獲取單個使用者
    public Person getPerson(Long id);

    //新增使用者
    public int insertPerson(Person person);

    //更新使用者
    public int updatePerson(Person person);

    //獲取全部使用者
    public List<Person> getAllPersons();

    //查詢使用者
    public List<Person> findPersons(@Param("personName") String personName, @Param("note") String note);

    //刪除使用者
    public int deletePerson(Long id);

}

MyBatis Mappper對映檔案

路徑為/resources/mapper/personMapper.xml

<?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.lay.mvc.dao.PersonDao">
    <select id="getPerson" parameterType="long" resultType="person">
		select id,person_name,note from t_person where id=#{id}
	</select>
    <insert id="insertPerson" useGeneratedKeys="true" keyProperty="id" >
		insert into t_person(person_name,note) values(#{personName},#{note})
	</insert>
    <update id="updatePerson">
        update t_person
        <set>
            <if test="personName!=null">person_name=#{personName},</if>
            <if test="note!=null">note=#{note}</if>
        </set>
        where id=#{id}
    </update>
    <select id="getAllPersons" resultType="person">
		select id,person_name,note from t_person
	</select>
    <select id="findPersons" resultType="person">
        select id,person_name,note from t_person
        <where>
            <if test="personName!=null">
                and person_name=#{personName}
            </if>
            <if test="note!=null">
                and note=#{note}
            </if>
        </where>
    </select>
    <delete id="deletePerson" parameterType="long">
		delete from t_person where id=#{id}
	</delete>
</mapper>

服務層Service

package com.lay.mvc.service;

import com.lay.mvc.entity.Person;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @Description:
 * @Author: lay
 * @Date: Created in 0:39 2018/11/11
 * @Modified By:IntelliJ IDEA
 */
public interface PersonService {

    //獲取單個使用者
    public Person getPerson(Long id);

    //新增使用者
    public Person insertPerson(Person person);

    //更新使用者名稱
    public Person updatePerson(Long id, String personName);

    //獲取全部使用者
    public List<Person> getAllPersons();

    //查詢使用者
    public List<Person> findPersons(String personName,String note);

    //刪除使用者
    public int deletePerson(Long id);


}

服務層實現類ServiceImpl

package com.lay.mvc.service.impl;

import com.lay.mvc.dao.PersonDao;
import com.lay.mvc.entity.Person;
import com.lay.mvc.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description:
 * @Author: lay
 * @Date: Created in 0:40 2018/11/11
 * @Modified By:IntelliJ IDEA
 */
@Service
public class PersonServiceImpl implements PersonService {


    @Autowired
    PersonDao personDao ;

    @Override
    @Transactional
    public Person getPerson(Long id) {
        return personDao.getPerson(id);
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, timeout = 1, propagation = Propagation.REQUIRES_NEW)
    public Person insertPerson(Person person) {
        personDao.insertPerson(person);
        return person;
    }

    @Override
    @Transactional
    public Person updatePerson(Long id, String personName) {
        Person person = this.getPerson(id);
        if (person == null) {
            return null;
        }
        person.setPersonName(personName);
        personDao.updatePerson(person);
        return person;
    }

    @Override
    public List<Person> getAllPersons() {

        return personDao.getAllPersons();
    }

    @Override
    public List<Person> findPersons(String personName, String note) {
        return personDao.findPersons(personName,note);
    }

    @Override
    @Transactional
    public int deletePerson(Long id) {
        return personDao.deletePerson(id);
    }

}

控制器Controller

package com.lay.mvc.controller;

import com.lay.mvc.entity.Person;
import com.lay.mvc.enumeration.SexEnum;
import com.lay.mvc.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Description:
 * @Author: lay
 * @Date: Created in 0:25 2018/11/11
 * @Modified By:IntelliJ IDEA
 */
@RequestMapping(value = "/person")
@Controller
public class PersonController {

    //注入使用者服務類
    @Autowired
    PersonService personService;

    //獲取人員列表
    @RequestMapping("/table")
    public ModelAndView table() {
        List<Person> personList = personService.getAllPersons();
        ModelAndView mv = new ModelAndView();
        mv.setViewName("person/table");
        mv.addObject("personList", personList);
        return mv;
    }

    @RequestMapping("/list")
    @ResponseBody
    public List<Person> list(
            @RequestParam(value = "personName", required = false) String personName,
            @RequestParam(value = "note", required = false) String note) {
        List<Person> personList = personService.findPersons(personName, note);
        return personList;
    }

}

啟動類

配置Mapper掃描

package com.lay.mvc;

import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
@MapperScan(basePackages = "com.lay.mvc.dao", annotationClass = Mapper.class)
public class MvcApplication {

    public static void main(String[] args) {
        SpringApplication.run(MvcApplication.class, args);
    }

}

檢視頁面

目錄:/resources/templates/person/table

<!DOCTYPE html>
<html xmlns:th="ht