Split or move libraries-data module

This commit is contained in:
catalin-burcea
2019-10-13 16:35:46 +03:00
parent 6a22b9162b
commit 7b2920f109
171 changed files with 678 additions and 690 deletions

View File

@@ -0,0 +1,11 @@
## DB Data Libraries
This module contains articles about database-related data processing libraries.
### Relevant articles
- [Introduction to Reladomo](https://www.baeldung.com/reladomo)
- [Introduction to ORMLite](https://www.baeldung.com/ormlite)
- [Guide to Java Data Objects](https://www.baeldung.com/jdo)
- [Intro to JDO Queries 2/2](https://www.baeldung.com/jdo-queries)
- [Introduction to HikariCP](https://www.baeldung.com/hikaricp)
- [Guide to Ebean ORM](https://www.baeldung.com/ebean-orm)

View File

@@ -0,0 +1 @@
log4j.rootLogger=INFO, stdout

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?><root>
</root>

228
libraries-data-db/pom.xml Normal file
View File

@@ -0,0 +1,228 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>libraries-data-db</artifactId>
<name>libraries-data-db</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.goldmansachs.reladomo</groupId>
<artifactId>reladomo</artifactId>
<version>${reladomo.version}</version>
</dependency>
<dependency>
<groupId>com.goldmansachs.reladomo</groupId>
<artifactId>reladomo-test-util</artifactId>
<version>${reladomo.version}</version>
</dependency>
<dependency>
<groupId>com.j256.ormlite</groupId>
<artifactId>ormlite-jdbc</artifactId>
<version>${ormlite.version}</version>
</dependency>
<!-- JDO -->
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>javax.jdo</artifactId>
<version>${javax.jdo.version}</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-core</artifactId>
<version>${datanucleus.version}</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-api-jdo</artifactId>
<version>${datanucleus.version}</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-rdbms</artifactId>
<version>${datanucleus.version}</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-maven-plugin</artifactId>
<version>${datanucleus-maven-plugin.version}</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-xml</artifactId>
<version>${datanucleus-xml.version}</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-jdo-query</artifactId>
<version>${datanucleus-jdo-query.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<!-- Hikari CP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>${HikariCP.version}</version>
<scope>compile</scope>
</dependency>
<!-- ebean -->
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean</artifactId>
<version>${ebean.version}</version>
</dependency>
</dependencies>
<build>
<finalName>libraries-data-db</finalName>
<plugins>
<!-- Reladomo -->
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>${maven-antrun-plugin.version}</version>
<executions>
<execution>
<id>generateMithra</id>
<phase>generate-sources</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<property name="plugin_classpath" refid="maven.plugin.classpath" />
<taskdef name="gen-reladomo" classpath="plugin_classpath" classname="com.gs.fw.common.mithra.generator.MithraGenerator" />
<gen-reladomo xml="${project.basedir}/src/main/resources/reladomo/ReladomoClassList.xml" generateGscListMethod="true"
generatedDir="${project.build.directory}/generated-sources/reladomo" nonGeneratedDir="${project.basedir}/src/main/java" />
<taskdef name="gen-ddl" classname="com.gs.fw.common.mithra.generator.dbgenerator.MithraDbDefinitionGenerator" loaderRef="reladomoGenerator">
<classpath refid="maven.plugin.classpath" />
</taskdef>
<gen-ddl xml="${project.basedir}/src/main/resources/reladomo/ReladomoClassList.xml"
generatedDir="${project.build.directory}/generated-db/sql" databaseType="postgres" />
</tasks>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.goldmansachs.reladomo</groupId>
<artifactId>reladomogen</artifactId>
<version>${reladomo.version}</version>
</dependency>
<dependency>
<groupId>com.goldmansachs.reladomo</groupId>
<artifactId>reladomo-gen-util</artifactId>
<version>${reladomo.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>${build-helper-maven-plugin.version}</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${project.build.directory}/generated-sources/reladomo</source>
</sources>
</configuration>
</execution>
<execution>
<id>add-resource</id>
<phase>generate-resources</phase>
<goals>
<goal>add-resource</goal>
</goals>
<configuration>
<resources>
<resource>
<directory>${project.build.directory}/generated-db/</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<!-- /Reladomo -->
<!-- JDO Plugin -->
<plugin>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-maven-plugin</artifactId>
<version>${datanucleus-maven-plugin.version}</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>
<plugin>
<groupId>io.ebean</groupId>
<artifactId>ebean-maven-plugin</artifactId>
<version>11.11.2</version>
<executions>
<!-- enhance main classes -->
<execution>
<id>main</id>
<phase>process-classes</phase>
<configuration>
<transformArgs>debug=1</transformArgs>
</configuration>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<reladomo.version>16.5.1</reladomo.version>
<build-helper-maven-plugin.version>3.0.0</build-helper-maven-plugin.version>
<maven-antrun-plugin.version>1.8</maven-antrun-plugin.version>
<ormlite.version>5.0</ormlite.version>
<datanucleus.version>5.1.1</datanucleus.version>
<datanucleus-maven-plugin.version>5.0.2</datanucleus-maven-plugin.version>
<datanucleus-xml.version>5.0.0-release</datanucleus-xml.version>
<datanucleus-jdo-query.version>5.0.4</datanucleus-jdo-query.version>
<javax.jdo.version>3.2.0-m7</javax.jdo.version>
<slf4j.version>1.7.25</slf4j.version>
<HikariCP.version>2.7.2</HikariCP.version>
<ebean.version>11.22.4</ebean.version>
</properties>
</project>

View File

@@ -0,0 +1,74 @@
package com.baeldung.libraries.ebean.app;
import com.baeldung.libraries.ebean.model.Address;
import com.baeldung.libraries.ebean.model.Customer;
import io.ebean.Ebean;
import io.ebean.EbeanServer;
import io.ebean.annotation.Transactional;
import java.util.Arrays;
public class App {
public static void main(String[] args) {
insertAndDeleteInsideTransaction();
crudOperations();
queryCustomers();
}
@Transactional
public static void insertAndDeleteInsideTransaction() {
Customer c1 = getCustomer();
EbeanServer server = Ebean.getDefaultServer();
server.save(c1);
Customer foundC1 = server.find(Customer.class, c1.getId());
server.delete(foundC1);
}
public static void crudOperations() {
Address a1 = new Address("5, Wide Street", null, "New York");
Customer c1 = new Customer("John Wide", a1);
EbeanServer server = Ebean.getDefaultServer();
server.save(c1);
c1.setName("Jane Wide");
c1.setAddress(null);
server.save(c1);
Customer foundC1 = Ebean.find(Customer.class, c1.getId());
Ebean.delete(foundC1);
}
public static void queryCustomers() {
Address a1 = new Address("1, Big Street", null, "New York");
Customer c1 = new Customer("Big John", a1);
Address a2 = new Address("2, Big Street", null, "New York");
Customer c2 = new Customer("Big John", a2);
Address a3 = new Address("3, Big Street", null, "San Jose");
Customer c3 = new Customer("Big Bob", a3);
Ebean.saveAll(Arrays.asList(c1, c2, c3));
Customer customer = Ebean.find(Customer.class)
.select("name")
.fetch("address", "city")
.where()
.eq("city", "San Jose")
.findOne();
Ebean.deleteAll(Arrays.asList(c1, c2, c3));
}
private static Customer getCustomer() {
Address a1 = new Address("1, Big Street", null, "New York");
Customer c1 = new Customer("Big John", a1);
return c1;
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.libraries.ebean.app;
import io.ebean.EbeanServer;
import io.ebean.EbeanServerFactory;
import io.ebean.config.ServerConfig;
import java.util.Properties;
public class App2 {
public static void main(String[] args) {
ServerConfig cfg = new ServerConfig();
cfg.setDefaultServer(true);
Properties properties = new Properties();
properties.put("ebean.db.ddl.generate", "true");
properties.put("ebean.db.ddl.run", "true");
properties.put("datasource.db.username", "sa");
properties.put("datasource.db.password", "");
properties.put("datasource.db.databaseUrl", "jdbc:h2:mem:app2");
properties.put("datasource.db.databaseDriver", "org.h2.Driver");
cfg.loadFromProperties(properties);
EbeanServer server = EbeanServerFactory.create(cfg);
}
}

View File

@@ -0,0 +1,48 @@
package com.baeldung.libraries.ebean.model;
import javax.persistence.Entity;
@Entity
public class Address extends BaseModel {
public Address(String addressLine1, String addressLine2, String city) {
super();
this.addressLine1 = addressLine1;
this.addressLine2 = addressLine2;
this.city = city;
}
private String addressLine1;
private String addressLine2;
private String city;
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Address [id=" + id + ", addressLine1=" + addressLine1 + ", addressLine2=" + addressLine2 + ", city=" + city + "]";
}
}

View File

@@ -0,0 +1,58 @@
package com.baeldung.libraries.ebean.model;
import io.ebean.annotation.WhenCreated;
import io.ebean.annotation.WhenModified;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
import java.time.Instant;
@MappedSuperclass
public abstract class BaseModel {
@Id
protected long id;
@Version
protected long version;
@WhenCreated
protected Instant createdOn;
@WhenModified
protected Instant modifiedOn;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Instant getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Instant createdOn) {
this.createdOn = createdOn;
}
public Instant getModifiedOn() {
return modifiedOn;
}
public void setModifiedOn(Instant modifiedOn) {
this.modifiedOn = modifiedOn;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
}

View File

@@ -0,0 +1,42 @@
package com.baeldung.libraries.ebean.model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
@Entity
public class Customer extends BaseModel {
public Customer(String name, Address address) {
super();
this.name = name;
this.address = address;
}
private String name;
@OneToOne(cascade = CascadeType.ALL)
Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.libraries.hikaricp;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;
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();
}
}

View File

@@ -0,0 +1,85 @@
package com.baeldung.libraries.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);
}
}

View File

@@ -0,0 +1,40 @@
package com.baeldung.libraries.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();
}
}

View File

@@ -0,0 +1,298 @@
package com.baeldung.libraries.jdo;
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
import org.datanucleus.metadata.PersistenceUnitMetaData;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;
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;
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.libraries.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.libraries.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();
}
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.libraries.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;
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.libraries.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;
}
}

