zoukankan      html  css  js  c++  java
  • jpa的一些知识点

    jpa是持久层框架,前身是hibernate

    项目中使用:

    (一)、pom.xml引入

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

    (二)。application.yml文件配置

    #环境配置 dev就是新建的application-dev.yml
    spring:
      profiles:
        active: dev
      jpa:
        hibernate:
    #      create-drop的话,每次修改字段,就会把表清空
          ddl-auto: update

    (三)、创建实体类

    @Entity
    public class Banner {
        // 这是表的主键
        @Id
        private String id;
        private String name;
        private String description;
        private String img;
        private String title;
    }

    运行项目,就可以在数据库创建实体类对应的表

    备注:

    有时候会遇到和这个错误

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path 
    resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed;
    nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.zb.missyou.model.Banner

    这是因为没有在实体类中指定主键,就是Banner里的@Id

    (四)、查询的时候控制台显示sql语句

    执行Repository查询语句(14-3-2)

    application-dev.yml

    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/sleeve?characterEncoding=UTF-8&serverTimezone=GMT%2B8
        username: root
        password: x5219438
       # 显示sql语句
      jpa:
        properties:
          hibernate:
            show_sql: true
            format_sql: true

     (五)、懒加载和急加载(14-3-3)

     (六)、 双向一对多配置(14-3-4)

       多方:维护端

       一方:关系被维护端

       Banner

    @OneToMany(mappedBy = "banner")
        private List<BannerItem> items;

    BannerItem

    @ManyToOne
        @JoinColumn(name = "bannerId")
        private Banner banner;

    jpa设置双向一对多有三个步骤:

    第一、在被维护端设置OneToMany

    第二、在维护端设置ManyToOne和外键

    第三、在被维护端设置mappedBy ,值就是维护端导航属性的名字,就是上面的banner

    备注:

    @JoinColumn我的理解就是给一对多的多表添加外键;如果不加的话,会生成一张第三张中间表,保存俩张表的主键id

  • 相关阅读:
    rgw
    comm命令
    s3cmd、aws的使用
    【RPM包的制作】
    【C++高级编程 | 23】future、packaged_task等使用机制
    【shell语法 | 01】基础练习
    【宏 | 01】#、##、__VA_ARGS__和##__VA_ARGS__的作用
    求求你别再用offset和limit分页了
    你和阿里程序员的差距在哪里?看看鸿蒙级计算机底层知识总结与操作系统就知道了
    什么?CPU 怎么运行代码?太刁难人了吧!
  • 原文地址:https://www.cnblogs.com/zhaobao1830/p/12703764.html
Copyright © 2011-2022 走看看