Web development using spring boot + mybatis + FreeMarker + ehcache

Time:2021-7-28

Original text: https://tlanyan.pp.ua/spring-boot-mybatis-freemarker-ehcache-web-development/

Previous Java projects were taken over from others, and they had not developed independently. I’ve taken time to study spring boot for web development these days. This article is used as a record and reference.

preparation

  1. Install intelij idea; Intelij idea is basically a necessary tool for Java and Android development, and the community version can be used for free;
  2. Install MySQL or MariaDB database.

Web development using spring boot + mybatis + FreeMarker

Create a spring boot project

1. Open idea, create a new project, select “spring initializr” in the boot dialog box, customize the project name and package name, and select Java SDK and version:

Web development using spring boot + mybatis + FreeMarker + ehcache

2. Select spring boot devtools, Lombok, spring web, FreeMarker, mybatis and MySQL:

Web development using spring boot + mybatis + FreeMarker + ehcache

Generatedpom.xmlThe contents are as follows:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.5</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.tlanyan</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot</name>
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>1.8</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.4</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </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>
            <configuration>
                <excludes>
                    <exclude>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                    </exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>

</project>

3. The project cannot be started at this time because there is no configuration database. Create the application.yml file in the root directory, and enter the following:

server:
port: 9000

spring:
freemarker:

template-loader-path: classpath:/templates
cache: true
suffix: .ftl

datasource:

url: jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=utf-8&useSSL=false&useUnicode=true
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
Mapper locations: classpath: / templates / mapper / * mapper.xml # mapper file location
type-aliases-package: com.tlanyan.springboot.entity

If you are familiar with the writing method of the properties file, you can directly edit the application.properties file in the Src / Resources folder

At this point, the project can run normally (run – > Run “springbootapplication”).

Spring boot managed static files

Static resources intosrc/resources/staticDirectory can be accessed to (you need to run the program again after adding a new file):

Web development using spring boot + mybatis + FreeMarker + ehcache

In addition to the static directory created by default, static resource files can also be stored in public, resources and meta-inf / resources directories.

Spring Boot + MyBatis + Spring MVC + FreeMarker

Mybatis is an excellent persistence layer framework, which supports custom SQL, stored procedures and advanced mapping. Mybatis eliminates almost all JDBC code and the work of setting parameters and obtaining result sets. Mybatis can configure and map primitive types, interfaces and Java POJOs (plain old Java objects) to records in the database through simple XML or annotations.

First, create the entity class corresponding to the database table:

package com.tlanyan.springboot.entity;

import lombok.Data;

import java.io.Serializable;

@Data
public class User implements Serializable {

private Integer id;
private String name;

}

Then create mapper interface:

package com.tlanyan.springboot.mapper;

import com.tlanyan.springboot.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserMapper {

public User findById(Integer id);

public List getAll();

}

And intemplates/mapperCreate under directoryUserMapper.xmlFile (the mapper file needs to be placed in the specified directory in the configuration file, and the files in templates will be automatically packaged, so we choose this location):

<?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.tlanyan.springboot.mapper.UserMapper”>

<select id="findById" resultType="com.tlanyan.springboot.entity.User">
    SELECT * from user WHERE id = #{id}
</select>
<select id="getAll" resultType="com.tlanyan.springboot.entity.User">
    select * from user
</select>

</mapper>

Next, write the service layer:

package com.tlanyan.springboot.service;

import com.tlanyan.springboot.entity.User;

import java.util.List;

public interface UserService {

public User findById(Integer id);

public List<User> getAll();

}

And its implementation:

package com.tlanyan.springboot.service.impl;

import com.tlanyan.springboot.entity.User;
import com.tlanyan.springboot.mapper.UserMapper;
import com.tlanyan.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

@Autowired
private UserMapper userMapper;

@Override
public User findById(Integer id) {
    return userMapper.findById(id);
}

@Override
public List<User> getAll() {
    return userMapper.getAll();
}

}

Then the controller layer:

package com.tlanyan.springboot.controller;