View File

@@ -0,0 +1,95 @@
package com.baeldung.libraries.jdo.query;
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
import org.datanucleus.metadata.PersistenceUnitMetaData;
import javax.jdo.JDOQLTypedQuery;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import java.util.List;
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.libraries.jdo.query.ProductItem " + "WHERE price < threshold PARAMETERS double threshold");
List<ProductItem> explicitParamResults = (List<ProductItem>) query.execute(10);
query = pm.newQuery("SELECT FROM " + "com.baeldung.libraries.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.libraries.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.libraries.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();
}
}

View File

@@ -0,0 +1,70 @@
package com.baeldung.libraries.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;
}
}

View File

@@ -0,0 +1,65 @@
package com.baeldung.libraries.jdo.xml;
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;
import java.util.ArrayList;
import java.util.List;
@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;
}
}

View File

@@ -0,0 +1,100 @@
package com.baeldung.libraries.jdo.xml;
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
import org.datanucleus.metadata.PersistenceUnitMetaData;
import javax.jdo.*;
import java.util.List;
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());
}
}

View File

@@ -0,0 +1,57 @@
package com.baeldung.libraries.jdo.xml;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;
import java.util.ArrayList;
import java.util.List;
@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;
}
}

View File

@@ -0,0 +1,58 @@
package com.baeldung.libraries.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;
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.libraries.ormlite;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "addresses")
public class Address {
@DatabaseField(generatedId = true)
private long addressId;
@DatabaseField(canBeNull = false)
private String addressLine;
public Address() {
}
public Address(String addressLine) {
this.addressLine = addressLine;
}
public long getAddressId() {
return addressId;
}
public void setAddressId(long addressId) {
this.addressId = addressId;
}
public String getAddressLine() {
return addressLine;
}
public void setAddressLine(String addressLine) {
this.addressLine = addressLine;
}
}

