SpringBoot非官方教程 | 第四篇:SpringBoot 整合JPA

转载请标明出处:
原文首发于:https://www.fangzhipeng.com/springboot/2017/05/04/sb4-jpaJ.html
本文出自方志朋的博客

个人博客纯净版:https://www.fangzhipeng.com/springboot/2017/05/04/sb4-jpaJ.html

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

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

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

添加相关依赖

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


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

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

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

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

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
    username: root
    password: 123456

  jpa:
    hibernate:
      ddl-auto: update  # 第一次简表create  后面用update
    show-sql: true

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

创建实体类

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

@Entity
public class Account {
    @Id
    @GeneratedValue
    private int id ;
    private String name ;
    private double money;

...  省略getter setter
}

Dao层

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

public interface AccountDao  extends JpaRepository<Account,Integer> {
}


Web层

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

@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    AccountDao accountDao;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<Account> 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 = true) String name,
                                @RequestParam(value = "money", required = true) double money) {
        Account account = new Account();
        account.setMoney(money);
        account.setName(name);
        account.setId(id);
        Account account1 = accountDao.saveAndFlush(account);

        return account1.toString();

    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public String postAccount(@RequestParam(value = "name") String name,
                              @RequestParam(value = "money") double money) {
        Account account = new Account();
        account.setMoney(money);
        account.setName(name);
        Account account1 = accountDao.save(account);
        return account1.toString();

    }


}


通过postman请求测试,代码已经全部通过测试。

源码下载:https://github.com/forezp/SpringBootLearning

更多阅读

史上最简单的 SpringCloud 教程汇总

SpringBoot教程汇总

Java面试题系列汇总

参考资料

accessing-data-jpa


扫码关注公众号有惊喜

(转载本站文章请注明作者和出处 方志朋的博客

  • 23
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 30
    评论
要将Spring Boot与JPA整合,首先需要在pom.xml文件中添加相应的依赖。这些依赖包括Spring Data JPA和MySQL驱动。例如,在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> ``` 接下来,你需要在Spring Boot应用程序的配置文件中添加数据库连接配置。你可以在application.properties或application.yml文件中添加以下配置: ```yaml spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name spring.datasource.username=your_username spring.datasource.password=your_password spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=update ``` 在这个配置中,你需要将`your_database_name`替换为你的数据库名称,`your_username`替换为你的数据库用户名,`your_password`替换为你的数据库密码。 然后,你可以创建实体类和存储库接口。实体类用于映射数据库表,而存储库接口用于定义对数据库的操作。可以使用`@Entity`和`@Table`注解来标识实体类,使用`@Repository`或`@RepositoryRestResource`注解来标识存储库接口。 最后,你可以在Spring Boot应用程序的启动类上添加`@EnableJpaRepositories`注解,以启用JPA存储库。 以上是将Spring Boot与JPA整合的基本步骤。通过这种方式,你可以使用JPA进行数据库操作,并且Spring Boot会自动为你处理大部分的配置和实现。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [springboot整合jpa,步骤详细(图文结合讲解)](https://blog.csdn.net/weixin_43442127/article/details/119953836)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [springboot整合JPA](https://blog.csdn.net/weixin_44740485/article/details/124904112)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 30
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值