1. 程式人生 > >Spring Boot整合Spring MVC、Spring、Spring Data JPA(Hibernate)

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

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

步驟一:

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

步驟二:

使用IDE匯入步驟一生成的maven專案

步驟三:

驗證北向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..."; } }

步驟四:

驗證資料庫操作,安裝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 driver

<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認證等等,非常強大,當前非常流行。

引用:

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