一、简介

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)的更多相关文章

  1. 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 ...

  2. 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. ...

  3. 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 ...

  4. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-004嵌套组件的注解AttributeOverrides

    一.数据库 二.代码 1. package org.jpwh.model.advanced; import javax.persistence.AttributeOverride; import ja ...

  5. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-003使用@AttributeOverrides

    Each @AttributeOverride for a component property is “complete”: any JPA or Hibernate annotation on t ...

  6. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-002使用@Embeddable

    一.数据库 二.代码 1. package org.jpwh.model.simple; import javax.persistence.Column; import javax.persisten ...

  7. JavaPersistenceWithHibernate第二版笔记-第四章-Mapping persistent classes-003映射实体时的可选操作(<delimited-identifiers/>、PhysicalNamingStrategy、PhysicalNamingStrategyStandardImpl、、、)

    一.自定义映射的表名 1. @Entity @Table(name = "USERS") public class User implements Serializable { / ...

  8. 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 ...

  9. 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 ...

随机推荐

  1. php对象

    在php中,必须使用class关键字明确的声明对象,然后在对象类中定义数据类型和方法. 示例: class Color{ public $value; public static $RED = &qu ...

  2. VS 与 SQLite数据库 连接

    SQLite并没有一次性做到位,只有下载这些东西是不能放在vs2010中并马上使用的,下载下来的文件中有sqlite3.c/h/dll/def,还是不够用的.我们需要的sqlite3.lib文件并不在 ...

  3. 【AFNetworking】AFNetworking源码阅读(一)

    1. 前言 2. iOS Example代码结构 3.AFNetworkActivityIndicatorManager 4. UIRefreshControl+AFNetworking 5. AFN ...

  4. 关于spring mvc MaxUploadSizeExceededException 死循环解决方案

    当看到这文章的时候相信你现在应该遇到这样的问题了,我也是自己遇到了后来找到解决方案了记录下来,如果下次遇到就可以直接解决了. 至于为什么会出现这样的情况,可以看这篇文章:https://bz.apac ...

  5. The underlying JVM is how to realize the synchronized

    http://www.programering.com/a/MjN0IjMwATg.html

  6. 《我是IT小小鸟》读书笔记

    转眼间,大学的第二学期悄悄来临了,老师给我们布置了一道原本我以为很无趣的题目----写<我是IT的读书笔记>,但是我读了<我是IT小小鸟>这本书后,令我受益匪浅:五个人,每个人 ...

  7. UVALive - 7374 Racing Gems 二维非递减子序列

    题目链接: http://acm.hust.edu.cn/vjudge/problem/356795 Racing Gems Time Limit: 3000MS 问题描述 You are playi ...

  8. IIS8托管WCF服务

    WCF服务程序本身不能运行,需要通过其他的宿主程序进行托管才能调用WCF服务功能,常见的宿主程序有IIS,WAS,Windows服务,当然在学习WCF技术的时候一般使用控制台应用程序或WinForm程 ...

  9. 如何混合使用ARC和非ARC

    如果你的项目使用的非ARC模式,则为ARC模式的代码文件加入-fobjc-arc标签.如果你的项目使用的ARC模式,则为非ARC模式的代码文件加入 -fno-objc-arc标签.添加标签的方法: 1 ...

  10. StoreKit framework

    关于In-APP Purchase 1. 中文文档 基本流程: http://www.cnblogs.com/wudan7/p/3621763.html 三种购买形式及StoreKit code介绍: ...