Guide to JDO (#1730)

* Guide to JDO

* Guide to JDO

* Guide to JDO
This commit is contained in:
Jesus Boadas
2017-04-25 14:54:32 -04:00
committed by maibin
parent 129c751cb4
commit b0e15fcca0
8 changed files with 323 additions and 21 deletions
@@ -0,0 +1,83 @@
package com.baeldung.jdo;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;
public class GuideToJDO {
private static final Logger LOGGER = Logger.getLogger(GuideToJDO.class.getName());
private Random rnd = new Random();
public static void main(String[] args) {
new GuideToJDO();
}
public GuideToJDO() {
CreateProducts();
ListProducts();
}
public void CreateProducts() {
PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("Tutorial");
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
try {
tx.begin();
Product product = new Product("Tablet", 80.0);
pm.makePersistent(product);
Product product2 = new Product("Phone", 20.0);
pm.makePersistent(product2);
Product product3 = new Product("Laptop", 200.0);
pm.makePersistent(product3);
for (int i = 0; i < 100; i++) {
String nam = "Product-" + i;
double price = rnd.nextDouble();
Product productx = new Product(nam, price);
pm.makePersistent(productx);
}
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
pm.close();
}
}
@SuppressWarnings("unchecked")
public void ListProducts() {
PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("Tutorial");
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
try {
tx.begin();
@SuppressWarnings("rawtypes")
Query q = pm.newQuery("SELECT FROM " + Product.class.getName() + " WHERE price < 1");
List<Product> products = (List<Product>) q.execute();
Iterator<Product> iter = products.iterator();
while (iter.hasNext()) {
Product p = iter.next();
LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
}
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
pm.close();
}
}
}
@@ -0,0 +1,43 @@
package com.baeldung.jdo;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
@PersistenceCapable
public class Product {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT)
long id;
String name = null;
Double price = 0.0;
public Product() {
this.name = null;
this.price = 0.0;
}
public Product(String name, Double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}