springboot series 03: database operation and front-end rendering

Posted by neox_blueline on Thu, 13 Jan 2022 12:10:27 +0100

Database operation

  • pom.xml import module:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

 

  • application.properties configuration database:

spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=111111
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true

 

hibernate.hbm2ddl.auto value comparison:

  • create: every time you load hibernate, you will delete the last generated table, and then regenerate a new table according to your model class. Even if there is no change twice, you should do so. This is an important reason for the loss of database table data.

  • Create drop: each time hibernate is loaded, a table is generated according to the model class, but the table is automatically deleted as soon as sessionFactory is closed.

  • update: the most commonly used attribute. When hibernate is loaded for the first time, the table structure will be automatically established according to the model class (provided that the database is established first). When hibernate is loaded later, the table structure will be automatically updated according to the model class. Even if the table structure is changed, the rows in the table still exist and the previous rows will not be deleted. It should be noted that when deployed to the server, the table structure will not be established immediately. It will not be established until the application runs for the first time.

  • validate: every time hibernate is loaded, the database table structure will be verified and created. It will only be compared with the tables in the database. No new table will be created, but new values will be inserted.

      

dialect mainly specifies that the storage engine for generating table names is InnoDBD;
Show SQL: whether to print automatically generated SQL;

Create a new database demo and create a table statement:

DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user`  (
  `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `age` int(11) NULL DEFAULT NULL,
  `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `nick_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `pass_word` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `reg_time` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `user_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `UK_mx7woyv2wwr462kfnpdhsfvxa`(`email`) USING BTREE,
  UNIQUE INDEX `UK_obbnmq5l56ghtreq7gj2ixt10`(`user_name`) USING BTREE,
  UNIQUE INDEX `UK_qsfr3pppdg879a7n2nfjuyf7h`(`nick_name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

Add entity class:

package com.example.demo.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;

@Entity
public class UserBean implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    //user name
    @Column(nullable = false, unique = true)
    private String userName;

    //password
    @Column(nullable = false)
    private String passWord;

    //mailbox
    @Column(nullable = false, unique = true)
    private String email;

    //nickname
    @Column(nullable = true, unique = true)
    private String nickName;

    //Age
    @Column
    private int age;

    //Registration time
    @Column(nullable = false)
    private String regTime;
//Omit getter, settet method and constructor    
}

 

  • Write dao

package com.example.demo.model;

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserBeanRepository extends JpaRepository<UserBean, Long> {
    /**
     * Query users by user name
     * @param userName
     * @return
     */
    UserBean findByUserName(String userName);

    /**
     * Query users by user name or mailbox
     * @param username
     * @param email
     * @return
     */
    UserBean findByUserNameOrEmail(String username, String email);
}

 

Fields in Entity that are not mapped into columns must be annotated with @ Transient, and they will be mapped into columns without annotation!

 

  • Test class, switch the directory to test/java

package com.example.demo.repository;
import com.example.demo.model.UserBean;
import com.example.demo.model.UserBeanRepository;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.text.DateFormat;
import java.util.Date;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserRepositoryTests {

    @Autowired
    private UserBeanRepository userBeanRepository;

    @Test
    public void testSave() throws Exception {
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
        String formattedDate = dateFormat.format(date);
        userBeanRepository.save(new UserBean("Zhang Liang", "13128600812", "1796969389@qq.com", "zhangl", 29, formattedDate));
 }

    @Test
    public void testFindAll() throws Exception {
        Assert.assertEquals(1, userBeanRepository.findAll().size());

    }

    @Test
    public void testFindByUserNameOrEmail() throws Exception {
        Assert.assertEquals("zhangl", userBeanRepository.findByUserNameOrEmail("Zhang Liang", "cc@126.com").getNickName());
    }

    @Test
    public void testDelete() throws Exception {
        userBeanRepository.delete(userBeanRepository.findByUserName("aa1"));
    }
}

 

Front end rendering Thymeleaf template

Spring boot recommends using thymeleaf instead of JSP. Thymeleaf is a template engine for rendering XML/XHTML/HTML5 content. Similar to JSP, Velocity, FreeMaker, etc., it can also be easily integrated with Spring MVC and other Web frameworks as a template engine for Web applications. Compared with other template engines, the biggest feature of thymeleaf is that it can directly open and correctly display the template page in the browser without starting the whole Web application.

 

pom.xml import module:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Create a new index in resources/templates HTML page:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"></meta>
    <title>Hello</title>
</head>
<body>
<h1  th:text="${message}">Hello World</h1>
</body>
</html>

 

controller jumps to the page:

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {

    @GetMapping("/index")
    public String index(Model model){
        model.addAttribute("message","Zhang Liang");
        return "index";
    }
}

 application.properties configuration:

spring.thymeleaf.cache=false

 

Test, start the main program and visit the browser http://localhost:8080/index

WebJars

WebJars is to print client (browser) resources (JavaScript, Css, etc.) into Jar package files for unified dependency management of resources. The Jar package of WebJars is deployed on Maven central warehouse.

 

Use steps

  •  pom.xml is introduced into related modules, and WebJars main official website} looks for components, such as Vuejs

 

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>vue</artifactId>
    <version>2.5.16</version>
</dependency>

 

 

  • Page introduction

<link th:href="@{/webjars/bootstrap/3.3.6/dist/css/bootstrap.css}" rel="stylesheet"></link>

 

Topics: Spring Spring Boot