SpringBoot + JPA

JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中.

添加相关依赖

SpringBoot版本:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
    </parent>

JPA:


<dependency>
    <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-jpa
     </artifactId>
</dependency>

添加mysql连接类和连接池类MySql-connector:

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

在application.properties文件配置数据源:

server.port=8088

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=password

#jpa learn example 
spring.jpa.hibernate.ddl-auto= update //如果是第一次建立用 create 但create之后一定要改为update。不然一直都是新建表
spring.jpa.show-sql= true

创建实体类

通过@Entity 表明是一个映射的实体类, @Id表明id, @GeneratedValue 字段自动生成

package com.yms.demo.domain.pojo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;


@Entity
public class TbArticleDirection {

    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    private String description;

    get...set...

}

Dao层

数据访问层,通过编写一个继承自 JpaRepository 的接口就能完成数据访问,其中包含了几本的单表查询的方法,非常的方便。值得注意的是,这个TbArticleDirection 对象名,而不是具体的表名,另外Interger是主键的类型,一般为Integer或者Long

package com.yms.demo.dao;

import com.yms.demo.domain.pojo.TbArticleDirection;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ArticleDirectionRepo extends JpaRepository<TbArticleDirection,Integer> {

}

Web层

package com.yms.demo.web;


import com.yms.demo.dao.ArticleDirectionRepo;
import com.yms.demo.domain.pojo.TbArticleDirection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/article")
public class ArticleDirectionController {

    @Autowired
    private ArticleDirectionRepo articleDirectionRepo;

    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    public List<TbArticleDirection> findAll() {
        return articleDirectionRepo.findAll();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public TbArticleDirection findOne(@PathVariable("id") Integer id) {
        return articleDirectionRepo.findOne(id);
    }


}

猜你喜欢

转载自blog.csdn.net/yangmingsen1999/article/details/81907784