Spring Boot整合Spring MVC、Spring、Spring Data JPA(Hibernate)

一句話總結:Spring Boot不是新的功能框架,而是爲了簡化如SSH、SSM等等多個框架的搭建、整合及配置。使用Spring Boot 10分鐘搭建起Spring MVC、Spring、Spring Data JPA(Hibernate)基礎後臺架構。基本零配置,全註解。java

 

步驟一:mysql

使用Spring Boot提供的網站生成maven項目及基礎依賴。打開https://start.spring.io/網站,右側輸入想要的特性依賴。輸入Web提供整合Spring MVC,輸入JPA提供整合Spring Data JPA和Hibernate。其餘按需輸入想要的功能特性。git

 

步驟二:github

使用IDE導入步驟一輩子成的maven項目spring

 

步驟三:sql

驗證北向Rest,建立Northbound類,Spring Boot已經整合入Spring MVC,按Spring MVC註解便可數據庫

@RestController
@RequestMapping("/rootpath")
public class DemoNorthbound {

    // @Autowired
    // private DemoService demoService;

    @RequestMapping("/restpath")
    public String testPrint() {

        System.out.println("hahaha...........");
        return "hello world...";
    }
}

 

步驟四:springboot

驗證數據庫操做,安裝Mysql,在/src/main/resources/application.properties文件中配置數據庫鏈接及Hibernate參數(惟一的配置)架構

#datasource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/demodb?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=yuzhengzhong

#jpa
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

在項目pom.xml中引用mysql driverapp

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

建立實體類

@Entity
@Table(name = "t_sys_user")
public class UserEntity {

    @Id
    @Column(length = 36)
    private String id;

    @Column(length = 100)
    private String name;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

建立DAO數據庫操做類,Spring Boot已經整合了Spring Data JPA,按Spring Data JPA繼承其Repository類,在Service中注入該DAO Repository類

public interface UserRepository extends JpaRepository<UserEntity, String> {
    // 經常使用DB操做使用JpaRepository提供的接口便可,甚至默認無需實現類
}

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;
}

 

大功告成! 

總結下,能夠看到Spring Boot極大的簡化了框架的引入和多個框架之間的整合,其可以整合的功能還不少,如測試、熱加載、3A認證等等,很是強大,當前很是流行。

 

做者提供了上述代碼的樣例,能夠直接下載基於樣例開發 https://github.com/yuzhengzhong/springboot-base

 

引用:

http://spring.io/projects/spring-boot

 

相關文章
相關標籤/搜索