Spring Boot 篇一: Web Application,Thymeleaf以及JPA(上)

学习Spring Boot,将整个过程记录下来,作为一个Step by Step的Tutorial教程吧。
这是第一篇,创建一个Web Application,使用Thymeleaf模板,基于JPA。

项目源码寄存在Github repo

开发环境

数据库

本案例中使用Microsoft SQL Server Express。呃,主要原因就是,当前我的电脑上已经安装有(随着Visual Studio安装的),就懒得再去安装额外的数据库系统了。

如果没有安装SQL Server Express,可以去SQL Server官网去下载,Express版本是免费的。

  • Java SDK,版本选择了11(最新的一个LTS版本)。
  • IDE: VS Code,自行下载。
  • 版本管理,毫无疑问:Git。
  • Maven的下载安装,详见Apache Maven 官网

创建程序

打开Spring Initalizer来创建初始程序:

Spring Initializer

下载压缩包,将该包解压到对应的目录下。

项目设置

更新POM

参考我之前《JDBC Driver to SQL Server Express》,POM文件需要更新以支持SQL Server。

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>10.2.1.jre11</version>
    <scope>runtime</scope>
</dependency>

JPA相关的属性

至于,使用SQL Server Express,需要额外的配置才能正确使用。参考之前的文档。

设置JPA相关的属性(app.properties):

spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://localhost;database=library;integratedSecurity=true;encrypt=true;trustServerCertificate=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

项目实现

Model定义

这里创建一个Person Role(用户角色)的Model。

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Convert;
import javax.persistence.Entity;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.springframework.validation.annotation.Validated;
 
@Validated
@Entity
@Table(name = "person_role_def")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class PersonRole {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Column(name = "id")
    private Long id;

    @Column(name="role_value", nullable = false, columnDefinition = "INT")
    @Convert(converter = PersonRoleEnumConverter.class)
    private PersonRoleEnum roleValue;

    @Column(name="role_name", nullable = true, length = 50)
    private String roleName;

    public PersonRole() {
    }

    public Long getId() {
        return id;
    }

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

    public PersonRoleEnum getRoleValue() {
        return roleValue;
    }

    public void setRoleValue(PersonRoleEnum roleValue) {
        this.roleValue = roleValue;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }
}

其中,Person Role有个Enum的属性,用来将创建的Role归集于系统所支持的角色中来,同时,保留了Own Defined作为系统的扩展:

public enum PersonRoleEnum {
    OWNDEFINED(0),
    AUTHOR( 1 ),
    ACTOR( 2 ),
    DIRECTOR(3);
 
    private final int code;
    
    PersonRoleEnum(int code) {
        this.code = code;
    }
 
    public static PersonRoleEnum fromCode(int code) {
        if ( code == 1 ) {
            return AUTHOR;
        }
        if ( code == 2 ) {
            return ACTOR;
        }
        if ( code == 3 ) {
            return DIRECTOR;
        }
        if ( code == 0) {
            return OWNDEFINED;
        }
        
        throw new UnsupportedOperationException(
            "The code " + code + " is not supported!"
        );
    }
 
    public int getCode() {
        return code;
    }
}

要存储Enum到Database,需要定义一个Converter:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class PersonRoleEnumConverter implements AttributeConverter<PersonRoleEnum, Integer> {
 
    @Override
    public Integer convertToDatabaseColumn(PersonRoleEnum role) {
        return role == null ? null : role.getCode();
    }
 
    @Override
    public PersonRoleEnum convertToEntityAttribute(Integer value) {
        return value == null ? null : PersonRoleEnum.fromCode( value );
    }
}

Repository

实现JPA Repository的Interface:

import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;

public interface PersonRoleRepository extends PagingAndSortingRepository<PersonRole, Long>, JpaSpecificationExecutor<PersonRole> 
{    
}

Exception

几个用到的Exception:BadResourceException, ResourceAlreadyExistsException, 和ResourceNotFoundException;

import java.util.ArrayList;
import java.util.List;

public class BadResourceException extends Exception {

    private List<String> errorMessages = new ArrayList<>();

    public BadResourceException() {
    }

    public BadResourceException(String msg) {
        super(msg);
    }

    public List<String> getErrorMessages() {
        return errorMessages;
    }

    public void setErrorMessages(List<String> errorMessages) {
        this.errorMessages = errorMessages;
    }

    public void addErrorMessage(String message) {
        this.errorMessages.add(message);
    }
}

public class ResourceAlreadyExistsException extends Exception {
 
    public ResourceAlreadyExistsException() {
    }
 
    public ResourceAlreadyExistsException(String msg) {
        super(msg);
    }
}

public class ResourceNotFoundException extends Exception {
 
    public ResourceNotFoundException() {
    }
 
    public ResourceNotFoundException(String msg) {
        super(msg);
    }    
}

Service

创建Service来实现Database层面的操作:

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.alvachien.springtutorial.thymeleafjpademo.exception.*;
import com.alvachien.springtutorial.thymeleafjpademo.model.PersonRole;
import com.alvachien.springtutorial.thymeleafjpademo.repository.PersonRoleRepository;

@Service
public class PersonRoleService {
    @Autowired
    private PersonRoleRepository personRoleRepository;

    private boolean existsById(Long id) {
        return personRoleRepository.existsById(id);
    }

    public PersonRole findById(Long id) throws ResourceNotFoundException {
        PersonRole role = personRoleRepository.findById(id).orElse(null);
        if (role == null) {
            throw new ResourceNotFoundException("Cannot find Role with id: " + id);
        }

        return role;
    }

    public List<PersonRole> findAll(int pageNumber, int rowPerPage) {
        List<PersonRole> roles = new ArrayList<>();
        Pageable sortedByIdAsc = PageRequest.of(pageNumber - 1, rowPerPage,
                Sort.by("id").ascending());
        personRoleRepository.findAll(sortedByIdAsc).forEach(roles::add);
        return roles;
    }

    public PersonRole save(PersonRole role) throws BadResourceException, ResourceAlreadyExistsException {
        if (!ObjectUtils.isEmpty(role.getRoleName())) {
            if (role.getId() != null && existsById(role.getId())) {
                throw new ResourceAlreadyExistsException("Role with id: " + role.getId() + " already exists");
            }
            return personRoleRepository.save(role);
        } else {
            BadResourceException exc = new BadResourceException("Failed to save role");
            exc.addErrorMessage("Contact is null or empty");
            throw exc;
        }
    }

    public void update(PersonRole role) throws BadResourceException, ResourceNotFoundException {
        if (!ObjectUtils.isEmpty(role.getRoleName())) {
            if (!existsById(role.getId())) {
                throw new ResourceNotFoundException("Cannot find role with id: " + role.getId());
            }
            personRoleRepository.save(role);
        } else {
            BadResourceException exc = new BadResourceException("Failed to save role");
            exc.addErrorMessage("Role is null or empty");
            throw exc;
        }
    }

    public void deleteById(Long id) throws ResourceNotFoundException {
        if (!existsById(id)) {
            throw new ResourceNotFoundException("Cannot find role with id: " + id);
        } else {
            personRoleRepository.deleteById(id);
        }
    }

    public Long count() {
        return personRoleRepository.count();
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值