import com.tlanyan.springboot.entity.User;
import com.tlanyan.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class UserController {

@Autowired
private UserService userService;

@RequestMapping("/user/list")
public String List(Model model) {
    List<User> users = userService.getAll();
    model.addAttribute("users", users);

    return "user/index";
}

@RequestMapping("/user/{id}")
public String view(@PathVariable("id") Integer id, Model model) {
    User user = userService.findById(id);
    model.addAttribute("user", user);

    return "user/view";
}

}

Finally, write FreeMarker template. Create a user folder under the resources / Templates folder, create a new index.ftl, and enter the following:

<h1>User List</h1>

<ul>

<#list users as user>
    <li>ID: ${user.id}, name: ${user.name}</li>
</#list>

</ul>

And view.ftl:

<h1>User ID: ${user.id}, name: ${user.name}</h1>

Create the user table in the database, fill in the data, run the program, and the program output results are as follows:

Web development using spring boot + mybatis + FreeMarker + ehcache

Web development using spring boot + mybatis + FreeMarker + ehcache

So far, spring boot + mybatis + spring MVC + FreeMarker has been fully functional.

Spring boot uses ehcache caching

Finally, it introduces how to use ehcache cache to enhance program performance.

Firstly, ehcache dependency is introduced. Introduce ehcache into pom.xml:

...
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

</dependencies>

Then create it in the resources directoryehcache.xmlConfiguration file (spring boot will scan this path, so please ensure that the file name is correct), and enter the following:

<ehcache>

<diskStore path="java.io.tmpdir"/>
<defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="false"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120"
/>
<cache name="user"
       maxElementsInMemory="10000"
       eternal="true"
       overflowToDisk="true"
       diskPersistent="true"
       diskExpiryThreadIntervalSeconds="600"/>

</ehcache>

Of which:

  1. Name: cache name.
  2. Maxelementsinmemory: maximum number of caches.
  3. Eternal: whether the object is permanently valid. Once set, timeout will not work.
  4. Timetoidleseconds: sets the allowed idle time (in seconds) of an object before it expires. It is only used when the eternal = false object is not permanently valid. The optional attribute is 0 by default, that is, the idle time is infinite.
  5. Timetoliveseconds: sets the allowable survival time of an object before expiration (unit: seconds). The maximum time is between creation time and expiration time. It is only used when the eternal = false object is not permanently valid. The default is 0. That is, the survival time of the object is infinite.
  6. Overflow to disk: when the number of objects in memory reaches maxelementsinmemory, ehcache will write the objects to disk.
  7. Diskspoolbuffersizemb: this parameter sets the size of the diskstore cache. The default is 30MB. Each cache should have its own buffer.
  8. Maxelementsondisk: the maximum number of hard disk caches.
  9. Diskpersistent: whether to cache virtual machine restart data.
  10. Diskexpirythreadintervalseconds: the running time interval of the disk invalidation thread. The default is 120 seconds.
  11. Memorystoreevictionpolicy: when the maxelementsinmemory limit is reached, ehcache will clean up memory according to the specified policy. The default policy is LRU (least recently used). You can set it to FIFO (first in first out) or LFU (less used).
  12. Clearonflush: whether to clear when the amount of memory is maximum.
  13. Diskstore represents the hard disk directory of the temporary cache.

Then configure enable caching in the application:

package com.tlanyan.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class SpringbootApplication {

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

}

And enable caching in the service layer:

package com.tlanyan.springboot.service.impl;

import com.tlanyan.springboot.entity.User;
import com.tlanyan.springboot.mapper.UserMapper;
import com.tlanyan.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@CacheConfig(cacheNames = “user”)
public class UserServiceImpl implements UserService {

@Autowired
private UserMapper userMapper;

@Override
@Cacheable
public User findById(Integer id) {
    return userMapper.findById(id);
}

@Override
@Cacheable
public List<User> getAll() {
    return userMapper.getAll();
}

}

be careful,cacheNamesThe value of needs to be inehcache.xmlExists in.

reference resources

  1. Spring boot dry goods series: (I) elegant introduction
  2. Introduction to springboot + MySQL + mybatis
  3. Springboot series (IV) web static resource configuration
  4. Spring boot cache application ehcache tutorial
  5. Spring boot 2 series tutorials (30) spring boot integrating ehcache

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]