zoukankan      html  css  js  c++  java
  • JPA(三):JPA基本注解

    基本注解

    @Entity

    标注用于实体类声明语句之前,指出该Java类为实体类,将映射到指定的数据库表。如声明一个实体类Customer,将它映射到数据的coustomer表上。

    package com.dxsoft.jpa.helloword;
    
    import javax.persistence.Entity;
    
    @Entity
    public class Person {
      //...  
    }

    @Table

    • 当实体类与其映射的数据库表名不同名时,需要使用@Table标注说明,该注解与@Entity标注并列使用,置于实体类声明语句之前,可写于单独语句行,也可与声明数据同行。
    • @Table标注的常用选项是name,用于指明数据库的表名。
    • @Table标注还有两个可选项catalog和schema用于设置表所属的数据库目录或模式,通常为数据库名。
    • uniqueConstraints选项用于设置约束条件,通常不须设置。
    package com.dxsoft.jpa.helloword;
    
    import javax.persistence.Entity;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "jpa_person")
    public class Person {
      //。。。  
    }

    @Id

    • @Id标注用于声明一个实体类的属性映射为数据库的主键列。该属性通常置于属性声明语句之前,可与声明数据同行,也可卸载单独行上。
    • @Id标注也可置于属性的getter方法之前。

    @GeneratedValue

    • @GeneratedValue用于标注主键的生成策略,通过strategy属性指定。默认情况下,JPA自动选择一个最合适底层数据库的主键生成策略:SqlServer对应identity,MySql对饮auto increment。
    • 在javax.persistence.GenerationType中定义了以下几种可供选择的策略:
      •   --- IDENTITY:采用数据库ID自增长的方式来自增主键字段,Oracle不支持这种方式(oracle12g后,应该支持了。);
      •   --- AUTO:JPA自动选择合适的策略,是默认选项;
      •   --- SEQUENCE:通过序列产生主键,通过@SequenceGenerator注解指定序列名,MySql不支持这种方式。
      •   --- TABLE:通过表产生键,框架借助由表模拟序列产生主键,使用该策略可以使应用更易于数据库移植。

    @Column

    • 当实体的属性与其映射的数据库表的列不同名时需要使用@Column标注说明,该属性通常置于实体的属性声明语句之前,还可与@Id标注一起使用。
    • @Column标注的常量属性是name,用于设置映射数据库表的列名。此外,该注解还包含其他多个属性,比如:unique,nullable,length等。
    • @Column标注的columnDefinition属性:表示该字段在数据中的实际类型,通常ORM框架可以根据属性类型自动判断数据中的字段的类型,但是对于Date类型仍无法确定数据库中字段类型究竟是Date,Time还是Timestamp。此外,String的默认类型为varchar,如果要将String类型映射到特定数据库的BLOB或Text字段类型。
    • @Column标注也可以置于属性的getter方法之前。

    @Basic

    • @Basic表示一个简单的属性到数据库表的字段的映射,对于没有任何标注的getXxx()方法,默认即为Basic
    • fetch:表示该属性的读取策略,有EAGER和LAZY两种,分别表示主支抓取和延迟加载,默认为EAGER
    • optional:表示该属性是否允许为null,默认为true。

    @Transient

    • 表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性。
    • 如果一个属性并非数据库的字段映射,就务必将其标示为@Transient,否则,ORM框架默认其注解为@Basic。

    假设Person类需要扩展一个帮助方法,getUserInfo()

        // 帮助方法,不希望保存到数据库,但是需要动态获取Customer对象的属性。
        public String getUserInfo() {
            return "username:" + fullName + ",age:" + age;
        }

    此时,运行时抛出异常。

    解决上边需求,而且又不抛异常的方案:需要在getUserInfo()方法上添加注解@Transient

    @Temporal

    • 在核心的JAVA API中并没有定义Date类型的精度(temporal precision)。而在数据库中,表示Date类型的数据类型有DATE,TIME和TEIMSTAMP三种精度(即单纯的日期,时间,或者两者兼备)。在运行属性映射是可使用
    • @Temporal注解来调整Date精度。

    修改项目:

    1)修改Person实体类,新增birth,createTime字段

    package com.dxsoft.jpa.helloword;
    
    import java.util.Date;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import javax.persistence.Transient;
    
    @Entity
    @Table(name = "jpa_person")
    public class Person {
        private Integer id;
        private String fullName;
        private int age;
        private Date birth;
        private Date createTime;
    
        public Person() {
    
        }
    
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Id
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        @Column(name = "full_name", nullable = false, length = 64)
        public String getFullName() {
            return fullName;
        }
    
        public void setFullName(String fullName) {
            this.fullName = fullName;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public Date getBirth() {
            return birth;
        }
    
        public void setBirth(Date birth) {
            this.birth = birth;
        }
    
        public Date getCreateTime() {
            return createTime;
        }
    
        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }
    
        // 帮助方法,不希望保存到数据库,但是需要动态获取Customer对象的属性。
        @Transient
        public String getUserInfo() {
            return "username:" + fullName + ",age:" + age;
        }
    
        @Override
        public String toString() {
            return "Person [id=" + id + ", fullName=" + fullName + ", age=" + age + "]";
        }
    
    }
    View Code

    2)修改测试main函数

    此时,删除mysql数据中的jpa_person表,重新运行。

    运行日志:

    Hibernate: 
        
        create table hibernate_sequence (
           next_val bigint
        ) engine=InnoDB
    Hibernate: 
        
        insert into hibernate_sequence values ( 1 )
    Hibernate: 
        
        create table jpa_person (
           id integer not null,
            age integer not null,
            birth datetime,
            createTime datetime,
            full_name varchar(64) not null,
            primary key (id)
        ) engine=InnoDB
    Fri Jun 15 12:25:35 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    Hibernate: 
        select
            next_val as id_val 
        from
            hibernate_sequence for update
                
    Hibernate: 
        update
            hibernate_sequence 
        set
            next_val= ? 
        where
            next_val=?
    Hibernate: 
        insert 
        into
            jpa_person
            (age, birth, createTime, full_name, id) 
        values
            (?, ?, ?, ?, ?)
    六月 15, 2018 12:25:35 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
    INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://127.0.0.1:3306/jpa]
    complete..
    View Code

    此时查看mysql中表

    显然这里的createTime可以使用,但是birth的日期精度要求是短日期格式就可以。

    使用@Temporal注解来调整Date精度

    修改person.java实体类

    删除mysql中数据库jpa_person表,重新运行查看数据表结构,及数据。

    运行日志:

    Hibernate: 
        
        create table hibernate_sequence (
           next_val bigint
        ) engine=InnoDB
    Hibernate: 
        
        insert into hibernate_sequence values ( 1 )
    Hibernate: 
        
        create table jpa_person (
           id integer not null,
            age integer not null,
            birth date,
            createTime datetime,
            full_name varchar(64) not null,
            primary key (id)
        ) engine=InnoDB
    Fri Jun 15 12:30:16 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    Hibernate: 
        select
            next_val as id_val 
        from
            hibernate_sequence for update
                
    Hibernate: 
        update
            hibernate_sequence 
        set
            next_val= ? 
        where
            next_val=?
    Hibernate: 
        insert 
        into
            jpa_person
            (age, birth, createTime, full_name, id) 
        values
            (?, ?, ?, ?, ?)
    六月 15, 2018 12:30:16 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
    INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://127.0.0.1:3306/jpa]
    complete..
    View Code

     

    用table来生成数据表的主键

    • 将当前主键的值单独保存到一个数据的表中,主键的值每次都是从指定的表中查询获得
    • 这种方式生成主键的策略可以适用于任何数据库,不必担心不同数据不兼容造成的问题。

    1)修改Person.java

        @TableGenerator(
                name = "person_id_generator", 
                table = "jpa_id_generator", 
                pkColumnName = "pk_name", 
                pkColumnValue = "person_id", 
                valueColumnName = "pk_value", 
                initialValue = 1, 
                allocationSize = 100)
        @GeneratedValue(
                strategy = GenerationType.TABLE, 
                generator = "person_id_generator")
        @Id
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }

    2)删除已经存在表jpa_person,重新执行三次main函数:

    3)发现新增了jpa_id_generator表,表jpa_id_generator中也有了记录:

     jpa_person记录为:

    jpa_id_generator记录为:

     

  • 相关阅读:
    Java基础知识【上】(转载)
    Windows下Python中pip安装Pillow报错总结(转载)
    CentOS7下安装Python的pip
    CentOS7安装NodeJS6.9
    PostGIS(解压版)安装
    CentOS7中安装Python3.5
    CentOS7安装docker
    Centos7更改默认启动模式(转载)
    CentOS7 查看IP、Gateway、DNS、Hostname
    CentOS7系统安装及初始化
  • 原文地址:https://www.cnblogs.com/yy3b2007com/p/9186698.html
Copyright © 2011-2022 走看看