iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >springboot jpaRepository为什么一定要对Entity序列化
  • 132
分享到

springboot jpaRepository为什么一定要对Entity序列化

2023-06-21 23:06:29 132人浏览 八月长安
摘要

这篇文章主要介绍“SpringBoot jpaRepository为什么一定要对Entity序列化”,在日常操作中,相信很多人在springboot jpaRepository为什么一定要对Entity序列化问题上存在疑

这篇文章主要介绍“SpringBoot jpaRepository为什么一定要对Entity序列化”,在日常操作中,相信很多人在springboot jpaRepository为什么一定要对Entity序列化问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”springboot jpaRepository为什么一定要对Entity序列化”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

    springboot jpaRepository对Entity序列化

    1. 问题

    一开始,我没有对实体类Inventory序列化,导致在使用内嵌数据库H2的JPA时,它直接安装字母序列把表Inventory的字段生成。

    举例,原来我按照

    inventory(id, name, quantity, type, comment)

    顺序写的数据库导入表,但是因为没有序列化,导致表结构变成

    inventory(id, comment,name, quantity, type )

    所以后面JPA处理失败。

    2. 写个基本的JpaRepository的使用

    顺便记录一下写spring cloud 基于和H2 database的jpa简单restful 程序。

    实体类Inventory

    package com.example.demo; import java.io.Serializable; import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.SequenceGenerator; @Entitypublic class Inventory implements Serializable{     private static final long serialVersionUID = 1L;     @Id    @SequenceGenerator(name="inventory_generator", sequenceName="inventory_sequence", initialValue = 2)    @GeneratedValue(generator = "inventory_generator")    private Integer id;    @Column(nullable = false)    private String name;    @Column(nullable = false)    private Integer quantity;    @Column(nullable = false)    private Integer type;    @Column(nullable = false)    private String comment;    public Inventory(Integer id, String name, Integer quantity, Integer type, String comment) {        super();        this.id = id;        this.name = name;        this.quantity = quantity;        this.type = type;        this.comment = comment;    }    public Inventory() {        super();    }    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Integer getQuantity() {        return quantity;    }    public void setQuantity(Integer quantity) {        this.quantity = quantity;    }    public Integer getType() {        return type;    }    public void setType(Integer type) {        this.type = type;    }    public String getComment() {        return comment;    }    public void setComment(String comment) {        this.comment = comment;    }    @Override    public String toString() {        return "Inventory [id=" + id + ", name=" + name + ", quantity=" + quantity + ", type=" + type + ", comment="                + comment + "]";    }}

    下面使用JpaRepository简化开发流程,非常舒服地定义简单的service 接口即可,会自动实现,大赞。

    package com.example.demo; import org.springframework.data.jpa.repository.JpaRepository; public interface InventoryRepository extends JpaRepository<Inventory, Integer> {     Inventory findById(Integer id); }

    我把controller方法放到了springboot启动类里面,这又是一个大问题,因为我的项目只有放在这才能被dispatcher转发,简直了。

    这里的@EnableDiscoveryClient 是因为我在做spring cloud的eureka 服务发现,需要这个注解让注册中心发现这个服务。

    package com.example.demo; import java.time.LocalTime; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.transaction.annotation.Transactional;import org.springframework.WEB.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController; @SpringBootApplication@EnableDiscoveryClient@RestControllerpublic class InventoryApplication {     public static void main(String[] args) {        SpringApplication.run(InventoryApplication.class, args);    }    @Autowired    private InventoryRepository inventoryRepository;     @Value("${server.port}")    private Integer port;     @RequestMapping("/info")    public String info(){        inventoryRepository.save(new Inventory(1, "火锅底料", 10000, 1, "你吃火锅,我吃底料"));        inventoryRepository.save(new Inventory(2, "微服务架构", 100, 2, "微服务还是要考虑 一波"));        return "{Inventory[port:"+port+", info:库存微服务"+"]}";    }     @GetMapping("/get/{id}")    @ResponseBody    @Transactional    public String getById(@PathVariable("id")Integer id){        return inventoryRepository.findById(id).toString();    }     @GetMapping("/")    @ResponseBody    @Transactional    public String re(){        return inventoryRepository.findAll().toString();    }     @GetMapping("/delete/{id}")    @ResponseBody    @Transactional    public String delete(@PathVariable("id")Integer id){        inventoryRepository.delete(id);        return "delete successfully";    }     @GetMapping("/save/id={id}&name={name}&quantity={quantity}&type={type}&comment={comment}")    public String save(@PathVariable("id")Integer id,@PathVariable("name")String name,            @PathVariable("quantity")Integer quantity,@PathVariable("type")Integer type,            @PathVariable("comment")String comment){        inventoryRepository.save(new Inventory(id,name,quantity,type,comment));        System.out.println(new Inventory(id,name,quantity,type,comment));        //强调一下identity和auto        return "save successfully";    }     @GetMapping("/update/id={id}&name={name}&quantity={quantity}&type={type}&comment={comment}")    @ResponseBody    @Transactional    public String update(@PathVariable("id")Integer id,@PathVariable("name")String name,            @PathVariable("quantity")Integer quantity,@PathVariable("type")Integer type,            @PathVariable("comment")String comment){        Inventory inventory=inventoryRepository.findById(id);        if(inventory.getComment().length()<LocalTime.now().toString().length()){            inventory.setComment(inventory.getComment()+LocalTime.now());        }else{            inventory.setComment(inventory.getComment().substring(0,inventory.getComment().length()-                    LocalTime.now().toString().length())+LocalTime.now());        }        inventoryRepository.save(inventory);        inventoryRepository.flush();        return "update successfully";    }}

    application.properties的配置很关键,搜了不少教程

    spring.jpa.show-sql=truelogging.pattern.level=traceserver.port=8765spring.application.name=inventoryserver.Tomcat.max-threads=1000eureka.instance.leaseRenewalIntervalInSeconds= 10eureka.client.reGIStryFetchIntervalSeconds= 5eureka.client.serviceUrl.defaultZone=Http://localhost:8889/eureka#eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${eureka.instance.server.port}/eureka #spring.thymeleaf.prefix=classpath:/templates/  #spring.thymeleaf.suffix=.html  #spring.thymeleaf.mode=HTML5  #spring.thymeleaf.encoding=UTF-8  # ;charset=<encoding> is added  #spring.thymeleaf.content-type=text/html  # set to false for hot refresh  spring.h3.console.enabled=truespring.thymeleaf.cache=false  spring.jpa.hibernate.ddl-auto=update#这里是把h3持久化到本地文件夹,这可以保持数据spring.datasource.url=jdbc:h3:file:C\:/h3/h3cache;AUTO_SERVER=TRUE;DB_CLOSE_DELAY=-1logging.file=c\:/h3/logging.loglogging.level.org.hibernate=debug#spring.datasource.data=classpath:import.sql

    数据库是自动导入的,只要命名方式是import.sql, 放在src/main/resources下面就可以

    insert into inventory(id, name, quantity, type, comment) values (1, "火锅底料", 10000, 1, "你吃火锅,我吃底料")insert into inventory(id, name, quantity, type, comment) values (2, "微服务架构", 100, 2, "微服务还是要考虑 一波")

    最后一个简单的测试

    junit测试一波

    package com.example.demo; import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)@SpringBootTestpublic class InventoryApplicationTests {     @Autowired    private InventoryRepository inventoriRepository;     @Test    public void test2() {        System.out.println(inventoriRepository.findAll());    } }

    springboot jpaRepository为什么一定要对Entity序列化

    上图是项目结构图

    springboot 使用JpaRepository

    在对数据库操作时使用 MissionInfoRepository,对应的实体类必须用下面两个注解修饰

    @Entity@Table(name = "mission_info")

    主键用下面修饰

     @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", nullable = false)

    springboot jpaRepository为什么一定要对Entity序列化

    到此,关于“springboot jpaRepository为什么一定要对Entity序列化”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程网网站,小编会继续努力为大家带来更多实用的文章!

    --结束END--

    本文标题: springboot jpaRepository为什么一定要对Entity序列化

    本文链接: https://www.lsjlt.com/news/301351.html(转载时请注明来源链接)

    有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

    本篇文章演示代码以及资料文档资料下载

    下载Word文档到电脑,方便收藏和打印~

    下载Word文档
    猜你喜欢
    • C++ 生态系统中流行库和框架的贡献指南
      作为 c++++ 开发人员,通过遵循以下步骤即可为流行库和框架做出贡献:选择一个项目并熟悉其代码库。在 issue 跟踪器中寻找适合初学者的问题。创建一个新分支,实现修复并添加测试。提交...
      99+
      2024-05-15
      框架 c++ 流行库 git
    • C++ 生态系统中流行库和框架的社区支持情况
      c++++生态系统中流行库和框架的社区支持情况:boost:活跃的社区提供广泛的文档、教程和讨论区,确保持续的维护和更新。qt:庞大的社区提供丰富的文档、示例和论坛,积极参与开发和维护。...
      99+
      2024-05-15
      生态系统 社区支持 c++ overflow 标准库
    • c++中if elseif使用规则
      c++ 中 if-else if 语句的使用规则为:语法:if (条件1) { // 执行代码块 1} else if (条件 2) { // 执行代码块 2}// ...else ...
      99+
      2024-05-15
      c++
    • c++中的继承怎么写
      继承是一种允许类从现有类派生并访问其成员的强大机制。在 c++ 中,继承类型包括:单继承:一个子类从一个基类继承。多继承:一个子类从多个基类继承。层次继承:多个子类从同一个基类继承。多层...
      99+
      2024-05-15
      c++
    • c++中如何使用类和对象掌握目标
      在 c++ 中创建类和对象:使用 class 关键字定义类,包含数据成员和方法。使用对象名称和类名称创建对象。访问权限包括:公有、受保护和私有。数据成员是类的变量,每个对象拥有自己的副本...
      99+
      2024-05-15
      c++
    • c++中优先级是什么意思
      c++ 中的优先级规则:优先级高的操作符先执行,相同优先级的从左到右执行,括号可改变执行顺序。操作符优先级表包含从最高到最低的优先级列表,其中赋值运算符具有最低优先级。通过了解优先级,可...
      99+
      2024-05-15
      c++
    • c++中a+是什么意思
      c++ 中的 a+ 运算符表示自增运算符,用于将变量递增 1 并将结果存储在同一变量中。语法为 a++,用法包括循环和计数器。它可与后置递增运算符 ++a 交换使用,后者在表达式求值后递...
      99+
      2024-05-15
      c++
    • c++中a.b什么意思
      c++kquote>“a.b”表示对象“a”的成员“b”,用于访问对象成员,可用“对象名.成员名”的语法。它还可以用于访问嵌套成员,如“对象名.嵌套成员名.成员名”的语法。 c++...
      99+
      2024-05-15
      c++
    • C++ 并发编程库的优缺点
      c++++ 提供了多种并发编程库,满足不同场景下的需求。线程库 (std::thread) 易于使用但开销大;异步库 (std::async) 可异步执行任务,但 api 复杂;协程库 ...
      99+
      2024-05-15
      c++ 并发编程
    • 如何在 Golang 中备份数据库?
      在 golang 中备份数据库对于保护数据至关重要。可以使用标准库中的 database/sql 包,或第三方包如 github.com/go-sql-driver/mysql。具体步骤...
      99+
      2024-05-15
      golang 数据库备份 mysql git 标准库
    软考高级职称资格查询
    编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
    • 官方手机版

    • 微信公众号

    • 商务合作