Google App Engine for Java,第 3 部分: 持久性和关系
2009-09-17 00:00:00 来源:WEB开发网现在,使用与 Google App Engine 数据存储交互的应用程序替换模拟实现,看看会发生什么。在这个示例中,您将使用 JDO 持久化 Contact
类。使用 Google Eclipse Plugin 编写的应用程序已经拥有了使用 JDO 所需的所有库。它还包含了一个 jdoconfig.xml 文件,因此,一旦对 Contact
类进行了注释,您就已经准备好开始使用 JDO。
清单 3 显示扩展后的 ContactDAO
接口,可使用 JDO API 进行持久化、查询、更新和删除对象:
清单 3. 使用 JDO 的 ContactDAO
package gaej.example.contact.server;
import gaej.example.contact.client.Contact;
import java.util.List;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
public class ContactJdoDAO implements ContactDAO {
private static final PersistenceManagerFactory pmfInstance = JDOHelper
.getPersistenceManagerFactory("transactions-optional");
public static PersistenceManagerFactory getPersistenceManagerFactory() {
return pmfInstance;
}
public void addContact(Contact contact) {
PersistenceManager pm = getPersistenceManagerFactory()
.getPersistenceManager();
try {
pm.makePersistent(contact);
} finally {
pm.close();
}
}
@SuppressWarnings("unchecked")
public List<Contact> listContacts() {
PersistenceManager pm = getPersistenceManagerFactory()
.getPersistenceManager();
String query = "select from " + Contact.class.getName();
return (List<Contact>) pm.newQuery(query).execute();
}
public void removeContact(Contact contact) {
PersistenceManager pm = getPersistenceManagerFactory()
.getPersistenceManager();
try {
pm.currentTransaction().begin();
// We don't have a reference to the selected Product.
// So we have to look it up first,
contact = pm.getObjectById(Contact.class, contact.getId());
pm.deletePersistent(contact);
pm.currentTransaction().commit();
} catch (Exception ex) {
pm.currentTransaction().rollback();
throw new RuntimeException(ex);
} finally {
pm.close();
}
}
public void updateContact(Contact contact) {
PersistenceManager pm = getPersistenceManagerFactory()
.getPersistenceManager();
String name = contact.getName();
String phone = contact.getPhone();
String email = contact.getEmail();
try {
pm.currentTransaction().begin();
// We don't have a reference to the selected Product.
// So we have to look it up first,
contact = pm.getObjectById(Contact.class, contact.getId());
contact.setName(name);
contact.setPhone(phone);
contact.setEmail(email);
pm.makePersistent(contact);
pm.currentTransaction().commit();
} catch (Exception ex) {
pm.currentTransaction().rollback();
throw new RuntimeException(ex);
} finally {
pm.close();
}
}
}
- ››Google搜索引擎的奥秘
- ››Google测试搜索结果页面右侧内容更丰富的信息栏
- ››Google Dart精粹:应用构建,快照和隔离体
- ››APP Loading页设计和App从当前页进入新页面交互
- ››App产品开发:App产品开发与推广的经验
- ››google的代码审查
- ››google analytics清晰追踪爬虫的爬行信息
- ››Google+中文用户在两千万Google+大军中是少数派
- ››Google AdWords最昂贵点击成本的20种关键词分类
- ››Google运作经理Bryan Power给出的GOOGLE求职意见
- ››Google用户体验的十大设计原则
- ››Applying Styles and Themes - 应用Style和Theme ...
更多精彩
赞助商链接