View File

@@ -0,0 +1,49 @@
package com.baeldung.libraries.ormlite;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable
public class Book {
@DatabaseField(generatedId = true)
private long bookId;
@DatabaseField
private String title;
@DatabaseField(foreign = true, foreignAutoRefresh = true, foreignAutoCreate = true)
private Library library;
public Book() {
}
public Book(String title) {
this.title = title;
}
public long getBookId() {
return bookId;
}
public void setBookId(long bookId) {
this.bookId = bookId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Library getLibrary() {
return library;
}
public void setLibrary(Library library) {
this.library = library;
}
}

View File

@@ -0,0 +1,58 @@
package com.baeldung.libraries.ormlite;
import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "libraries", daoClass = LibraryDaoImpl.class)
public class Library {
@DatabaseField(generatedId = true)
private long libraryId;
@DatabaseField(canBeNull = false)
private String name;
@DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true)
private Address address;
@ForeignCollectionField(eager = false)
private ForeignCollection<Book> books;
public Library() {
}
public long getLibraryId() {
return libraryId;
}
public void setLibraryId(long libraryId) {
this.libraryId = libraryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public ForeignCollection<Book> getBooks() {
return books;
}
public void setBooks(ForeignCollection<Book> books) {
this.books = books;
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.libraries.ormlite;
import com.j256.ormlite.dao.Dao;
import java.sql.SQLException;
import java.util.List;
public interface LibraryDao extends Dao<Library, Long> {
public List<Library> findByName(String name) throws SQLException;
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.libraries.ormlite;
import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.support.ConnectionSource;
import java.sql.SQLException;
import java.util.List;
public class LibraryDaoImpl extends BaseDaoImpl<Library, Long> implements LibraryDao {
public LibraryDaoImpl(ConnectionSource connectionSource) throws SQLException {
super(connectionSource, Library.class);
}
@Override
public List<Library> findByName(String name) throws SQLException {
return super.queryForEq("name", name);
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.libraries.reladomo;
public class Department extends DepartmentAbstract {
public Department() {
super();
// You must not modify this constructor. Mithra calls this internally.
// You can call this constructor. You can also add new constructors.
}
public Department(long id, String name) {
super();
this.setId(id);
this.setName(name);
}
}

View File

@@ -0,0 +1,4 @@
package com.baeldung.libraries.reladomo;
public class DepartmentDatabaseObject extends DepartmentDatabaseObjectAbstract
{
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.libraries.reladomo;
import com.gs.fw.finder.Operation;
import java.util.Collection;
public class DepartmentList extends DepartmentListAbstract
{
public DepartmentList()
{
super();
}
public DepartmentList(int initialSize)
{
super(initialSize);
}
public DepartmentList(Collection c)
{
super(c);
}
public DepartmentList(Operation operation)
{
super(operation);
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.libraries.reladomo;
public class Employee extends EmployeeAbstract
{
public Employee()
{
super();
// You must not modify this constructor. Mithra calls this internally.
// You can call this constructor. You can also add new constructors.
}
public Employee(long id, String name){
super();
this.setId(id);
this.setName(name);
}
}

View File

@@ -0,0 +1,4 @@
package com.baeldung.libraries.reladomo;
public class EmployeeDatabaseObject extends EmployeeDatabaseObjectAbstract
{
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.libraries.reladomo;
import com.gs.fw.finder.Operation;
import java.util.Collection;
public class EmployeeList extends EmployeeListAbstract
{
public EmployeeList()
{
super();
}
public EmployeeList(int initialSize)
{
super(initialSize);
}
public EmployeeList(Collection c)
{
super(c);
}
public EmployeeList(Operation operation)
{
super(operation);
}
}

View File

@@ -0,0 +1,51 @@
package com.baeldung.libraries.reladomo;
import com.gs.fw.common.mithra.MithraManager;
import com.gs.fw.common.mithra.MithraManagerProvider;
import java.io.InputStream;
public class ReladomoApplication {
public static void main(String[] args) {
try {
ReladomoConnectionManager.getInstance().createTables();
} catch (Exception e1) {
e1.printStackTrace();
}
MithraManager mithraManager = MithraManagerProvider.getMithraManager();
mithraManager.setTransactionTimeout(120);
try (InputStream is = ReladomoApplication.class.getClassLoader().getResourceAsStream("ReladomoRuntimeConfig.xml")) {
MithraManagerProvider.getMithraManager().readConfiguration(is);
Department department = new Department(1, "IT");
Employee employee = new Employee(1, "John");
department.getEmployees().add(employee);
department.cascadeInsert();
Department depFound = DepartmentFinder.findByPrimaryKey(1);
System.out.println("Department Name:" + department.getName());
Employee empFound = EmployeeFinder.findOne(EmployeeFinder.name().eq("John"));
System.out.println("Employee Id:" + empFound.getId());
empFound.setName("Steven");
empFound.delete();
Department depDetached = DepartmentFinder.findByPrimaryKey(1).getDetachedCopy();
mithraManager.executeTransactionalCommand(tx -> {
Department dep = new Department(2, "HR");
Employee emp = new Employee(2, "Jim");
dep.getEmployees().add(emp);
dep.cascadeInsert();
return null;
});
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,91 @@
package com.baeldung.libraries.reladomo;
import com.gs.fw.common.mithra.bulkloader.BulkLoader;
import com.gs.fw.common.mithra.bulkloader.BulkLoaderException;
import com.gs.fw.common.mithra.connectionmanager.SourcelessConnectionManager;
import com.gs.fw.common.mithra.connectionmanager.XAConnectionManager;
import com.gs.fw.common.mithra.databasetype.DatabaseType;
import com.gs.fw.common.mithra.databasetype.H2DatabaseType;
import org.h2.tools.RunScript;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.TimeZone;
import java.util.stream.Stream;
public class ReladomoConnectionManager implements SourcelessConnectionManager {
private static ReladomoConnectionManager instance;
private XAConnectionManager xaConnectionManager;
private final String databaseName = "myDb";
public static synchronized ReladomoConnectionManager getInstance() {
if (instance == null) {
instance = new ReladomoConnectionManager();
}
return instance;
}
private ReladomoConnectionManager() {
this.createConnectionManager();
}
private XAConnectionManager createConnectionManager() {
xaConnectionManager = new XAConnectionManager();
xaConnectionManager.setDriverClassName("org.h2.Driver");
xaConnectionManager.setJdbcConnectionString("jdbc:h2:mem:" + databaseName);
xaConnectionManager.setJdbcUser("sa");
xaConnectionManager.setJdbcPassword("");
xaConnectionManager.setPoolName("My Connection Pool");
xaConnectionManager.setInitialSize(1);
xaConnectionManager.setPoolSize(10);
xaConnectionManager.initialisePool();
return xaConnectionManager;
}
@Override
public BulkLoader createBulkLoader() throws BulkLoaderException {
return null;
}
@Override
public Connection getConnection() {
return xaConnectionManager.getConnection();
}
@Override
public DatabaseType getDatabaseType() {
return H2DatabaseType.getInstance();
}
@Override
public TimeZone getDatabaseTimeZone() {
return TimeZone.getDefault();
}
@Override
public String getDatabaseIdentifier() {
return databaseName;
}
public void createTables() throws Exception {
Path ddlPath = Paths.get(ClassLoader.getSystemResource("sql").toURI());
try (Connection conn = xaConnectionManager.getConnection(); Stream<Path> list = Files.list(ddlPath);) {
list.forEach(path -> {
try {
RunScript.execute(conn, Files.newBufferedReader(path));
} catch (SQLException | IOException exc) {
exc.printStackTrace();
}
});
}
}
}

View File

@@ -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

View 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>

View 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.libraries.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.libraries.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>

View File

@@ -0,0 +1,51 @@
drop table if exists emp;
drop table if exists dept;
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;

View File

@@ -0,0 +1,3 @@
entity-packages: com.baeldung.libraries.ebean.model
transactional-packages: com.baeldung.libraries.ebean.app
querybean-packages: com.baeldung.libraries.ebean.app

View File

@@ -0,0 +1,7 @@
ebean.db.ddl.generate=true
ebean.db.ddl.run=true
datasource.db.username=sa
datasource.db.password=
datasource.db.databaseUrl=jdbc:h2:mem:customer
datasource.db.databaseDriver=org.h2.Driver

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="io.ebean.DDL" level="TRACE"/>
<logger name="io.ebean.SQL" level="TRACE"/>
<logger name="io.ebean.TXN" level="TRACE"/>
<root level="WARN">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,11 @@
<MithraObject objectType="transactional">
<PackageName>com.baeldung.libraries.reladomo</PackageName>
<ClassName>Department</ClassName>
<DefaultTable>departments</DefaultTable>
<Attribute name="id" javaType="long" columnName="department_id" primaryKey="true"/>
<Attribute name="name" javaType="String" columnName="name" maxLength="50" truncate="true"/>
<Relationship name="employees" relatedObject="Employee" cardinality="one-to-many" reverseRelationshipName="department" relatedIsDependent="true">
Employee.departmentId = this.id
</Relationship>
</MithraObject>

View File

@@ -0,0 +1,9 @@
<MithraObject objectType="transactional">
<PackageName>com.baeldung.libraries.reladomo</PackageName>
<ClassName>Employee</ClassName>
<DefaultTable>employees</DefaultTable>
<Attribute name="id" javaType="long" columnName="employee_id" primaryKey="true"/>
<Attribute name="name" javaType="String" columnName="name" maxLength="50" truncate="true"/>
<Attribute name="departmentId" javaType="long" columnName="department_id"/>
</MithraObject>

View File

@@ -0,0 +1,4 @@
<Mithra>
<MithraObjectResource name="Department"/>
<MithraObjectResource name="Employee"/>
</Mithra>

View File

@@ -0,0 +1,6 @@
<MithraRuntime>
<ConnectionManager className="com.baeldung.libraries.reladomo.ReladomoConnectionManager ">
<MithraObjectConfiguration className="com.baeldung.libraries.reladomo.Department" cacheType="partial"/>
<MithraObjectConfiguration className="com.baeldung.libraries.reladomo.Employee " cacheType="partial"/>
</ConnectionManager>
</MithraRuntime>

View File

@@ -0,0 +1,17 @@
package com.baeldung.libraries.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());
}
}

View File

@@ -0,0 +1,111 @@
package com.baeldung.libraries.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.libraries.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");
pumd.addProperty("datanucleus.schema.autoCreateTables", "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.libraries.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");
pumd.addProperty("datanucleus.schema.autoCreateTables", "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();
}
}
}

View File

@@ -0,0 +1,168 @@
package com.baeldung.libraries.ormlite;
import com.j256.ormlite.dao.CloseableWrappedIterable;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.jdbc.JdbcPooledConnectionSource;
import com.j256.ormlite.table.TableUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import static org.junit.Assert.*;
public class ORMLiteIntegrationTest {
private static JdbcPooledConnectionSource connectionSource;
private static Dao<Library, Long> libraryDao;
private static Dao<Book, Long> bookDao;
@BeforeClass
public static void setup() throws SQLException {
connectionSource = new JdbcPooledConnectionSource("jdbc:h2:mem:myDb");
TableUtils.createTableIfNotExists(connectionSource, Library.class);
TableUtils.createTableIfNotExists(connectionSource, Address.class);
TableUtils.createTableIfNotExists(connectionSource, Book.class);
libraryDao = DaoManager.createDao(connectionSource, Library.class);
bookDao = DaoManager.createDao(connectionSource, Book.class);
}
@Test
public void givenDAO_whenCRUD_thenOk() throws SQLException {
Library library = new Library();
library.setName("My Library");
libraryDao.create(library);
Library result = libraryDao.queryForId(library.getLibraryId());
assertEquals("My Library", result.getName());
library.setName("My Other Library");
libraryDao.update(library);
libraryDao.delete(library);
}
@Test
public void whenLoopDao_thenOk() throws SQLException {
Library library1 = new Library();
library1.setName("My Library");
libraryDao.create(library1);
Library library2 = new Library();
library2.setName("My Other Library");
libraryDao.create(library2);
libraryDao.forEach(lib -> {
System.out.println(lib.getName());
});
}
@Test
public void givenIterator_whenLoop_thenOk() throws SQLException, IOException {
Library library1 = new Library();
library1.setName("My Library");
libraryDao.create(library1);
Library library2 = new Library();
library2.setName("My Other Library");
libraryDao.create(library2);
try (CloseableWrappedIterable<Library> wrappedIterable = libraryDao.getWrappedIterable()) {
wrappedIterable.forEach(lib -> {
System.out.println(lib.getName());
});
}
}
@Test
public void givenCustomDao_whenSave_thenOk() throws SQLException, IOException {
Library library = new Library();
library.setName("My Library");
LibraryDao customLibraryDao = DaoManager.createDao(connectionSource, Library.class);
customLibraryDao.create(library);
assertEquals(1, customLibraryDao.findByName("My Library")
.size());
}
@Test
public void whenSaveForeignField_thenOk() throws SQLException, IOException {
Library library = new Library();
library.setName("My Library");
library.setAddress(new Address("Main Street nr 20"));
libraryDao.create(library);
Dao<Address, Long> addressDao = DaoManager.createDao(connectionSource, Address.class);
assertEquals(1, addressDao.queryForEq("addressLine", "Main Street nr 20")
.size());
}
@Test
public void whenSaveForeignCollection_thenOk() throws SQLException, IOException {
Library library = new Library();
library.setName("My Library");
libraryDao.create(library);
libraryDao.refresh(library);
library.getBooks()
.add(new Book("1984"));
Book book = new Book("It");
book.setLibrary(library);
bookDao.create(book);
assertEquals(2, bookDao.queryForEq("library_id", library)
.size());
}
@Test
public void whenGetLibrariesWithMoreThanOneBook_thenOk() throws SQLException, IOException {
Library library = new Library();
library.setName("My Library");
libraryDao.create(library);
Library library2 = new Library();
library2.setName("My Other Library");
libraryDao.create(library2);
libraryDao.refresh(library);
libraryDao.refresh(library2);
library.getBooks()
.add(new Book("Book1"));
library2.getBooks()
.add(new Book("Book2"));
library2.getBooks()
.add(new Book("Book3"));
List<Library> libraries = libraryDao.queryBuilder()
.where()
.in("libraryId", bookDao.queryBuilder()
.selectColumns("library_id")
.groupBy("library_id")
.having("count(*) > 1"))
.query();
assertEquals(1, libraries.size());
}
@After
public void clear() throws SQLException {
TableUtils.clearTable(connectionSource, Library.class);
TableUtils.clearTable(connectionSource, Book.class);
TableUtils.clearTable(connectionSource, Address.class);
}
@AfterClass
public static void tearDown() throws SQLException, IOException {
connectionSource.close();
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.libraries.reladomo;
import com.gs.fw.common.mithra.test.ConnectionManagerForTests;
import com.gs.fw.common.mithra.test.MithraTestResource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class ReladomoIntegrationTest {
private MithraTestResource mithraTestResource;
@Before
public void setUp() throws Exception {
this.mithraTestResource = new MithraTestResource("reladomo/ReladomoTestConfig.xml");
final ConnectionManagerForTests connectionManager = ConnectionManagerForTests.getInstanceForDbName("testDb");
this.mithraTestResource.createSingleDatabase(connectionManager);
mithraTestResource.addTestDataToDatabase("reladomo/test-data.txt", connectionManager);
this.mithraTestResource.setUp();
}
@Test
public void whenGetTestData_thenOk() {
Employee employee = EmployeeFinder.findByPrimaryKey(1);
assertEquals(employee.getName(), "Paul");
}
@After
public void tearDown() throws Exception {
this.mithraTestResource.tearDown();
}
}

View File

@@ -0,0 +1,7 @@
<MithraRuntime>
<ConnectionManager className="com.gs.fw.common.mithra.test.ConnectionManagerForTests">
<Property name="resourceName" value="testDb"/>
<MithraObjectConfiguration className="com.baeldung.libraries.reladomo.Department" cacheType="partial"/>
<MithraObjectConfiguration className="com.baeldung.libraries.reladomo.Employee" cacheType="partial"/>
</ConnectionManager>
</MithraRuntime>

View File

@@ -0,0 +1,7 @@
class com.baeldung.libraries.reladomo.Department
id, name
1, "Marketing"
class com.baeldung.libraries.reladomo.Employee
id, name
1, "Paul"