學習Springboot框架二 之集成jpa查詢mysql數據庫

Study2


這個項目要完成前端能查詢到數據庫。
所以創建時除了選擇web,還要選擇一下mysql、jpa


首先要像上個工程一樣,保證瀏覽器能訪問到controller,
不再贅述。

這兒就是創建了CURDController.java

@RestController
public class CRUDController {
    @Autowired
    private CRUDService crudService;
    @RequestMapping("/getAll")
    public String getAll(){
        return "abc";
    }
}

接着就是Sevice層代碼。
CRUDService.java

@Repository
//@Component
public interface StudyResposity extends JpaRepository<StudySpringBoot, String> {
}

然後是service的實現impl層

@Service
public class CRUDServiceImpl implements CRUDService {
    @Autowired
    private StudyResposity studyResposity;
    @Override
    public String getAll() {
        return studyResposity.findAll().toString();
    }
}

StudyResposity就是數據庫層的接口,是集成jpa的接口來完成數據庫的查詢
dao層 StudyResposity.java

@Repository
//@Component
public interface StudyResposity extends JpaRepository<StudySpringBoot, String> {
}

最後就是和數據庫映射的pojo類,或者稱爲model
實體類 StudySpringBoot.java

@Table(name = "study_spring_boot")
@Entity
public class StudySpringBoot implements Serializable {
    @Id
    private String id;
    @Column
    private String createTime;
    
    public String getId() {
        return id;
    }

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

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        return "StudySpringBoot{" +
                "id='" + id + '\'' +
                ", createTime='" + createTime + '\'' +
                '}';
    }
}

完成這些步驟理論上可以直接運行了。但是還是有些東西需要配置。

  1. 數據庫連接串 在application.properties中寫入
#server
#tomcat端口
server.port= 80

#datasources
#數據庫連接串,地址(ip、端口、數據庫名)、驅動類、用戶名、密碼
spring.datasource.url=jdbc:mysql://tencent_server:3306/study?useUnicode=true&characterEncoding=utf8
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root-wlh

#JPA Configuration:
spring.jpa.database=MySQL
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect

理論上這些配完就可以運行了,可是卻報了Autowired沒有合適的類裝載。說明它並沒有成功掃描到那個註解。
所以在Application中需要配置掃描路徑,所以最後Study2Application.java改爲如下

@SpringBootApplication(scanBasePackages = "com.wlh.study")
@EnableJpaRepositories(basePackages = "com.wlh.study")
@EntityScan(basePackages = "com.wlh.study")
public class Study2Application {
    public static void main(String[] args) {
        SpringApplication.run(Study2Application.class, args);
    }
}

最後這個項目就成功運行了,從數據庫中把表中所有數據查出來並顯示在瀏覽器。


以前沒有用過jpa,結果集成它意外的方便好用呵呵呵。
只需要繼承一個接口就行,不過它默認使用的是hibernate,
應該有辦法可以改成其他的吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章