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)
@Column(name = "START_PRICE", nullable = false)
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方法
@Entity
public class Item {
@Id
@GeneratedValue(generator = Constants.ID_GENERATOR)
protected Long id; @Access(AccessType.PROPERTY)
@Column(name = "ITEM_NAME")
protected String name; //Hibernate calls getName() and setName() when loading and storing items.
public String getName() {
return name;
} public void setName(String name) {
this.name = !name.startsWith("AUCTION: ") ? "AUCTION: " + name : name;
}
}
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:
<hibernate-mapping>
<class name="Item">
<id name="id">
...
</id>
<property name="validated" column="VALIDATED" access="noop" />
</class>
</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.
@org.hibernate.annotations.Formula(
"substr(DESCRIPTION, 1, 12) || '...'"
)
protected String shortDescription;
@org.hibernate.annotations.Formula(
"(select avg(b.AMOUNT) from BID b where b.ITEM_ID = ID)"
)
protected BigDecimal averageBidAmount;
4. @org.hibernate.annotations.ColumnTransformer
@Column(name = "IMPERIALWEIGHT")
@org.hibernate.annotations.ColumnTransformer(
read = "IMPERIALWEIGHT / 2.20462",
write = "? * 2.20462"
)
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:
List < Item > result =
em.createQuery("select i from Item i where i.metricWeight = :w")
.setParameter("w", 2.0)
.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
@Temporal(TemporalType.TIMESTAMP)
@Column(insertable = false, updatable = false)
@org.hibernate.annotations.Generated(
org.hibernate.annotations.GenerationTime.ALWAYS
)
protected Date lastModified;
@Column(insertable = false)
@org.hibernate.annotations.ColumnDefault("1.00")
@org.hibernate.annotations.Generated(
org.hibernate.annotations.GenerationTime.INSERT
)
protected BigDecimal initialPrice;
6.Temporal properties
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
@org.hibernate.annotations.CreationTimestamp
protected Date createdOn;
// Java 8 API
// 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,若不注解,枚举默认是次序数字
package org.jpwh.model.querying;
public enum AuctionType {
HIGHEST_BID,
LOWEST_BID,
FIXED_PRICE
}
@NotNull
@Enumerated(EnumType.STRING)
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.
四、
五、
JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-001Mapping basic properties(@Basic、@Access、access="noop"、@Formula、@ColumnTransformer、@Generated、 @ColumnDefaul、@Temporal、@Enumerated)的更多相关文章
- JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-007UserTypes的用法(@org.hibernate.annotations.Type、@org.hibernate.annotations.TypeDefs、CompositeUserType、DynamicParameterizedType、、、)
一.结构 二.Hibernate支持的UserTypes接口 UserType —You can transform values by interacting with the plain JD ...
- JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-006类型转换器( @Converter(autoApply = true) 、type="converter:qualified.ConverterName" )
一.结构 二.代码 1. package org.jpwh.model.advanced; import java.io.Serializable; import java.math.BigDecim ...
- JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-005控制类型映射(Nationalized、@LOB、@org.hibernate.annotations.Type)
一.简介 1. 2. 3. 4. to override this default mapping. The JPA specification has a convenient shortcut a ...
- JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-004嵌套组件的注解AttributeOverrides
一.数据库 二.代码 1. package org.jpwh.model.advanced; import javax.persistence.AttributeOverride; import ja ...
- JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-003使用@AttributeOverrides
Each @AttributeOverride for a component property is “complete”: any JPA or Hibernate annotation on t ...
- JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-002使用@Embeddable
一.数据库 二.代码 1. package org.jpwh.model.simple; import javax.persistence.Column; import javax.persisten ...
- JavaPersistenceWithHibernate第二版笔记-第四章-Mapping persistent classes-003映射实体时的可选操作(<delimited-identifiers/>、PhysicalNamingStrategy、PhysicalNamingStrategyStandardImpl、、、)
一.自定义映射的表名 1. @Entity @Table(name = "USERS") public class User implements Serializable { / ...
- JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-003Table per concrete class with unions(@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)、<union-subclass>)
一.代码 1. package org.jpwh.model.inheritance.tableperclass; import org.jpwh.model.Constants; import ja ...
- JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-002Table per concrete class with implicit polymorphism(@MappedSuperclass、@AttributeOverride)
一.结构 二.代码 1. package org.jpwh.model.inheritance.mappedsuperclass; import javax.persistence.MappedSup ...
随机推荐
- ABAP自定义类的构造方法
REPORT ytest_011. *----------------------------------------------------------------------* * CLASS z ...
- Ant学习---第一节:Ant安装和简单使用
一.下载 ant 插件,路径如下: http://ant.apache.org/bindownload.cgi 二.安装 ant 插件,解压下载下来的 ant 插件,配置环境变量(最好系统环境变量), ...
- 团队开发——SCRUM报告(一)
一.成员介绍 队长:胡亚宝 PM:曹美娜 成员:焦燕.袁亚姣.黄亚萍 二.sprint会议 由于之前是一五一小长假,所以距离上次会议中间隔了很长时间,这里在对上次会议做一下简单的汇总 在上次会议上我们 ...
- 大作业NABC分析结果
大作业NABC分析结果 这次的大作业计划制作一款关于七巧板的游戏软件.关于编写的APP的NABC需求分析: N:需求 ,本款软件主要面向一些在校的大学生,他们在校空闲时间比较多,而且热衷于一些益智类游 ...
- PDO应用
<?php //PDO:数据访问抽象层//dsn:数据源://带有事务功能:$dsn = "mysql:host=localhost;dbname=mydb"; ——建立数 ...
- javascript_04 数据类型
ECMAScript 数据类型 标准 核心 数据类型 typeof 判断数据类型 数字型 布尔型 对象类型 函数 字符串 undefined 未定义 数字型 字符型 var s='1233 ...
- 《我是IT小小鸟》读书笔记
转眼间,大学的第二学期悄悄来临了,老师给我们布置了一道原本我以为很无趣的题目----写<我是IT的读书笔记>,但是我读了<我是IT小小鸟>这本书后,令我受益匪浅:五个人,每个人 ...
- zoj 2760 How Many Shortest Path 最大流
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1760 Given a weighted directed graph ...
- mvc从xheditor编辑器中获取内容时存在潜在危险
xmfdsh在使用xheditor提交要发布的文章等内容的时候出现了如下的错误: 从客户端(Content="<p style="text-align...")中检 ...
- HackPorts – Mac OS X 渗透测试框架与工具
HackPorts是一个OS X 下的一个渗透框架. HackPorts是一个“超级工程”,充分利用现有的代码移植工作,安全专业人员现在可以使用数以百计的渗透工具在Mac系统中,而不需要虚拟机. 工具 ...