BAEL-1734 move packages from libraries to libraries-data
This commit is contained in:
@@ -3,3 +3,7 @@
|
||||
- [Introduction to ORMLite](http://www.baeldung.com/ormlite)
|
||||
- [Introduction To Kryo](http://www.baeldung.com/kryo)
|
||||
- [Introduction to KafkaStreams in Java](http://www.baeldung.com/java-kafka-streams)
|
||||
- [Guide to Java Data Objects](http://www.baeldung.com/jdo)
|
||||
- [Intro to JDO Queries 2/2](http://www.baeldung.com/jdo-queries)
|
||||
- [Introduction to HikariCP](http://www.baeldung.com/hikaricp)
|
||||
- [Introduction to JCache](http://www.baeldung.com/jcache)
|
||||
|
||||
1
libraries-data/log4j.properties
Normal file
1
libraries-data/log4j.properties
Normal file
@@ -0,0 +1 @@
|
||||
log4j.rootLogger=INFO, stdout
|
||||
26
libraries-data/myPersistence.xml
Normal file
26
libraries-data/myPersistence.xml
Normal file
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?><root>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
</root>
|
||||
@@ -85,6 +85,55 @@
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
<!-- Hikari CP -->
|
||||
<dependency>
|
||||
<groupId>com.zaxxer</groupId>
|
||||
<artifactId>HikariCP</artifactId>
|
||||
<version>2.7.2</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<!-- JDO -->
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>javax.jdo</artifactId>
|
||||
<version>3.2.0-m7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>datanucleus-core</artifactId>
|
||||
<version>5.1.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>datanucleus-api-jdo</artifactId>
|
||||
<version>5.1.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>datanucleus-rdbms</artifactId>
|
||||
<version>5.1.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>datanucleus-maven-plugin</artifactId>
|
||||
<version>5.0.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>datanucleus-xml</artifactId>
|
||||
<version>5.0.0-release</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>datanucleus-jdo-query</artifactId>
|
||||
<version>5.0.4</version>
|
||||
</dependency>
|
||||
<!-- Jcache -->
|
||||
<dependency>
|
||||
<groupId>javax.cache</groupId>
|
||||
<artifactId>cache-api</artifactId>
|
||||
<version>${cache.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -184,6 +233,29 @@
|
||||
</plugin>
|
||||
<!-- /Reladomo-->
|
||||
|
||||
<!-- JDO Plugin -->
|
||||
<plugin>
|
||||
<groupId>org.datanucleus</groupId>
|
||||
<artifactId>datanucleus-maven-plugin</artifactId>
|
||||
<version>5.0.2</version>
|
||||
<configuration>
|
||||
<api>JDO</api>
|
||||
<props>${basedir}/datanucleus.properties</props>
|
||||
<log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration>
|
||||
<verbose>true</verbose>
|
||||
<fork>false</fork>
|
||||
<!-- Solve windows line too long error -->
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>process-classes</phase>
|
||||
<goals>
|
||||
<goal>enhance</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
@@ -203,5 +275,6 @@
|
||||
<kafka.version>1.0.0</kafka.version>
|
||||
<ignite.version>2.3.0</ignite.version>
|
||||
<gson.version>2.8.2</gson.version>
|
||||
<cache.version>1.0.0</cache.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.hikaricp;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
|
||||
public class DataSource {
|
||||
|
||||
private static HikariConfig config = new HikariConfig();
|
||||
private static HikariDataSource ds;
|
||||
|
||||
static {
|
||||
// config = new HikariConfig("datasource.properties");
|
||||
|
||||
// Properties props = new Properties();
|
||||
// props.setProperty("dataSourceClassName", "org.h2.Driver");
|
||||
// props.setProperty("dataSource.user", "");
|
||||
// props.setProperty("dataSource.password", "");
|
||||
// props.put("dataSource.logWriter", new PrintWriter(System.out));
|
||||
// config = new HikariConfig(props);
|
||||
|
||||
config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'");
|
||||
config.setUsername("");
|
||||
config.setPassword("");
|
||||
config.addDataSourceProperty("cachePrepStmts", "true");
|
||||
config.addDataSourceProperty("prepStmtCacheSize", "250");
|
||||
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
|
||||
ds = new HikariDataSource(config);
|
||||
|
||||
// ds.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'");
|
||||
// ds.setUsername("");
|
||||
// ds.setPassword("");
|
||||
}
|
||||
|
||||
private DataSource() {
|
||||
}
|
||||
|
||||
public static Connection getConnection() throws SQLException {
|
||||
return ds.getConnection();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.hikaricp;
|
||||
|
||||
import java.sql.Date;
|
||||
|
||||
public class Employee {
|
||||
|
||||
private int empNo;
|
||||
private String ename;
|
||||
private String job;
|
||||
private int mgr;
|
||||
private Date hiredate;
|
||||
private int sal;
|
||||
private int comm;
|
||||
private int deptno;
|
||||
|
||||
public int getEmpNo() {
|
||||
return empNo;
|
||||
}
|
||||
|
||||
public void setEmpNo(int empNo) {
|
||||
this.empNo = empNo;
|
||||
}
|
||||
|
||||
public String getEname() {
|
||||
return ename;
|
||||
}
|
||||
|
||||
public void setEname(String ename) {
|
||||
this.ename = ename;
|
||||
}
|
||||
|
||||
public String getJob() {
|
||||
return job;
|
||||
}
|
||||
|
||||
public void setJob(String job) {
|
||||
this.job = job;
|
||||
}
|
||||
|
||||
public int getMgr() {
|
||||
return mgr;
|
||||
}
|
||||
|
||||
public void setMgr(int mgr) {
|
||||
this.mgr = mgr;
|
||||
}
|
||||
|
||||
public Date getHiredate() {
|
||||
return hiredate;
|
||||
}
|
||||
|
||||
public void setHiredate(Date hiredate) {
|
||||
this.hiredate = hiredate;
|
||||
}
|
||||
|
||||
public int getSal() {
|
||||
return sal;
|
||||
}
|
||||
|
||||
public void setSal(int sal) {
|
||||
this.sal = sal;
|
||||
}
|
||||
|
||||
public int getComm() {
|
||||
return comm;
|
||||
}
|
||||
|
||||
public void setComm(int comm) {
|
||||
this.comm = comm;
|
||||
}
|
||||
|
||||
public int getDeptno() {
|
||||
return deptno;
|
||||
}
|
||||
|
||||
public void setDeptno(int deptno) {
|
||||
this.deptno = deptno;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("Employee [empNo=%d, ename=%s, job=%s, mgr=%d, hiredate=%s, sal=%d, comm=%d, deptno=%d]", empNo, ename, job, mgr, hiredate, sal, comm, deptno);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.hikaricp;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class HikariCPDemo {
|
||||
|
||||
public static List<Employee> fetchData() {
|
||||
final String SQL_QUERY = "select * from emp";
|
||||
List<Employee> employees = null;
|
||||
try (Connection con = DataSource.getConnection(); PreparedStatement pst = con.prepareStatement(SQL_QUERY); ResultSet rs = pst.executeQuery();) {
|
||||
employees = new ArrayList<Employee>();
|
||||
Employee employee;
|
||||
while (rs.next()) {
|
||||
employee = new Employee();
|
||||
employee.setEmpNo(rs.getInt("empno"));
|
||||
employee.setEname(rs.getString("ename"));
|
||||
employee.setJob(rs.getString("job"));
|
||||
employee.setMgr(rs.getInt("mgr"));
|
||||
employee.setHiredate(rs.getDate("hiredate"));
|
||||
employee.setSal(rs.getInt("sal"));
|
||||
employee.setComm(rs.getInt("comm"));
|
||||
employee.setDeptno(rs.getInt("deptno"));
|
||||
employees.add(employee);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return employees;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
fetchData();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.jcache;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.cache.event.CacheEntryCreatedListener;
|
||||
import javax.cache.event.CacheEntryEvent;
|
||||
import javax.cache.event.CacheEntryListenerException;
|
||||
import javax.cache.event.CacheEntryUpdatedListener;
|
||||
|
||||
public class SimpleCacheEntryListener implements CacheEntryCreatedListener<String, String>, CacheEntryUpdatedListener<String, String>, Serializable {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = -712657810462878763L;
|
||||
private boolean updated;
|
||||
private boolean created;
|
||||
|
||||
public boolean getUpdated() {
|
||||
return this.updated;
|
||||
}
|
||||
|
||||
public boolean getCreated() {
|
||||
return this.created;
|
||||
}
|
||||
|
||||
public void onUpdated(Iterable<CacheEntryEvent<? extends String, ? extends String>> events) throws CacheEntryListenerException {
|
||||
this.updated = true;
|
||||
}
|
||||
|
||||
public void onCreated(Iterable<CacheEntryEvent<? extends String, ? extends String>> events) throws CacheEntryListenerException {
|
||||
this.created = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.jcache;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.cache.integration.CacheLoader;
|
||||
import javax.cache.integration.CacheLoaderException;
|
||||
|
||||
public class SimpleCacheLoader implements CacheLoader<Integer, String> {
|
||||
|
||||
@Override
|
||||
public String load(Integer key) throws CacheLoaderException {
|
||||
return "fromCache" + key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Integer, String> loadAll(Iterable<? extends Integer> keys) throws CacheLoaderException {
|
||||
Map<Integer, String> data = new HashMap<>();
|
||||
for (int key : keys) {
|
||||
data.put(key, load(key));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.jcache;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.cache.processor.EntryProcessor;
|
||||
import javax.cache.processor.EntryProcessorException;
|
||||
import javax.cache.processor.MutableEntry;
|
||||
|
||||
public class SimpleEntryProcessor implements EntryProcessor<String, String, String>, Serializable {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = -5616476363722945132L;
|
||||
|
||||
public String process(MutableEntry<String, String> entry, Object... args) throws EntryProcessorException {
|
||||
|
||||
if (entry.exists()) {
|
||||
String current = entry.getValue();
|
||||
entry.setValue(current + " - modified");
|
||||
return current;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
299
libraries-data/src/main/java/com/baeldung/jdo/GuideToJDO.java
Normal file
299
libraries-data/src/main/java/com/baeldung/jdo/GuideToJDO.java
Normal file
@@ -0,0 +1,299 @@
|
||||
package com.baeldung.jdo;
|
||||
|
||||
import java.util.Collection;
|
||||
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.PersistenceManager;
|
||||
import javax.jdo.PersistenceManagerFactory;
|
||||
import javax.jdo.Query;
|
||||
import javax.jdo.Transaction;
|
||||
|
||||
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
|
||||
import org.datanucleus.metadata.PersistenceUnitMetaData;
|
||||
|
||||
public class GuideToJDO {
|
||||
|
||||
private static final Logger LOGGER = Logger.getLogger(GuideToJDO.class.getName());
|
||||
private Random rnd = new Random();
|
||||
private PersistenceUnitMetaData pumd;
|
||||
private PersistenceUnitMetaData pumdXML;
|
||||
|
||||
public static void main(String[] args) {
|
||||
new GuideToJDO();
|
||||
}
|
||||
|
||||
public GuideToJDO() {
|
||||
CreateH2Properties();
|
||||
CreateXMLProperties();
|
||||
CreateProducts();
|
||||
ListProducts();
|
||||
QueryJDOQL();
|
||||
QuerySQL();
|
||||
QueryJPQL();
|
||||
UpdateProducts();
|
||||
ListProducts();
|
||||
DeleteProducts();
|
||||
ListProducts();
|
||||
persistXML();
|
||||
listXMLProducts();
|
||||
}
|
||||
|
||||
public void CreateH2Properties() {
|
||||
|
||||
pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
|
||||
pumd.addClassName("com.baeldung.jdo.Product");
|
||||
pumd.setExcludeUnlistedClasses();
|
||||
pumd.addProperty("javax.jdo.option.ConnectionDriverName", "org.h2.Driver");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionPassword", "");
|
||||
pumd.addProperty("datanucleus.autoCreateSchema", "true");
|
||||
|
||||
}
|
||||
|
||||
public void CreateXMLProperties() {
|
||||
pumdXML = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
|
||||
pumdXML.addClassName("com.baeldung.jdo.ProductXML");
|
||||
pumdXML.setExcludeUnlistedClasses();
|
||||
pumdXML.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myPersistence.xml");
|
||||
pumdXML.addProperty("datanucleus.autoCreateSchema", "true");
|
||||
}
|
||||
|
||||
public void CreateProducts() {
|
||||
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
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("rawtypes")
|
||||
public void UpdateProducts() {
|
||||
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
PersistenceManager pm = pmf.getPersistenceManager();
|
||||
Transaction tx = pm.currentTransaction();
|
||||
try {
|
||||
tx.begin();
|
||||
Query query = pm.newQuery(Product.class, "name == \"Phone\"");
|
||||
Collection result = (Collection) query.execute();
|
||||
Product product = (Product) result.iterator().next();
|
||||
product.setName("Android Phone");
|
||||
tx.commit();
|
||||
} finally {
|
||||
if (tx.isActive()) {
|
||||
tx.rollback();
|
||||
}
|
||||
pm.close();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void DeleteProducts() {
|
||||
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
PersistenceManager pm = pmf.getPersistenceManager();
|
||||
Transaction tx = pm.currentTransaction();
|
||||
try {
|
||||
tx.begin();
|
||||
Query query = pm.newQuery(Product.class, "name == \"Android Phone\"");
|
||||
Collection result = (Collection) query.execute();
|
||||
Product product = (Product) result.iterator().next();
|
||||
pm.deletePersistent(product);
|
||||
tx.commit();
|
||||
} finally {
|
||||
if (tx.isActive()) {
|
||||
tx.rollback();
|
||||
}
|
||||
pm.close();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public void ListProducts() {
|
||||
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
PersistenceManager pm = pmf.getPersistenceManager();
|
||||
Transaction tx = pm.currentTransaction();
|
||||
try {
|
||||
tx.begin();
|
||||
|
||||
Query q = pm.newQuery("SELECT FROM " + Product.class.getName() + " WHERE price > 10");
|
||||
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 });
|
||||
}
|
||||
LOGGER.log(Level.INFO, "--------------------------------------------------------------");
|
||||
tx.commit();
|
||||
} finally {
|
||||
if (tx.isActive()) {
|
||||
tx.rollback();
|
||||
}
|
||||
|
||||
pm.close();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public void QueryJDOQL() {
|
||||
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
PersistenceManager pm = pmf.getPersistenceManager();
|
||||
Transaction tx = pm.currentTransaction();
|
||||
try {
|
||||
tx.begin();
|
||||
|
||||
// Declarative JDOQL :
|
||||
LOGGER.log(Level.INFO, "Declarative JDOQL --------------------------------------------------------------");
|
||||
Query qDJDOQL = pm.newQuery(Product.class);
|
||||
qDJDOQL.setFilter("name == 'Tablet' && price == price_value");
|
||||
qDJDOQL.declareParameters("double price_value");
|
||||
List<Product> resultsqDJDOQL = qDJDOQL.setParameters(80.0).executeList();
|
||||
|
||||
Iterator<Product> iterDJDOQL = resultsqDJDOQL.iterator();
|
||||
while (iterDJDOQL.hasNext()) {
|
||||
Product p = iterDJDOQL.next();
|
||||
LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
|
||||
}
|
||||
LOGGER.log(Level.INFO, "--------------------------------------------------------------");
|
||||
|
||||
tx.commit();
|
||||
} finally {
|
||||
if (tx.isActive()) {
|
||||
tx.rollback();
|
||||
}
|
||||
|
||||
pm.close();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public void QuerySQL() {
|
||||
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
PersistenceManager pm = pmf.getPersistenceManager();
|
||||
Transaction tx = pm.currentTransaction();
|
||||
try {
|
||||
tx.begin();
|
||||
|
||||
// SQL :
|
||||
LOGGER.log(Level.INFO, "SQL --------------------------------------------------------------");
|
||||
Query query = pm.newQuery("javax.jdo.query.SQL", "SELECT * FROM PRODUCT");
|
||||
query.setClass(Product.class);
|
||||
List<Product> results = query.executeList();
|
||||
|
||||
Iterator<Product> iter = results.iterator();
|
||||
while (iter.hasNext()) {
|
||||
Product p = iter.next();
|
||||
LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
|
||||
}
|
||||
LOGGER.log(Level.INFO, "--------------------------------------------------------------");
|
||||
|
||||
tx.commit();
|
||||
} finally {
|
||||
if (tx.isActive()) {
|
||||
tx.rollback();
|
||||
}
|
||||
|
||||
pm.close();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public void QueryJPQL() {
|
||||
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
PersistenceManager pm = pmf.getPersistenceManager();
|
||||
Transaction tx = pm.currentTransaction();
|
||||
try {
|
||||
tx.begin();
|
||||
|
||||
// JPQL :
|
||||
LOGGER.log(Level.INFO, "JPQL --------------------------------------------------------------");
|
||||
Query q = pm.newQuery("JPQL", "SELECT p FROM " + Product.class.getName() + " p WHERE p.name = 'Laptop'");
|
||||
List results = (List) q.execute();
|
||||
|
||||
Iterator<Product> iter = results.iterator();
|
||||
while (iter.hasNext()) {
|
||||
Product p = iter.next();
|
||||
LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
|
||||
}
|
||||
LOGGER.log(Level.INFO, "--------------------------------------------------------------");
|
||||
|
||||
tx.commit();
|
||||
} finally {
|
||||
if (tx.isActive()) {
|
||||
tx.rollback();
|
||||
}
|
||||
|
||||
pm.close();
|
||||
}
|
||||
}
|
||||
|
||||
public void persistXML() {
|
||||
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null);
|
||||
PersistenceManager pm = pmf.getPersistenceManager();
|
||||
Transaction tx = pm.currentTransaction();
|
||||
try {
|
||||
tx.begin();
|
||||
ProductXML productXML = new ProductXML(0, "Tablet", 80.0);
|
||||
pm.makePersistent(productXML);
|
||||
ProductXML productXML2 = new ProductXML(1, "Phone", 20.0);
|
||||
pm.makePersistent(productXML2);
|
||||
ProductXML productXML3 = new ProductXML(2, "Laptop", 200.0);
|
||||
pm.makePersistent(productXML3);
|
||||
tx.commit();
|
||||
} finally {
|
||||
if (tx.isActive()) {
|
||||
tx.rollback();
|
||||
}
|
||||
pm.close();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public void listXMLProducts() {
|
||||
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null);
|
||||
PersistenceManager pm = pmf.getPersistenceManager();
|
||||
Transaction tx = pm.currentTransaction();
|
||||
try {
|
||||
tx.begin();
|
||||
|
||||
Query q = pm.newQuery("SELECT FROM " + ProductXML.class.getName());
|
||||
List<ProductXML> products = (List<ProductXML>) q.execute();
|
||||
Iterator<ProductXML> iter = products.iterator();
|
||||
while (iter.hasNext()) {
|
||||
ProductXML p = iter.next();
|
||||
LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.getName(), p.getPrice() });
|
||||
pm.deletePersistent(p);
|
||||
}
|
||||
LOGGER.log(Level.INFO, "--------------------------------------------------------------");
|
||||
tx.commit();
|
||||
} finally {
|
||||
if (tx.isActive()) {
|
||||
tx.rollback();
|
||||
}
|
||||
|
||||
pm.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
43
libraries-data/src/main/java/com/baeldung/jdo/Product.java
Normal file
43
libraries-data/src/main/java/com/baeldung/jdo/Product.java
Normal file
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.jdo;
|
||||
|
||||
import javax.jdo.annotations.PersistenceCapable;
|
||||
import javax.jdo.annotations.PrimaryKey;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
|
||||
@PersistenceCapable()
|
||||
public class ProductXML {
|
||||
|
||||
@XmlAttribute
|
||||
private long productNumber = 0;
|
||||
@PrimaryKey
|
||||
private String name = null;
|
||||
private Double price = 0.0;
|
||||
|
||||
public ProductXML() {
|
||||
this.productNumber = 0;
|
||||
this.name = null;
|
||||
this.price = 0.0;
|
||||
}
|
||||
|
||||
public ProductXML(long productNumber, String name, Double price) {
|
||||
this.productNumber = productNumber;
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.jdo.query;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.jdo.JDOQLTypedQuery;
|
||||
import javax.jdo.PersistenceManager;
|
||||
import javax.jdo.PersistenceManagerFactory;
|
||||
import javax.jdo.Query;
|
||||
|
||||
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
|
||||
import org.datanucleus.metadata.PersistenceUnitMetaData;
|
||||
|
||||
public class MyApp {
|
||||
|
||||
private static PersistenceManagerFactory pmf;
|
||||
private static PersistenceManager pm;
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
defineDynamicPersistentUnit();
|
||||
createTestData();
|
||||
queryUsingJDOQL();
|
||||
queryUsingTypedJDOQL();
|
||||
queryUsingSQL();
|
||||
queryUsingJPQL();
|
||||
|
||||
}
|
||||
|
||||
public static void createTestData() {
|
||||
ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut", 5);
|
||||
ProductItem item2 = new ProductItem("pro2", "price less than 10", "InStock", 8);
|
||||
ProductItem item3 = new ProductItem("pro3", "price more than 10", "SoldOut", 15);
|
||||
|
||||
if (pm != null) {
|
||||
pm.makePersistent(item1);
|
||||
pm.makePersistent(item2);
|
||||
pm.makePersistent(item3);
|
||||
}
|
||||
}
|
||||
|
||||
public static void defineDynamicPersistentUnit() {
|
||||
|
||||
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
|
||||
pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:mysql://localhost:3306/jdo_db");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionUserName", "root");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionPassword", "admin");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionDriverName", "com.mysql.jdbc.Driver");
|
||||
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");
|
||||
|
||||
pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
pm = pmf.getPersistenceManager();
|
||||
}
|
||||
|
||||
public static void queryUsingJDOQL() {
|
||||
|
||||
Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem " + "WHERE price < threshold PARAMETERS double threshold");
|
||||
List<ProductItem> explicitParamResults = (List<ProductItem>) query.execute(10);
|
||||
|
||||
query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
|
||||
query.setParameters("double threshold");
|
||||
List<ProductItem> explicitParamResults2 = (List<ProductItem>) query.execute(10);
|
||||
|
||||
query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
|
||||
List<ProductItem> implicitParamResults = (List<ProductItem>) query.execute(10);
|
||||
|
||||
}
|
||||
|
||||
public static void queryUsingTypedJDOQL() {
|
||||
JDOQLTypedQuery<ProductItem> tq = pm.newJDOQLTypedQuery(ProductItem.class);
|
||||
QProductItem cand = QProductItem.candidate();
|
||||
tq = tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro")));
|
||||
List<ProductItem> results = tq.executeList();
|
||||
|
||||
}
|
||||
|
||||
public static void queryUsingSQL() {
|
||||
|
||||
Query query = pm.newQuery("javax.jdo.query.SQL", "select * from " + "product_item where price < ? and status = ?");
|
||||
query.setClass(ProductItem.class);
|
||||
query.setParameters(10, "InStock");
|
||||
List<ProductItem> results = query.executeList();
|
||||
|
||||
}
|
||||
|
||||
public static void queryUsingJPQL() {
|
||||
Query query = pm.newQuery("JPQL", "select i from " + "com.baeldung.jdo.query.ProductItem i where i.price < 10" + " and i.status = 'InStock'");
|
||||
List<ProductItem> results = (List<ProductItem>) query.execute();
|
||||
|
||||
}
|
||||
|
||||
public static void namedQuery() {
|
||||
Query<ProductItem> query = pm.newNamedQuery(ProductItem.class, "PriceBelow10");
|
||||
List<ProductItem> results = query.executeList();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.jdo.query;
|
||||
|
||||
import javax.jdo.annotations.IdGeneratorStrategy;
|
||||
import javax.jdo.annotations.PersistenceCapable;
|
||||
import javax.jdo.annotations.Persistent;
|
||||
import javax.jdo.annotations.PrimaryKey;
|
||||
|
||||
@PersistenceCapable(table = "product_item")
|
||||
public class ProductItem {
|
||||
|
||||
@PrimaryKey
|
||||
@Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT)
|
||||
int id;
|
||||
String name;
|
||||
String description;
|
||||
String status;
|
||||
double price;
|
||||
|
||||
public ProductItem() {
|
||||
|
||||
}
|
||||
|
||||
public ProductItem(String name, String description, String status, double price) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.status = status;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.jdo.xml;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.jdo.annotations.Element;
|
||||
import javax.jdo.annotations.PersistenceCapable;
|
||||
import javax.jdo.annotations.PrimaryKey;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlElementWrapper;
|
||||
|
||||
@PersistenceCapable(schema = "/myproduct/people", table = "person")
|
||||
public class AnnotadedPerson {
|
||||
@XmlAttribute
|
||||
private long personNum;
|
||||
|
||||
@PrimaryKey
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
@XmlElementWrapper(name = "phone-numbers")
|
||||
@XmlElement(name = "phone-number")
|
||||
@Element(types = String.class)
|
||||
private List phoneNumbers = new ArrayList();
|
||||
|
||||
public AnnotadedPerson(long personNum, String firstName, String lastName) {
|
||||
super();
|
||||
this.personNum = personNum;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public long getPersonNum() {
|
||||
return personNum;
|
||||
}
|
||||
|
||||
public void setPersonNum(long personNum) {
|
||||
this.personNum = personNum;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public List getPhoneNumbers() {
|
||||
return phoneNumbers;
|
||||
}
|
||||
|
||||
public void setPhoneNumbers(List phoneNumbers) {
|
||||
this.phoneNumbers = phoneNumbers;
|
||||
}
|
||||
|
||||
}
|
||||
105
libraries-data/src/main/java/com/baeldung/jdo/xml/MyApp.java
Normal file
105
libraries-data/src/main/java/com/baeldung/jdo/xml/MyApp.java
Normal file
@@ -0,0 +1,105 @@
|
||||
package com.baeldung.jdo.xml;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.jdo.JDOHelper;
|
||||
import javax.jdo.PersistenceManager;
|
||||
import javax.jdo.PersistenceManagerFactory;
|
||||
import javax.jdo.Query;
|
||||
import javax.jdo.Transaction;
|
||||
|
||||
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
|
||||
import org.datanucleus.metadata.PersistenceUnitMetaData;
|
||||
|
||||
public class MyApp {
|
||||
|
||||
private static PersistenceUnitMetaData pumd;
|
||||
private static PersistenceManagerFactory pmf;
|
||||
private static PersistenceManager pm;
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// persist product object using dynamic persistence unit
|
||||
defineDynamicPersistentUnit();
|
||||
Product product = new Product("id1", "Sony Discman", "A standard discman from Sony", 49.99);
|
||||
persistObject(product);
|
||||
closePersistenceManager();
|
||||
|
||||
// persist AnnotatedPerson object using named pmf
|
||||
defineNamedPersistenceManagerFactory("XmlDatastore");
|
||||
AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320, "annotated", "person");
|
||||
annotatedPerson.getPhoneNumbers().add("999999999");
|
||||
annotatedPerson.getPhoneNumbers().add("000000000");
|
||||
persistObject(annotatedPerson);
|
||||
queryAnnotatedPersonsInXML();
|
||||
closePersistenceManager();
|
||||
|
||||
// persist Person object using PMF created by properties file
|
||||
definePersistenceManagerFactoryUsingPropertiesFile("META-INF\\datanucleus.properties");
|
||||
Person person = new Person(654321, "bealdung", "author");
|
||||
person.getPhoneNumbers().add("123456789");
|
||||
person.getPhoneNumbers().add("987654321");
|
||||
persistObject(person);
|
||||
queryPersonsInXML();
|
||||
closePersistenceManager();
|
||||
}
|
||||
|
||||
public static void defineDynamicPersistentUnit() {
|
||||
|
||||
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
|
||||
pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml");
|
||||
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");
|
||||
pumd.addProperty("datanucleus.xml.indentSize", "4");
|
||||
|
||||
pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
pm = pmf.getPersistenceManager();
|
||||
}
|
||||
|
||||
public static void defineNamedPersistenceManagerFactory(String pmfName) {
|
||||
|
||||
pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore");
|
||||
pm = pmf.getPersistenceManager();
|
||||
}
|
||||
|
||||
public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath) {
|
||||
|
||||
pmf = JDOHelper.getPersistenceManagerFactory(filePath);
|
||||
pm = pmf.getPersistenceManager();
|
||||
}
|
||||
|
||||
public static void closePersistenceManager() {
|
||||
|
||||
if (pm != null && !pm.isClosed()) {
|
||||
pm.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static void persistObject(Object obj) {
|
||||
|
||||
Transaction tx = pm.currentTransaction();
|
||||
|
||||
try {
|
||||
tx.begin();
|
||||
pm.makePersistent(obj);
|
||||
tx.commit();
|
||||
} finally {
|
||||
if (tx.isActive()) {
|
||||
tx.rollback();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void queryPersonsInXML() {
|
||||
|
||||
Query<Person> query = pm.newQuery(Person.class);
|
||||
List<Person> result = query.executeList();
|
||||
System.out.println("name: " + result.get(0).getFirstName());
|
||||
}
|
||||
|
||||
public static void queryAnnotatedPersonsInXML() {
|
||||
|
||||
Query<AnnotadedPerson> query = pm.newQuery(AnnotadedPerson.class);
|
||||
List<AnnotadedPerson> result = query.executeList();
|
||||
System.out.println("name: " + result.get(0).getFirstName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.jdo.xml;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.jdo.annotations.PersistenceCapable;
|
||||
import javax.jdo.annotations.PrimaryKey;
|
||||
|
||||
@PersistenceCapable
|
||||
public class Person {
|
||||
private long personNum;
|
||||
|
||||
@PrimaryKey
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
private List phoneNumbers = new ArrayList();
|
||||
|
||||
public Person(long personNum, String firstName, String lastName) {
|
||||
super();
|
||||
this.personNum = personNum;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public long getPersonNum() {
|
||||
return personNum;
|
||||
}
|
||||
|
||||
public void setPersonNum(long personNum) {
|
||||
this.personNum = personNum;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public List getPhoneNumbers() {
|
||||
return phoneNumbers;
|
||||
}
|
||||
|
||||
public void setPhoneNumbers(List phoneNumbers) {
|
||||
this.phoneNumbers = phoneNumbers;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.jdo.xml;
|
||||
|
||||
import javax.jdo.annotations.PersistenceCapable;
|
||||
import javax.jdo.annotations.PrimaryKey;
|
||||
|
||||
@PersistenceCapable
|
||||
public class Product {
|
||||
|
||||
@PrimaryKey
|
||||
String id;
|
||||
String name;
|
||||
String description;
|
||||
double price;
|
||||
|
||||
public Product() {
|
||||
|
||||
}
|
||||
|
||||
public Product(String id, String name, String description, double price) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
javax.jdo.PersistenceManagerFactoryClass=org.datanucleus.api.jdo.JDOPersistenceManagerFactory
|
||||
javax.jdo.option.ConnectionURL= xml:file:myfile-ds.xml
|
||||
datanucleus.xml.indentSize=6
|
||||
datanucleus.schema.autoCreateAll=true
|
||||
17
libraries-data/src/main/resources/META-INF/jdoconfig.xml
Normal file
17
libraries-data/src/main/resources/META-INF/jdoconfig.xml
Normal file
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<jdoconfig xmlns="http://xmlns.jcp.org/xml/ns/jdo/jdoconfig"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jdo/jdoconfig
|
||||
http://xmlns.jcp.org/xml/ns/jdo/jdoconfig_3_2.xsd"
|
||||
version="3.2">
|
||||
|
||||
<!-- Datastore Txn PMF -->
|
||||
<persistence-manager-factory name="XmlDatastore">
|
||||
<property name="javax.jdo.PersistenceManagerFactoryClass"
|
||||
value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory" />
|
||||
<property name="javax.jdo.option.ConnectionURL" value="xml:file:namedPMF-ds.xml" />
|
||||
<property name="datanucleus.xml.indentSize" value="6" />
|
||||
<property name="datanucleus.schema.autoCreateAll"
|
||||
value="true" />
|
||||
</persistence-manager-factory>
|
||||
</jdoconfig>
|
||||
29
libraries-data/src/main/resources/META-INF/package.jdo
Normal file
29
libraries-data/src/main/resources/META-INF/package.jdo
Normal file
@@ -0,0 +1,29 @@
|
||||
<jdo xmlns="http://xmlns.jcp.org/xml/ns/jdo/jdo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jdo/jdo http://xmlns.jcp.org/xml/ns/jdo/jdo_3_1.xsd"
|
||||
version="3.1">
|
||||
<package name="com.baeldung.jdo.xml">
|
||||
<class name="Person" detachable="true" schema="/myproduct/people"
|
||||
table="person">
|
||||
<field name="personNum">
|
||||
<extension vendor-name="datanucleus" key="XmlAttribute"
|
||||
value="true" />
|
||||
</field>
|
||||
<field name="firstName" primary-key="true" /> <!-- PK since JAXB requires String -->
|
||||
<field name="lastName" />
|
||||
<field name="phoneNumbers">
|
||||
<collection element-type="java.lang.String" />
|
||||
<element column="phoneNumber" />
|
||||
</field>
|
||||
</class>
|
||||
</package>
|
||||
<package name="com.baeldung.jdo.query">
|
||||
<class name="ProductItem" detachable="true" table="product_item">
|
||||
|
||||
<query name="PriceBelow10" language="javax.jdo.query.SQL">
|
||||
<![CDATA[SELECT * FROM PRODUCT_ITEM WHERE PRICE < 10
|
||||
]]></query>
|
||||
|
||||
</class>
|
||||
</package>
|
||||
|
||||
</jdo>
|
||||
47
libraries-data/src/main/resources/db.sql
Normal file
47
libraries-data/src/main/resources/db.sql
Normal file
@@ -0,0 +1,47 @@
|
||||
create table dept(
|
||||
deptno numeric,
|
||||
dname varchar(14),
|
||||
loc varchar(13),
|
||||
constraint pk_dept primary key (deptno)
|
||||
);
|
||||
|
||||
create table emp(
|
||||
empno numeric,
|
||||
ename varchar(10),
|
||||
job varchar(9),
|
||||
mgr numeric,
|
||||
hiredate date,
|
||||
sal numeric,
|
||||
comm numeric,
|
||||
deptno numeric,
|
||||
constraint pk_emp primary key (empno),
|
||||
constraint fk_deptno foreign key (deptno) references dept (deptno)
|
||||
);
|
||||
|
||||
insert into dept values(10, 'ACCOUNTING', 'NEW YORK');
|
||||
insert into dept values(20, 'RESEARCH', 'DALLAS');
|
||||
insert into dept values(30, 'SALES', 'CHICAGO');
|
||||
insert into dept values(40, 'OPERATIONS', 'BOSTON');
|
||||
|
||||
insert into emp values(
|
||||
7839, 'KING', 'PRESIDENT', null,
|
||||
to_date('17-11-1981','dd-mm-yyyy'),
|
||||
7698, null, 10
|
||||
);
|
||||
insert into emp values(
|
||||
7698, 'BLAKE', 'MANAGER', 7839,
|
||||
to_date('1-5-1981','dd-mm-yyyy'),
|
||||
7782, null, 20
|
||||
);
|
||||
insert into emp values(
|
||||
7782, 'CLARK', 'MANAGER', 7839,
|
||||
to_date('9-6-1981','dd-mm-yyyy'),
|
||||
7566, null, 30
|
||||
);
|
||||
insert into emp values(
|
||||
7566, 'JONES', 'MANAGER', 7839,
|
||||
to_date('2-4-1981','dd-mm-yyyy'),
|
||||
7839, null, 40
|
||||
);
|
||||
|
||||
commit;
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.hikaricp;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class HikariCPIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenConnection_thenFetchDbData() {
|
||||
List<Employee> employees = HikariCPDemo.fetchData();
|
||||
assertEquals(4, employees.size());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.jcache;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import javax.cache.Cache;
|
||||
import javax.cache.CacheManager;
|
||||
import javax.cache.Caching;
|
||||
import javax.cache.configuration.FactoryBuilder;
|
||||
import javax.cache.configuration.MutableConfiguration;
|
||||
import javax.cache.spi.CachingProvider;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CacheLoaderTest {
|
||||
|
||||
private static final String CACHE_NAME = "SimpleCache";
|
||||
|
||||
private Cache<Integer, String> cache;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
CachingProvider cachingProvider = Caching.getCachingProvider();
|
||||
CacheManager cacheManager = cachingProvider.getCacheManager();
|
||||
MutableConfiguration<Integer, String> config = new MutableConfiguration<Integer, String>().setReadThrough(true).setCacheLoaderFactory(new FactoryBuilder.SingletonFactory<>(new SimpleCacheLoader()));
|
||||
this.cache = cacheManager.createCache("SimpleCache", config);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadingFromStorage_thenCorrect() {
|
||||
for (int i = 1; i < 4; i++) {
|
||||
String value = cache.get(i);
|
||||
assertEquals("fromCache" + i, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.jcache;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.cache.Cache;
|
||||
import javax.cache.CacheManager;
|
||||
import javax.cache.Caching;
|
||||
import javax.cache.configuration.MutableConfiguration;
|
||||
import javax.cache.spi.CachingProvider;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class EntryProcessorIntegrationTest {
|
||||
|
||||
private static final String CACHE_NAME = "MyCache";
|
||||
|
||||
private Cache<String, String> cache;
|
||||
|
||||
@Before
|
||||
public void instantiateCache() {
|
||||
CachingProvider cachingProvider = Caching.getCachingProvider();
|
||||
CacheManager cacheManager = cachingProvider.getCacheManager();
|
||||
MutableConfiguration<String, String> config = new MutableConfiguration<>();
|
||||
this.cache = cacheManager.createCache(CACHE_NAME, config);
|
||||
this.cache.put("key", "value");
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyValue_thenCorrect() {
|
||||
this.cache.invoke("key", new SimpleEntryProcessor());
|
||||
assertEquals("value - modified", cache.get("key"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.jcache;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.cache.Cache;
|
||||
import javax.cache.CacheManager;
|
||||
import javax.cache.Caching;
|
||||
import javax.cache.configuration.FactoryBuilder;
|
||||
import javax.cache.configuration.MutableCacheEntryListenerConfiguration;
|
||||
import javax.cache.configuration.MutableConfiguration;
|
||||
import javax.cache.spi.CachingProvider;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class EventListenerIntegrationTest {
|
||||
|
||||
private static final String CACHE_NAME = "MyCache";
|
||||
|
||||
private Cache<String, String> cache;
|
||||
private SimpleCacheEntryListener listener;
|
||||
private MutableCacheEntryListenerConfiguration<String, String> listenerConfiguration;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
CachingProvider cachingProvider = Caching.getCachingProvider();
|
||||
CacheManager cacheManager = cachingProvider.getCacheManager();
|
||||
MutableConfiguration<String, String> config = new MutableConfiguration<String, String>();
|
||||
this.cache = cacheManager.createCache("MyCache", config);
|
||||
this.listener = new SimpleCacheEntryListener();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRunEvent_thenCorrect() throws InterruptedException {
|
||||
this.listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(FactoryBuilder.factoryOf(this.listener), null, false, true);
|
||||
this.cache.registerCacheEntryListener(this.listenerConfiguration);
|
||||
|
||||
assertEquals(false, this.listener.getCreated());
|
||||
|
||||
this.cache.put("key", "value");
|
||||
assertEquals(true, this.listener.getCreated());
|
||||
assertEquals(false, this.listener.getUpdated());
|
||||
|
||||
this.cache.put("key", "newValue");
|
||||
assertEquals(true, this.listener.getUpdated());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.jcache;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.cache.Cache;
|
||||
import javax.cache.CacheManager;
|
||||
import javax.cache.Caching;
|
||||
import javax.cache.configuration.MutableConfiguration;
|
||||
import javax.cache.spi.CachingProvider;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class JCacheIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void instantiateCache() {
|
||||
CachingProvider cachingProvider = Caching.getCachingProvider();
|
||||
CacheManager cacheManager = cachingProvider.getCacheManager();
|
||||
MutableConfiguration<String, String> config = new MutableConfiguration<>();
|
||||
Cache<String, String> cache = cacheManager.createCache("simpleCache", config);
|
||||
cache.put("key1", "value1");
|
||||
cache.put("key2", "value2");
|
||||
assertEquals("value1", cache.get("key1"));
|
||||
assertEquals("value2", cache.get("key2"));
|
||||
cacheManager.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.baeldung.jdo;
|
||||
|
||||
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
|
||||
import org.datanucleus.metadata.PersistenceUnitMetaData;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.jdo.PersistenceManager;
|
||||
import javax.jdo.PersistenceManagerFactory;
|
||||
import javax.jdo.Query;
|
||||
import javax.jdo.Transaction;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class GuideToJDOIntegrationTest {
|
||||
@Test
|
||||
public void givenProduct_WhenNewThenPerformTransaction() {
|
||||
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
|
||||
pumd.addClassName("com.baeldung.jdo.Product");
|
||||
pumd.setExcludeUnlistedClasses();
|
||||
pumd.addProperty("javax.jdo.option.ConnectionDriverName", "org.h2.Driver");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionPassword", "");
|
||||
pumd.addProperty("datanucleus.autoCreateSchema", "true");
|
||||
|
||||
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
PersistenceManager pm = pmf.getPersistenceManager();
|
||||
Transaction tx = pm.currentTransaction();
|
||||
try {
|
||||
tx.begin();
|
||||
for (int i = 0; i < 100; i++) {
|
||||
String nam = "Product-" + i;
|
||||
Product productx = new Product(nam, (double) i);
|
||||
pm.makePersistent(productx);
|
||||
}
|
||||
tx.commit();
|
||||
} catch (Throwable thr) {
|
||||
fail("Failed test : " + thr.getMessage());
|
||||
} finally {
|
||||
if (tx.isActive()) {
|
||||
tx.rollback();
|
||||
}
|
||||
pm.close();
|
||||
}
|
||||
|
||||
pmf.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProduct_WhenQueryThenExist() {
|
||||
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
|
||||
pumd.addClassName("com.baeldung.jdo.Product");
|
||||
pumd.setExcludeUnlistedClasses();
|
||||
pumd.addProperty("javax.jdo.option.ConnectionDriverName", "org.h2.Driver");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa");
|
||||
pumd.addProperty("javax.jdo.option.ConnectionPassword", "");
|
||||
pumd.addProperty("datanucleus.autoCreateSchema", "true");
|
||||
|
||||
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
|
||||
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);
|
||||
tx.commit();
|
||||
} catch (Throwable thr) {
|
||||
fail("Failed test : " + thr.getMessage());
|
||||
} finally {
|
||||
if (tx.isActive()) {
|
||||
tx.rollback();
|
||||
}
|
||||
pm.close();
|
||||
}
|
||||
|
||||
pmf.close();
|
||||
|
||||
PersistenceManagerFactory pmf2 = new JDOPersistenceManagerFactory(pumd, null);
|
||||
PersistenceManager pm2 = pmf2.getPersistenceManager();
|
||||
Transaction tx2 = pm2.currentTransaction();
|
||||
try {
|
||||
tx2.begin();
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
Query q = pm2.newQuery("SELECT FROM " + Product.class.getName() + " WHERE price == 200");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Product> products = (List<Product>) q.execute();
|
||||
for (Product p : products) {
|
||||
assertEquals("Laptop", p.name);
|
||||
}
|
||||
|
||||
tx2.commit();
|
||||
} finally {
|
||||
if (tx2.isActive()) {
|
||||
tx2.rollback();
|
||||
}
|
||||
|
||||
pm2.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user