跳转到主要内容

springboot 集成数据库

创建项目请参照

create-springboot-project: https://qq829.cn/book/books/bbcbf/page/create-springboot-project

集成数据库

注意:如果你是按create-springboot-project创建的项目,需要删除配置



# application.yml
spring:
  autoconfigure:
    # 阻止Spring Boot自动配置数据源
    exclude: org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

约定与名词解释

  • entity(实体),与数据表,代表一张真实的数据表
  • DAO(数据访问对象),访问数据库的接口或实例,在spring-boot中,有时候有喜欢取名为Mapper
  • DTO(数据传输对象),含业务领域的数据(既包含entity,但是应该多余entity),但不包含业务逻辑

创建数据库


创建Entity(实体)与数据库结构保持一致

在实体上增加注解 @Data


@Data
public class UserEntity {
    private Integer id;
    private String name;
    private Integer age;
    private String email;
}

创建DTO

这个可以后创建或者先直接继承于Entity,注意 @Data 注解


@Data
public class UserDTO extends UserEntity {

}

创建Dao或者Mapper

注意 @Mapper 注解


@Mapper
public interface UserMapper {

    @Select("SELECT * FROM user")
    List<UserEntity> findAll();
}