zoukankan      html  css  js  c++  java
  • JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-001Mapping basic properties(@Basic、@Access、access="noop"、@Formula、@ColumnTransformer、@Generated、 @ColumnDefaul、@Temporal、@Enumerated)

    一、简介

    在JPA中,默认所有属性都会persist,属性要属于以下3种情况,Hibernate在启动时会报错

    1.java基本类型或包装类

    2.有注解 @Embedded

    3.有实现java.io.Serializable

    二、Overriding basic property defaults

    1.@javax.persistence.Transient

    如果不想属性被持久化,则注解

    @javax.persistence.Transient

    2.@Basic(optional = false)和@Column(nullable = false)、 @NotNull的区别

    all persistent properties are nullable and optional; 若注解@Basic(optional = false),则Hibernate会在SQL上加上not null约束,是依靠数据库来检查是否为空。若为空Hibernate will complain with an exception before hitting the database with an SQL
    statement.

    (1)

    @Basic(optional = false)
    BigDecimal initialPrice;

    (2)

    1 @Column(name = "START_PRICE", nullable = false)
    2 BigDecimal initialPrice;

    We recommend the Bean Validation @NotNull annotation so you can manually validate an Item instance and/or have your user interface code in the presentation layer execute validation checks automatically.

    三、Customizing property access

    1.使用@Access(AccessType.PROPERTY),使加载实体时访问get、set方法

     1 @Entity
     2 public class Item {
     3     @Id
     4     @GeneratedValue(generator = Constants.ID_GENERATOR)
     5     protected Long id;
     6 
     7     @Access(AccessType.PROPERTY)
     8     @Column(name = "ITEM_NAME")
     9     protected String name;
    10 
    11     //Hibernate calls  getName() and  setName() when loading and storing items.
    12     public String getName() {
    13         return name;
    14     }
    15 
    16     public void setName(String name) {
    17         this.name = !name.startsWith("AUCTION: ") ? "AUCTION: " + name : name;
    18     }
    19 }

    2.<access="noop">

    For example, let’s say the ITEM
    database table has a VALIDATED column and your Hibernate application won’t access this column through the domain model. It might be a legacy column or a column maintained by another application or database trigger. All you want is to refer to this column in a JPA query such as select i from Item i where i.validated = true or select i.id, i.validated from Item i . The Java Item class in your domain model doesn’t have this property; hence there is no place to put annotations. The only way to map such a virtual property is with an hbm.xml native metadata file:

    1 <hibernate-mapping>
    2     <class name="Item">
    3         <id name="id">
    4             ...
    5         </id>
    6         <property name="validated" column="VALIDATED" access="noop" />
    7     </class>
    8 </hibernate-mapping>

    This mapping tells Hibernate that you’d like to access the virtual Item#validated property, mapped to the VALIDATED column, in queries; but for value read/writes at runtime, you want “no operation” on an instance of Item . The class doesn’t have that attribute. Remember that such a native mapping file has to be complete: any annotations on the Item class are now ignored!

    3.Using derived properties

    The given SQL formulas are evaluated every time the Item entity is retrieved from the database and not at any other time, so the result may be outdated if other properties are modified. The properties never appear in an SQL INSERT or UPDATE , only in SELECT s. Evaluation occurs in the database; Hibernate embeds the SQL formula in the
    SELECT clause when loading the instance. 

    1 @org.hibernate.annotations.Formula(
    2     "substr(DESCRIPTION, 1, 12) || '...'"
    3 )
    4 protected String shortDescription;
    5 @org.hibernate.annotations.Formula(
    6     "(select avg(b.AMOUNT) from BID b where b.ITEM_ID = ID)"
    7 )
    8 protected BigDecimal averageBidAmount;

     4. @org.hibernate.annotations.ColumnTransformer

    1 @Column(name = "IMPERIALWEIGHT")
    2 @org.hibernate.annotations.ColumnTransformer(
    3     read = "IMPERIALWEIGHT / 2.20462",
    4     write = "? * 2.20462"
    5 )
    6 protected double metricWeight;

    Hibernate also applies column converters in query restrictions. For example, the following query retrieves all items with a weight of two kilograms:

    1 List < Item > result =
    2     em.createQuery("select i from Item i where i.metricWeight = :w")
    3     .setParameter("w", 2.0)
    4     .getResultList();

    The actual SQL executed by Hibernate for this query contains the following restriction in the WHERE clause:

    where i.IMPERIALWEIGHT / 2.20462=?

    注意:Note that your database probably won’t be able to rely on an index for this restriction;you’ll see a full table scan, because the weight for all ITEM rows has to be calculated to evaluate the restriction.

    5.@org.hibernate.annotations.Generated

    是否标@org.hibernate.annotations.Generated注解的区别:

    Typically, Hibernate applications need to refresh instances that contain any properties for which the database generates values, after saving. This means you would have to make another round trip to the database to read the value after inserting or updating a row. Marking properties as generated, however, lets the application delegate this responsibility to Hibernate. Essentially, whenever Hibernate issues an SQL INSERT or UPDATE for an entity that has declared generated properties, it does a SELECT immediately afterward to retrieve the generated values

     1 @Temporal(TemporalType.TIMESTAMP)
     2 @Column(insertable = false, updatable = false)
     3 @org.hibernate.annotations.Generated(
     4     org.hibernate.annotations.GenerationTime.ALWAYS
     5 )
     6 protected Date lastModified;
     7 @Column(insertable = false)
     8 @org.hibernate.annotations.ColumnDefault("1.00")
     9 @org.hibernate.annotations.Generated(
    10     org.hibernate.annotations.GenerationTime.INSERT
    11 )
    12 protected BigDecimal initialPrice;

    6.Temporal properties

    1 @Temporal(TemporalType.TIMESTAMP)
    2 @Column(updatable = false)
    3 @org.hibernate.annotations.CreationTimestamp
    4 protected Date createdOn;
    5 // Java 8 API
    6 // protected Instant reviewedOn;

    Available TemporalType options are DATE , TIME , and TIMESTAMP , establishing what part of the temporal value should be stored in the database.

    7.@Enumerated,若不注解,枚举默认是次序数字

    1 package org.jpwh.model.querying;
    2 
    3 public enum AuctionType {
    4     HIGHEST_BID,
    5     LOWEST_BID,
    6     FIXED_PRICE
    7 }
    1 @NotNull
    2 @Enumerated(EnumType.STRING)
    3 protected AuctionType auctionType = AuctionType.HIGHEST_BID;

    Without the @Enumerated annotation, Hibernate would store the ORDINAL position of the value. That is, it would store 1 for HIGHEST_BID , 2 for LOWEST_BID , and 3 for FIXED_PRICE . This is a brittle default;

    8.

    四、

    五、

  • 相关阅读:
    作业4.称体重
    一、虚拟环境.二、路由配置主页与404.三、2.x路由分发.四、伪静态.五、request对象.六、FBV与CBV.七、文件上传.
    一、数据库表中字段的增删改查,二、路由基础.三、有名无名分组.四、多app共存的路由分配.五、多app共存时模板冲突问题.六、创建app流程.七、路由分发.八、路由别名,九、名称空间.十、反向解析.十一、2.x新特性.十二、自定义转换器
    Django项目的创建与介绍.应用的创建与介绍.启动项目.pycharm创建启动项目.生命周期.三件套.静态文件.请求及数据.配置Mysql完成数据迁移.单表ORM记录的增删改查
    学习Django,http协议,
    值类型之间的相互转化,运算符,if条件判断,循环,函数
    js导读,js引入,js选择器,事件,操作页面文档,计算后样式,数据类型
    字体图标,盒子显隐,overflow属性,伪类设计边框,盒子阴影2d形变
    浮动布局,定位布局(固定定位,绝对定位,相对定位),过渡动画
    盒子总结,文本属性操作,reset操作,高级选择器,高级选择器优先级,边界圆角(了解),a标签的四大伪类,背景图片操作,背景图片之精灵图
  • 原文地址:https://www.cnblogs.com/shamgod/p/5362716.html
Copyright © 2011-2022 走看看