一、简介

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. OC中成员变量的命名

    先前写C++ 的时候,命名成员变量一般都是用 m_veriableName:的方式,但是进到新项目组,用了OC以后,发现成员变量都是用 veriableName_的方式,最后的一个下划线表示是成员变量 ...

  2. 浅谈ERP系统实施后如何完善企业内部控制制度建设

    ERP与企业内部控制制度,前者提升企业的管理水平,后者为企业发展保驾护航,两项工作都是企业各项工作的重中之重. ERP是企业资源规划Enterprise Resource Planning的缩写.企业 ...

  3. 【Search for a Range】cpp

    题目: Given a sorted array of integers, find the starting and ending position of a given target value. ...

  4. django Forgienkey字段 在前台用js做处理

    在我做的项目中有个选择省城市的选项,这两个字段的关系是一对多的关系class Province(models.Model): # 省会      name = models.CharField(max ...

  5. windows环境下svn同步web文件[转]

    windows环境下svn同步web文件 SVN在团队开发中使用非常普遍,是一个很方便的版本控制系统. 如果要是能将SVN服务器上的数据自动发布到Web服务器,那将是整个项目开发.测试更加便捷.利用S ...

  6. [百度空间] [原]MFC杂乱笔记

    1. 创建动态菜单 假如ID是动态分配的,那么重载virtual BOOLOnCmdMsg(UINT,int,void*,AFX_CMDHANDLERINFO*); 据MSDN不详细解释,当第二个参数 ...

  7. css之margin && padding讲解

    margin && padding盒子模型: margin是模块与模块的空隙,padding是内容与边框的空隙 注: 1.margin:边缘.空白 2.padding:填充 margi ...

  8. UML对象图(转载)

    概述: 对象图都来源于类图,依赖类图对象图. 对象图表示一个类图的一个实例.类图和对象图的基本概念是相似的.对象图也代表了一个系统的静态视图,但这种静态视图是系统在某一时刻的一个快照. 对象图是用于呈 ...

  9. Java读取图片并修改像素,创建图片

    public void replaceImageColor(String file, Color srcColor, Color targetColor) throws IOException{ UR ...

  10. 理解 Memory barrier

    理解 Memory barrier(内存屏障) 发布于 2014 年 04 月 21 日2014 年 05 月 15 日 作者 name5566 参考文献列表:http://en.wikipedia. ...