The original article:
https://tlanyan.pp.ua/spring-boot-mybatis-freemarker-ehcache-web-development/

The Java projects I have done before are all inherited from others and I have not developed them independently. In these days, I took some time to study Spring Boot for web development. This article is used as a record and reference.

The preparatory work

  1. Install Intelij IDEA; Intelij Idea is an essential tool for Java and Android development. The community version is free to use.
  2. Install the MySQL or MariaDB database.

Use Spring Boot + Mybatis + Freemarker for Web development

Create the Spring Boot project

1. Open Idea, create a new project, select “Spring Initializr” in the boot dialog box, and customize the project name, package name, select Java SDK and version, etc.

2. Select Spring Boot DevTools, Lombok, Spring Web, Freemarker, MyBatis and MySQL.

The generated pom.xml content is as follows:

< 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 > < the parent > < groupId > org. Springframework. Boot < / groupId > The < artifactId > spring - the 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> </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 > < the 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 no database is configured, etc. Create the application.yml file in the root directory and type 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: the classpath: / templates/mapper / * mapper. # mapper XML file location type – aliases – package: com.tlanyan.springboot.entity

If you are familiar with the properties file, you can directly edit the application.properties file in the SRC /resources folder

The project can now Run normally (run-> Run “SpringBootApplication”).

Spring Boot hosts static files

Static resources can be accessed by placing them in SRC /resources/static directory (re-run the program after adding new files) :

In addition to the static directory created by default, static resource files can be placed in public, resources, and META-INF/ RESOUCES directories.

Spring Boot + MyBatis + Spring MVC + FreeMarker

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all JDBC code and the work of setting parameters and getting result sets. MyBatis can configure and map primitive types, interfaces, and Java POJOs (Plain Old Java Objects) to records in the database using simple XML or annotations.

Create the entity class for 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 the 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 create the usermapper. XML file in the templates/mapper directory (the mapper file needs to be in the directory specified in the configuration file, and the files in the templates will be automatically packaged, so we chose this location) :

< 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 the Freemarker template. In the Resources/Templates folder create the User 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 the FTL:

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

Mysql > create user table, and fill in the data, run the program, program output results are as follows:

At this point, Spring Boot + MyBatis + Spring MVC + Freemarker has completely worked properly.

Spring Boot uses the Ehcache cache

Finally, we introduce the use of Ehcache cache to enhance program performance.

First, introduce the Ehcache dependency. Introducing Ehcache in pom.xml:

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

</dependencies>

Then create the ehcache.xml configuration file in your resouces directory (Spring Boot will scan this path, so make sure the file name is correct) and type 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>

Among them:

  1. Name: Cache name.
  2. MaxElementSinMemory: Maximum number of caches.
  3. Eternal: Is the object permanently valid? Once set, timeout will not work.
  4. TimeToidleContext: Sets the amount of time (in seconds) an object is allowed to idle before it fails. Only used if the object Eternal =false is not permanently valid. Optional property. Default value is 0, meaning infinite idle time.
  5. TimeToliveConds: Sets how long (in seconds) an object is allowed to live before it fails. The maximum time is between creation time and expiration time. Eternal =false is used only if the object is not permanently valid. The default is 0., i.e. the object has an infinite lifetime.
  6. OverflowToDisk: When the number of objects in memory reaches maxElementsInMemory, Ehcache writes 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: Maximum number of caches on the hard disk.
  9. DiskPersistent: Whether or not to cache virtual machine restart period data.
  10. DiskExpiryThreadIntervalSeconds: disk failure thread running time interval, the default is 120 seconds.
  11. MemoryStoreEvictionPolicy: when maxElementsInMemory limit is reached, Ehcache will be based on the specified strategies to clear the memory. 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 flush when memory is maximum.
  13. DiskStore represents a temporarily cached hard disk directory.

Then configure caching on 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 at 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();
}

}

Note that the value of cacheNames needs to be present in ehcache.xml.

reference

  1. Spring Boot Dry Series :(1) An elegant introduction
  2. SpringBoot+MySQL+MyBatis
  3. SpringBoot Series IV Web Static Resource Configuration
  4. Spring Boot Caching Application Ehcache Beginner Tutorial
  5. Spring Boot2 series of tutorials (30)Spring Boot integration with Ehcache