今天公司要做一個小項目,好久沒碰項目了(刷題好累。。。),聽說spring boot很火,決定試一試。暫時就從mysql里面讀數據好了,使用hiberante。
1.獲取jar包。
從http://start.spring.io/獲取,當然對於使用eclipse(離不開。。。)的同學,有STS插件支持,關於插件用法自行百度,很簡單。關鍵的是選擇要支持的特性。這里是讀數據,我記得只選擇了web,jpa和mysql三個標簽。
2.導入工程。
新建實體類:
- package com.example.demo;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- @Entity
- public class Person {
- @Id
- @GeneratedValue
- private Long id;
- private String name;
- private String address;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- }
Dao類:
- package com.example.demo;
- import java.util.List;
- import org.springframework.data.jpa.repository.JpaRepository;
- public interface Dao extends JpaRepository<Person, Long>{
- List<Person> findByName(String name);
- }
controller
- package com.example.demo;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- @RestController
- @SpringBootApplication
- public class Demo2Application {
- @Autowired
- Dao dao;
- @RequestMapping("/get")
- public Person getP(String name){
- Person person = dao.findByName(name).get(0);
- return person;
- }
- @RequestMapping("/")
- public String index(){
- return "Hello Spring Boot";
- }
- public static void main(String[] args) {
- SpringApplication.run(Demo2Application.class, args);
- }
- }
只添加一個查數據的url。
最后是配置文件:
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8
- spring.datasource.username=root
- spring.datasource.password=
- spring.jpa.hibernate.ddl-auto=update;
- spring.jpa.show-sql=true
- spring.jackson.serialization.indent-output=true
訪問之前,現在數據庫中建表,插數據。
然后啟動,瀏覽器訪問。
瀏覽器:
說明訪問成功。
整體感覺就是,這個框架幫程序員實現了太多功能,原本光一個hibernate就需要N多配置,但是在springboot中完全沒有感知hibernate的存在。有時間需要研究下源碼,看看他是怎么做到的。
這個簡單的demo就到此結束了。