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 annotation for this purpose, @Lob
@Entity
public class Item {
@Lob
protected byte[] image;
@Lob
protected String description;
// ...
}
This maps the byte[] to an SQL BLOB data type and the String to a CLOB . Unfortunately, you still don’t get lazy loading with this design.
Alternatively, you can switch the type of property in your Java class. JDBC supports locator objects ( LOB s) directly. If your Java property is java.sql.Clob or java .sql.Blob , you get lazy loading without bytecode instrumentation:
@Entity
public class Item {
@Lob
protected java.sql.Blob imageBlob;
@Lob
protected java.sql.Clob description;
// ...
}
5.自定义类型
@Entity
public class Item {
@org.hibernate.annotations.Type(type = "yes_no")
protected boolean verified = false;
}
或
metaBuilder.applyBasicType(new MyUserType(), new String[]{"date"});
二、代码
package org.jpwh.model.advanced; import org.jpwh.model.Constants; import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.sql.Blob;
import java.util.Date; @Entity
public class Item { /*
The <code>Item</code> entity defaults to field access, the <code>@Id</code> is on a field. (We
have also moved the brittle <code>ID_GENERATOR</code> string into a constant.)
*/
@Id
@GeneratedValue(generator = Constants.ID_GENERATOR)
protected Long id; @org.hibernate.annotations.Type(type = "yes_no")
protected boolean verified = false; // JPA says @Temporal is required but Hibernate will default to TIMESTAMP without it
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
@org.hibernate.annotations.CreationTimestamp
protected Date createdOn; // Java 8 API
// protected Instant reviewedOn; @NotNull
@Basic(fetch = FetchType.LAZY) // Defaults to EAGER
protected String description; @Basic(fetch = FetchType.LAZY)
@Column(length = 131072) // 128 kilobyte maximum for the picture
protected byte[] image; // Maps to SQL VARBINARY type @Lob
protected Blob imageBlob; @NotNull
@Enumerated(EnumType.STRING) // Defaults to ORDINAL
protected AuctionType auctionType = AuctionType.HIGHEST_BID; @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; @Column(name = "IMPERIALWEIGHT")
@org.hibernate.annotations.ColumnTransformer(
read = "IMPERIALWEIGHT / 2.20462",
write = "? * 2.20462"
)
protected double metricWeight; @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; /*
The <code>@Access(AccessType.PROPERTY)</code> setting on the <code>name</code> field switches this
particular property to runtime access through getter/setter methods by the JPA provider.
*/
@Access(AccessType.PROPERTY)
@Column(name = "ITEM_NAME") // Mappings are still expected here!
protected String name; /*
Hibernate will call <code>getName()</code> and <code>setName()</code> when loading and storing items.
*/
public String getName() {
return name;
} public void setName(String name) {
this.name =
!name.startsWith("AUCTION: ") ? "AUCTION: " + name : name;
} public Long getId() { // Optional but useful
return id;
} public String getDescription() {
return description;
} public void setDescription(String description) {
this.description = description;
} public String getShortDescription() {
return shortDescription;
} public BigDecimal getAverageBidAmount() {
return averageBidAmount;
} public double getMetricWeight() {
return metricWeight;
} public void setMetricWeight(double metricWeight) {
this.metricWeight = metricWeight;
} public Date getLastModified() {
return lastModified;
} public BigDecimal getInitialPrice() {
return initialPrice;
} public Date getCreatedOn() {
return createdOn;
} public boolean isVerified() {
return verified;
} public void setVerified(boolean verified) {
this.verified = verified;
} public byte[] getImage() {
return image;
} public void setImage(byte[] image) {
this.image = image;
} public Blob getImageBlob() {
return imageBlob;
} public void setImageBlob(Blob imageBlob) {
this.imageBlob = imageBlob;
} public AuctionType getAuctionType() {
return auctionType;
} public void setAuctionType(AuctionType auctionType) {
this.auctionType = auctionType;
}
}
三、测试代码
package org.jpwh.test.advanced; import org.hibernate.Session;
import org.hibernate.engine.jdbc.StreamUtils;
import org.jpwh.env.JPATest;
import org.jpwh.model.advanced.Item;
import org.testng.annotations.Test; import javax.persistence.EntityManager;
import javax.transaction.UserTransaction;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.util.Random; import static org.testng.Assert.assertEquals; public class LazyProperties extends JPATest { @Override
public void configurePersistenceUnit() throws Exception {
configurePersistenceUnit("AdvancedPU");
} @Test
public void storeLoadProperties() throws Exception {
UserTransaction tx = TM.getUserTransaction();
try {
tx.begin();
EntityManager em = JPA.createEntityManager();
Item someItem = new Item();
someItem.setName("Some item");
someItem.setDescription("This is some description.");
byte[] bytes = new byte[131072];
new Random().nextBytes(bytes);
someItem.setImage(bytes);
em.persist(someItem);
tx.commit();
em.close();
Long ITEM_ID = someItem.getId(); tx.begin();
em = JPA.createEntityManager(); Item item = em.find(Item.class, ITEM_ID); // Accessing one initializes ALL lazy properties in a single SELECT
assertEquals(item.getDescription(), "This is some description.");
assertEquals(item.getImage().length, 131072); // 128 kilobytes tx.commit();
em.close();
} finally {
TM.rollback();
}
} @Test
public void storeLoadLocator() throws Exception {
// TODO: This test fails on H2 standalone
// http://groups.google.com/group/h2-database/browse_thread/thread/9c6f4893a62c9b1a
UserTransaction tx = TM.getUserTransaction();
try {
tx.begin();
EntityManager em = JPA.createEntityManager(); byte[] bytes = new byte[131072];
new Random().nextBytes(bytes);
InputStream imageInputStream = new ByteArrayInputStream(bytes);
int byteLength = bytes.length; Item someItem = new Item();
someItem.setName("Some item");
someItem.setDescription("This is some description."); // Need the native Hibernate API
Session session = em.unwrap(Session.class);
// You need to know the number of bytes you want to read from the stream!
Blob blob = session.getLobHelper()
.createBlob(imageInputStream, byteLength); someItem.setImageBlob(blob);
em.persist(someItem); tx.commit();
em.close(); Long ITEM_ID = someItem.getId(); tx.begin();
em = JPA.createEntityManager(); Item item = em.find(Item.class, ITEM_ID); // You can stream the bytes directly...
InputStream imageDataStream = item.getImageBlob().getBinaryStream(); // ... or materialize them into memory:
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
StreamUtils.copy(imageDataStream, outStream);
byte[] imageBytes = outStream.toByteArray();
assertEquals(imageBytes.length, 131072); tx.commit();
em.close();
} finally {
TM.rollback();
}
} }
<persistence-unit name="AdvancedPU">
<jta-data-source>myDS</jta-data-source>
<class>org.jpwh.model</class>
<class>org.jpwh.model.advanced.Item</class>
<class>org.jpwh.model.advanced.Bid</class>
<class>org.jpwh.model.advanced.User</class>
<class>org.jpwh.model.advanced.Address</class>
<class>org.jpwh.model.advanced.City</class>
<class>org.jpwh.model.advanced.ItemBidSummary</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<!--
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
-->
</persistence-unit>
JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-005控制类型映射(Nationalized、@LOB、@org.hibernate.annotations.Type)的更多相关文章
- 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-001Mapping basic properties(@Basic、@Access、access="noop"、@Formula、@ColumnTransformer、@Generated、 @ColumnDefaul、@Temporal、@Enumerated)
一.简介 在JPA中,默认所有属性都会persist,属性要属于以下3种情况,Hibernate在启动时会报错 1.java基本类型或包装类 2.有注解 @Embedded 3.有实现java.io. ...
- 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-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-006Mixing inheritance strategies(@SecondaryTable、@PrimaryKeyJoinColumn、<join fetch="select">)
一.结构 For example, you can map a class hierarchy to a single table, but, for a particular subclass, s ...
随机推荐
- 利用python scrapy 框架抓取豆瓣小组数据
因为最近在找房子在豆瓣小组-上海租房上找,发现搜索困难,于是想利用爬虫将数据抓取. 顺便熟悉一下Python. 这边有scrapy 入门教程出处:http://www.cnblogs.com/txw1 ...
- [磁盘管理与分区]——MBR破坏与修复
GURB的破坏和恢复(利用备份体恢复) (1)备份 # count= //对MBR中的引导程序部分作备份 (2)破坏MBR中的前446字节 # count= (3)恢复MBR中前446字节 ===&g ...
- N!大整数阶乘问题
问题:求N!阶乘,1<=N<10000 思路:windows下面visual 6.0中c一个整型占4个字节(自己可以try一下,printf("%d", sizeof( ...
- json序列指定名称
class jsonModel{ public string md5 { get; set; } public object report { get; set; } public string @v ...
- 浅谈IT
在没有学计算机应用技术之前我对IT的认知度几乎为零,曾经还天真的认为IT就是白领,只要做上IT行业,以后便可高枕无忧.后来阴差阳错学了这个专业.通过一年的学习,虽然学艺不精但多少对IT行业了解的一知半 ...
- 《我是IT一只小小鸟》读后感
<我是IT一只小小鸟>读后感 首先,非常感谢我的老师给我推荐了这么一本书,虽然刚开始因为这门课学分太低,所以我对老师布置了字数这么多的作业存在有很大的不满,但在看了这本书后我的不满立马得到 ...
- hibernate---table_Generator
首先讲一下调试技巧:: @javax.persistence.TableGenerator( name="Teacher_GEN", table="GENERATOR_T ...
- 在listener或者工具中使用spring容器中的bean实例
在项目中经常遇见需要在Listener中或者工具中使用Spring容器中的bean实例,由于bean不能在stataic的类中使用. 介绍一种方式: public class SpringTool { ...
- share干什么的
share到底干什么的 //--------------------打开GameServer,share中加载------------------------- .加载nBodyID //玩家的nBo ...
- [百度空间] [note] pointer to member is a POD type
C++03 3.9-10: 1 Arithmetic types (3.9.1), enumeration types, pointer types, and pointer to member ty ...