使用idea搭建SpringBoot+Spring jpa项目(实现获取数据库数据显示在页面中)

时间:2024-03-28 19:52:13

搭建SpringBoot准备

  • javaweb基础
  • idea使用基础
  • maven使用基础

开始搭建SpringBoot项目

  1. 创建springboot
    使用idea搭建SpringBoot+Spring jpa项目(实现获取数据库数据显示在页面中)
  2. 设置Group、Artifact、Packaging
    使用idea搭建SpringBoot+Spring jpa项目(实现获取数据库数据显示在页面中)
  3. 选择web及SpringBoot版本
    使用idea搭建SpringBoot+Spring jpa项目(实现获取数据库数据显示在页面中)
  4. 配置application.properites
    SpringBoot默认情况下没有项目名和端口号需要我们在application.properites文件内配置项目和端口号
    再加上mysql配置
server.servlet.path=/evaluate
server.port=8081

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql:///evaluate?characterEncoding=utf-8&useSSL=false
spring.jpa.show-sql=true
  1. 编写实体类类
    因为要使用jpa,所以实体类中属性命名方式要和数据中的表按照规则对应

Jpa识别实体类

@Entity 识别为实体类
@id 识别为主键
@GeneratedValue(strategy = GenerationType.IDENTITY) 识别为自增
规则如下:
1.命名相同
2.如果数据中有下划线,下划线后面字母大写
即:实体类:danYuan < ----- >数据库表字段:dan_yuan
3.如果不使用它的自动对应配置,可以直接配置
@Table(name = “表名”)
@Column(name=“字段名”)

@Entity
@Table(name = "danyuan")
public class Danyuan {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="danyuan_id")
    private Integer danyuanId;
    @Column(name="name")
    private String name;
    @Column(name="dizhi")
    private String dizhi;
    @Column(name="code")
    private String code;
    @Column(name="parent_code")
    private String parentCode;
    //get、set方法省略
    }

如果不匹配的话会报错
使用idea搭建SpringBoot+Spring jpa项目(实现获取数据库数据显示在页面中)
6. DanyuanRepository接口
需要继承JpaRepository
JpaRepository<实体类,主键类型>

public interface DanyuanRepository extends JpaRepository<Danyuan,Integer> {

    List<Danyuan> findByParentCode(String code);

}

  1. service层
public interface DanyuanService {
    List<Danyuan> findByParentCode(String code);
}
@Service
public class DanyuanServiceImpl implements DanyuanService {

   @Autowired
   private DanyuanRepository danyuanRepository;

    @Override
    public List<Danyuan> findByParentCode(String code) {
        return danyuanRepository.findByParentCode(code);
    }
}
  1. Controller
@Controller
@RequestMapping("/danyuan")
public class DanyuanController {

    @Autowired
    private DanyuanService danyuanService;

    @RequestMapping("/findByParentCode")
    @ResponseBody
    public List<Danyuan> findByParentCode(@RequestParam("parentCode") String parentCode){
        return danyuanService.findByParentCode(parentCode);
    }
}
  1. 已经简单实现获取数据库数据显示在页面中
    10.效果展示
    使用idea搭建SpringBoot+Spring jpa项目(实现获取数据库数据显示在页面中)