Welcome

首页 / 软件开发 / Flex / 基于flex4技术从零开发flex博客系统:7 Using JPA

基于flex4技术从零开发flex博客系统:7 Using JPA2010-04-20 cnblogs sbanApp engine java在数据存储方面不仅支持JDO,还支持JPA。第4,5课我们存储数据使用的是JDO,这一课看一下如果使用JPA。

一,Using JPA

打开gapp_flexblog项目,在src/META-INF/目录下,添加persistence.xml文件,内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="transactions-optional">
<provider>org.datanucleus.store.appengine.jpa.DatastorePersistenceProvider</provider>
<properties>
<property name="datanucleus.NontransactionalRead" value="true"/>
<property name="datanucleus.NontransactionalWrite" value="true"/>
<property name="datanucleus.ConnectionURL" value="appengine"/>
</properties>
</persistence-unit>
</persistence>

其中persistence-unit的name在实例化EntityManagerFactory时会用到。

在sban.flexblog.managers目录下,添加类EMFactory:

package sban.flexblog.managers;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public final class EMFactory {
private static EntityManagerFactory _instance = Persistence
.createEntityManagerFactory("transactions-optional");

private EMFactory() {
}

public static EntityManagerFactory getInstance() {
return _instance;
}

}

该类用于返回EntityManagerFactory一个实例,其中参数”transactions-optional”为上文中定义。

在sban.flexblog目录下添加实体类GreetingEntity:

package sban.flexblog;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class GreetingEntity {

public GreetingEntity(String user, String content, Date date)
{
this.user = user;
this.greetingContent=content;
this.date = date;
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String user;

private String greetingContent;

private Date date;

public Long getId()
{
return this.id;
}

public String getGreetingContent()
{
return this.greetingContent;
}

public void setGreetingContent(String v)
{
this.greetingContent = v;
}

public Date getDate()
{
return this.date;
}
}