springboot系列03:数据库操作及前端渲染

2022/1/13 19:03:32

本文主要是介绍springboot系列03:数据库操作及前端渲染,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

数据库操作

  • pom.xml引入模块:

<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配置数据库:

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值对比:

  • create:每次加载 hibernate 时都会删除上一次的生成的表,然后根据你的 model 类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。

  • create-drop :每次加载 hibernate 时根据 model 类生成表,但是 sessionFactory 一关闭,表就自动删除。

  • update:最常用的属性,第一次加载 hibernate 时根据 model 类会自动建立起表的结构(前提是先建立好数据库),以后加载 hibernate 时根据 model 类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等 应用第一次运行起来后才会。

  • validate :每次加载 hibernate 时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。

      

dialect 主要是指定生成表名的存储引擎为 InnoDBD;
show-sql 是否打印出自动生成的 SQL;

新建数据库demo,建表语句:

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;

 添加实体类:

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;

    //用户名
    @Column(nullable = false, unique = true)
    private String userName;

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

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

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

    //年龄
    @Column
    private int age;

    //注册时间
    @Column(nullable = false)
    private String regTime;
//省略getter settet方法、构造方法    
}

 

  • 编写dao

package com.example.demo.model;

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

public interface UserBeanRepository extends JpaRepository<UserBean, Long> {
    /**
     * 根据用户名查询用户
     * @param userName
     * @return
     */
    UserBean findByUserName(String userName);

    /**
     * 根据用户名或邮箱查询用户
     * @param username
     * @param email
     * @return
     */
    UserBean findByUserNameOrEmail(String username, String email);
}

 

Entity 中不映射成列的字段得加 @Transient 注解,不加注解也会映射成列!

 

  • 测试类,切换目录至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("张亮", "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("张亮", "cc@126.com").getNickName());
    }

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

 

前端渲染Thymeleaf 模板

Springboot 推荐使用 Thymeleaf 来代替 Jsp。Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。类似 JSP,Velocity,FreeMaker 等,它也可以轻易的与 Spring MVC 等 Web 框架进行集成作为 Web 应用的模板引擎。与其它模板引擎相比,Thymeleaf 最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个 Web 应用。

 

pom.xml引入模块:

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

 在resources/templates新建index.html页面:

<!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跳转到页面:

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","张亮");
        return "index";
    }
}

 application.properties配置:

spring.thymeleaf.cache=false

 

测试,启动主程序,浏览器访问http://localhost:8080/index

WebJars

WebJars 是将客户端(浏览器)资源(JavaScript,Css等)打成 Jar 包文件,以对资源进行统一依赖管理。WebJars 的 Jar 包部署在 Maven 中央仓库上。

 

使用步骤

  •  pom.xml引入相关模块,WebJars主官网 查找对于的组件,比如 Vuejs

 

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

 

 

  • 页面引入

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

 



这篇关于springboot系列03:数据库操作及前端渲染的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程