SpringBoot如何整合JPA

  介绍

这篇文章将为大家详细讲解有关SpringBoot如何整合JPA、小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

JPA全称Java Persistence API。JPA通过JDK 5.0注解或XML描述对象,关系表的映射关系,并将运行期的实体对象持久化到数据库中。

JPA的目标之一是制定一个可以由很多供应商实现的API,并且开发人员可以编码来实现该API,而不是使用私有供应商特有的API。

JPA是需要供应商来实现其功能的,Hibernate就是JPA提供者中很强的一个,应该说无人能出其右。从功能上来说,JPA就是Hibernate功能的一个子集。

添加相关依赖

添加spring-boot-starter-jdbc依赖:

 & lt; dependency>
  ,,,,,,,,,,,& lt; groupId> org.springframework.boot
  ,,,,,,,,,,,& lt; artifactId> spring-boot-starter-data-jpa
  ,,,,,,,,,,,& lt;/artifactId>
  ,,,,,,,& lt;/dependency> 

添加mysql连接类和连接池类:

<>之前,,,,& lt; dependency>   ,,,,,,,,,,,& lt; groupId> mysql   ,,,,,,,,,,,& lt; artifactId> mysql-connector-java   ,,,,,,,,,,,& lt; scope> runtime   ,,,,,,,& lt;/dependency>

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

春:
  数据源:才能
  ,,,driver-class-name: com.mysql.jdbc.Driver
  ,,,url:, jdbc: mysql://localhost: 3306/测试? useUnicode=true& characterEncoding=utf8& characterSetResults=utf8
  ,,,用户名:根
  ,,,密码:123456
  
  jpa:才能
  hibernate:,,,
  ,,,,,ddl-auto:, update , #,第一次简表create ,后面用更新
  ,,,show-sql:,真正的

注意,如果通过jpa在数据库中建表,将jpa。hibernate, ddl-auto改为创建、建完表之后,要改为更新,要不然每次重启工程会删除表并新建。

创建实体类

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

 @ entity
  public  class  Account  {
  ,,@ id
  ,,@GeneratedValue
  ,,,private  int  id ;
  ,,,private  String  name ;
  ,,,private  double 资金;
  
  ……,,省略getter  setter
  }

Dao层

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

 public  interface  AccountDao , extends  JpaRepository<帐户,Integer>, {
  Web层}

在这个栗子中我简略了服务层的书,写在实际开发中,不可省略。新写一个控制器,写几个restful api来测试数据的访问。

 @RestController
  @RequestMapping (“/account")
  public  class  AccountController  {
  
  ,,@ autowired
  ,,,AccountDao  accountDao;
  
  ,,,@RequestMapping (=value “/list",, method =, RequestMethod.GET)
  ,,,public  List, getAccounts (), {
  ,,,,,,,return  accountDao.findAll ();
  ,,,}
  
  ,,,@RequestMapping (=value “/{id},,, method =, RequestMethod.GET)
  ,,,public  Account  getAccountById (@PathVariable (“id"), int  id), {
  ,,,,,,,return  accountDao.findOne (id);
  ,,,}
  
  ,,,@RequestMapping (=value “/{id},,, method =, RequestMethod.PUT)
  ,,,public  String  updateAccount (@PathVariable (“id"), int  id, @RequestParam (=value “name",, required =,真的),String 名字,
  ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@RequestParam (=value “money",, required =,真的),double 钱),{
  ,,,,,,,Account  Account =, new 帐户();
  ,,,,,,,account.setMoney(钱);
  ,,,,,,,account.setName(名称);
  ,,,,,,,account.setId (id);
  ,,,,,,,Account  account1 =, accountDao.saveAndFlush(账户);
  
  ,,,,,,,return  account1.toString ();
  
  ,,,}
  
  ,,,@RequestMapping (=value ““,, method =, RequestMethod.POST)
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null

SpringBoot如何整合JPA