Skip to Content.
Sympa Menu

perfsonar-dev - [pS-dev] [GEANT/SA2/ps-java-services] r5809 - in trunk/perfsonar-base3-persistence/src: . main main/java main/java/net main/java/net/geant main/java/net/geant/perfsonar main/java/net/geant/perfsonar/logging main/java/net/geant/perfsonar/persistence test test/java test/java/entity test/java/net test/java/net/geant test/java/net/geant/perfsonar test/java/net/geant/perfsonar/persistence test/java/net/geant/perfsonar/persistence/helper

Subject: perfsonar development work

List archive

[pS-dev] [GEANT/SA2/ps-java-services] r5809 - in trunk/perfsonar-base3-persistence/src: . main main/java main/java/net main/java/net/geant main/java/net/geant/perfsonar main/java/net/geant/perfsonar/logging main/java/net/geant/perfsonar/persistence test test/java test/java/entity test/java/net test/java/net/geant test/java/net/geant/perfsonar test/java/net/geant/perfsonar/persistence test/java/net/geant/perfsonar/persistence/helper


Chronological Thread 
  • From:
  • To:
  • Subject: [pS-dev] [GEANT/SA2/ps-java-services] r5809 - in trunk/perfsonar-base3-persistence/src: . main main/java main/java/net main/java/net/geant main/java/net/geant/perfsonar main/java/net/geant/perfsonar/logging main/java/net/geant/perfsonar/persistence test test/java test/java/entity test/java/net test/java/net/geant test/java/net/geant/perfsonar test/java/net/geant/perfsonar/persistence test/java/net/geant/perfsonar/persistence/helper
  • Date: Sun, 6 Mar 2011 21:15:17 GMT

Author: psnc.pietrzak
Date: 2011-03-06 21:15:17 +0000 (Sun, 06 Mar 2011)
New Revision: 5809

Added:
trunk/perfsonar-base3-persistence/src/main/
trunk/perfsonar-base3-persistence/src/main/java/
trunk/perfsonar-base3-persistence/src/main/java/net/
trunk/perfsonar-base3-persistence/src/main/java/net/geant/
trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/

trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/logging/

trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/logging/Logger.java

trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/persistence/

trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/persistence/HibernateConfiguration.java

trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/persistence/Persistence.java
trunk/perfsonar-base3-persistence/src/test/
trunk/perfsonar-base3-persistence/src/test/java/
trunk/perfsonar-base3-persistence/src/test/java/entity/
trunk/perfsonar-base3-persistence/src/test/java/entity/Address.java
trunk/perfsonar-base3-persistence/src/test/java/entity/Company.java
trunk/perfsonar-base3-persistence/src/test/java/entity/Company_.java
trunk/perfsonar-base3-persistence/src/test/java/entity/Employee.java
trunk/perfsonar-base3-persistence/src/test/java/net/
trunk/perfsonar-base3-persistence/src/test/java/net/geant/
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/

trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/

trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/CompanyTest.java

trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/EmployeeTest.java

trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/PersistenceTests.java

trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/helper/

trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/helper/DataGenerator.java

trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/helper/PersistenceTestBase.java
Log:
First version.

Added:
trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/logging/Logger.java
===================================================================
---
trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/logging/Logger.java
(rev 0)
+++
trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/logging/Logger.java
2011-03-06 21:15:17 UTC (rev 5809)
@@ -0,0 +1,12 @@
+package net.geant.perfsonar.logging;
+
+/**
+ * @author <a
href="mailto:">Blazej
Pietrzak</a>
+ */
+public interface Logger {
+
+ void info(String message, Object... args);
+
+ void error(Exception ex, String message, Object... args);
+
+}

Added:
trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/persistence/HibernateConfiguration.java
===================================================================
---
trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/persistence/HibernateConfiguration.java
(rev 0)
+++
trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/persistence/HibernateConfiguration.java
2011-03-06 21:15:17 UTC (rev 5809)
@@ -0,0 +1,257 @@
+package net.geant.perfsonar.persistence;
+
+import java.io.IOException;
+import java.net.URI;
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Collection;
+
+import javax.persistence.EntityManagerFactory;
+import javax.sql.DataSource;
+
+import net.geant.perfsonar.logging.Logger;
+
+import org.hibernate.ejb.Ejb3Configuration;
+
+import com.mchange.v2.c3p0.ComboPooledDataSource;
+
+/**
+ * Configuration for JPA-Hibernate implementation.
+ *
+ * Please note that you must invoke
{@link
#addEntity(Class)} method to add
+ * classes that will be managed within the given JPA configuration.
+ *
+ * @author <a
href="mailto:">Blazej
Pietrzak</a>
+ */
+public class HibernateConfiguration {
+ protected static final Logger nullLogger = new Logger() {
+ @Override
+ public void info(String message, Object... args) { }
+
+ @Override
+ public void error(Exception ex, String message, Object...
args) { }
+ };
+
+ private Logger logger = nullLogger;
+ private URI dbUri;
+ private Driver driver;
+ private int poolTimeout = 5000;
+ private int poolMinSize = 1;
+ private int poolMaxSize = 30;
+ private String ddl = "update";
+ private String dialect;
+ private Collection<Class<?>> classes = new ArrayList<Class<?>>();
+
+ public Logger getLogger() {
+ return logger;
+ }
+
+ public void setLogger(Logger logger) {
+ this.logger = logger;
+ }
+
+ public URI getDbUri() {
+ return dbUri;
+ }
+
+ public void setDbUri(URI dbUri) {
+ this.dbUri = dbUri;
+ }
+
+ public Driver getDriver() {
+ return driver;
+ }
+
+ public void setDriver(Driver driver) throws SQLException {
+ this.driver = driver;
+ DriverManager.registerDriver(driver);
+ }
+
+ public int getPoolTimeout() {
+ return poolTimeout;
+ }
+
+ public void setPoolTimeout(int poolTimeout) {
+ this.poolTimeout = poolTimeout;
+ }
+
+ public int getPoolMinSize() {
+ return poolMinSize;
+ }
+
+ public void setPoolMinSize(int poolMinSize) {
+ this.poolMinSize = poolMinSize;
+ }
+
+ public int getPoolMaxSize() {
+ return poolMaxSize;
+ }
+
+ public void setPoolMaxSize(int poolMaxSize) {
+ this.poolMaxSize = poolMaxSize;
+ }
+
+ public void setDDL(String value) {
+ this.ddl = value;
+ }
+
+ public String getDDL() {
+ return ddl;
+ }
+
+ public void setDialect(String value) {
+ this.dialect = value;
+ }
+
+ public String getDialect() {
+ return dialect;
+ }
+
+ /**
+ * Adds a class to the collection of classes that will be
+ * managed by this persistence configuration.
+ *
+ * @param clazz class annotated with @javax.persistence.Entity
+ */
+ public void addEntity(Class<?> clazz) {
+ classes.add(clazz);
+ }
+
+ /**
+ * Tests the connection to the database.
+ */
+ protected void checkConnection(String user, String password) throws
SQLException {
+ Connection fake = null;
+ try {
+ if (user == null)
+ fake = DriverManager.getConnection(dbUri.toString());
+ else
+ fake = DriverManager.getConnection(dbUri.toString(), user,
password);
+ } finally {
+ if (fake != null)
+ fake.close();
+ }
+ }
+
+ /**
+ * Guesses the default dialect for the given jdbc driver.
+ *
+ * This method is used in case if the dialect was not set explicitly
+ * via the
{@link
#setDialect(String)} method.
+ * There is no need for most of the default dialects to be set
explicitly,
+ * because there is an extensive list of default dialects provided.
+ * In case if a custom dialect is needed
{@link
#setDialect(String)} method
+ * should be invoked.
+ *
+ * @return dialect of the jdbc driver that will be used by the
persistence layer.
+ * @throws IOException if the dialect cannot be guessed
+ */
+ protected String guessDialect() throws IOException {
+ final String driver = this.driver.getClass().getName();
+ if (driver.equals("org.hsqldb.jdbcDriver")) {
+ return "org.hibernate.dialect.HSQLDialect";
+ } else if (driver.equals("com.mysql.jdbc.Driver")) {
+ return "play.db.jpa.MySQLDialect";
+ } else if (driver.equals("org.postgresql.Driver")) {
+ return "org.hibernate.dialect.PostgreSQLDialect";
+ } else if
(driver.toLowerCase().equals("com.ibm.db2.jdbc.app.DB2Driver")) {
+ return "org.hibernate.dialect.DB2Dialect";
+ } else if (driver.equals("com.ibm.as400.access.AS400JDBCDriver")) {
+ return "org.hibernate.dialect.DB2400Dialect";
+ } else if (driver.equals("com.ibm.as400.access.AS390JDBCDriver")) {
+ return "org.hibernate.dialect.DB2390Dialect";
+ } else if (driver.equals("oracle.jdbc.driver.OracleDriver")) {
+ return "org.hibernate.dialect.Oracle9iDialect";
+ } else if (driver.equals("com.sybase.jdbc2.jdbc.SybDriver")) {
+ return "org.hibernate.dialect.SybaseAnywhereDialect";
+ } else if
("com.microsoft.jdbc.sqlserver.SQLServerDriver".equals(driver)) {
+ return "org.hibernate.dialect.SQLServerDialect";
+ } else if ("com.sap.dbtech.jdbc.DriverSapDB".equals(driver)) {
+ return "org.hibernate.dialect.SAPDBDialect";
+ } else if ("com.informix.jdbc.IfxDriver".equals(driver)) {
+ return "org.hibernate.dialect.InformixDialect";
+ } else if ("com.ingres.jdbc.IngresDriver".equals(driver)) {
+ return "org.hibernate.dialect.IngresDialect";
+ } else if ("progress.sql.jdbc.JdbcProgressDriver".equals(driver)) {
+ return "org.hibernate.dialect.ProgressDialect";
+ } else if ("com.mckoi.JDBCDriver".equals(driver)) {
+ return "org.hibernate.dialect.MckoiDialect";
+ } else if ("InterBase.interclient.Driver".equals(driver)) {
+ return "org.hibernate.dialect.InterbaseDialect";
+ } else if ("com.pointbase.jdbc.jdbcUniversalDriver".equals(driver)) {
+ return "org.hibernate.dialect.PointbaseDialect";
+ } else if ("com.frontbase.jdbc.FBJDriver".equals(driver)) {
+ return "org.hibernate.dialect.FrontbaseDialect";
+ } else if ("org.firebirdsql.jdbc.FBDriver".equals(driver)) {
+ return "org.hibernate.dialect.FirebirdDialect";
+ } else if ("org.apache.derby.jdbc.EmbeddedDriver".equals(driver))
+ return "org.hibernate.dialect.DerbyDialect";
+ else
+ throw new UnsupportedOperationException("Unknown dialect for " +
+ driver + ". Please, set the property jpa.dialect in the
configuration file.");
+ }
+
+ private DataSource createDataSource(String user, String password)
throws Exception {
+ System.setProperty("com.mchange.v2.log.MLog",
"com.mchange.v2.log.FallbackMLog");
+
System.setProperty("com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL",
"OFF");
+ final ComboPooledDataSource ds = new ComboPooledDataSource();
+ ds.setDriverClass(driver.getClass().getName());
+ ds.setJdbcUrl(dbUri.toString());
+ ds.setUser(user);
+ ds.setPassword(password);
+ ds.setAcquireRetryAttempts(1);
+ ds.setAcquireRetryDelay(0);
+ ds.setBreakAfterAcquireFailure(true);
+ ds.setTestConnectionOnCheckout(true);
+
+ ds.setCheckoutTimeout(poolTimeout);
+ ds.setMaxPoolSize(poolMaxSize);
+ ds.setMinPoolSize(poolMinSize);
+
+ //url = ds.getJdbcUrl();
+ Connection c = null;
+ try {
+ c = ds.getConnection();
+ } finally {
+ if (c != null) {
+ c.close();
+ }
+ }
+
+ logger.info("Connected to %s", ds.getJdbcUrl());
+
+ return ds;
+ }
+
+ protected EntityManagerFactory createEntityManagerFactory(String
user, String password) throws IOException {
+ final Ejb3Configuration cfg = new Ejb3Configuration();
+ try {
+ cfg.setDataSource(createDataSource(user, password));
+ } catch (Exception e) {
+ if (e.getCause() instanceof InterruptedException) {
+ logger.error(e, "Cannot connected to the database. Check
the configuration.");
+ } else
+ logger.error(e, "Cannot connect to the database: %s",
e.getMessage());
+
+ return null;
+ }
+
+ cfg.setProperty("hibernate.hbm2ddl.auto", ddl);
+ cfg.setProperty("hibernate.dialect", dialect != null ? dialect :
guessDialect());
+ cfg.setProperty("javax.persistence.transaction", "RESOURCE_LOCAL");
+
+ for (Class<?> clazz : classes )
+ cfg.addAnnotatedClass(clazz);
+
+ /*if (getProperties().getProperty("jpa.debug.sql",
"false").equals("true")) {
+
org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.ALL);
+ } else {
+
org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.OFF);
+ }*/
+
+ return cfg.createEntityManagerFactory();
+ }
+}
\ No newline at end of file

Added:
trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/persistence/Persistence.java
===================================================================
---
trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/persistence/Persistence.java
(rev 0)
+++
trunk/perfsonar-base3-persistence/src/main/java/net/geant/perfsonar/persistence/Persistence.java
2011-03-06 21:15:17 UTC (rev 5809)
@@ -0,0 +1,27 @@
+package net.geant.perfsonar.persistence;
+
+import java.io.IOException;
+import java.sql.SQLException;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+
+/**
+ * Provides persistence operations via JPA EntityManager object.
+ *
+ * Please note that the separate instance of EntityManager should be used
per thread.
+ *
+ * @author <a
href="mailto:">Blazej
Pietrzak</a>
+ */
+public class Persistence {
+ private EntityManagerFactory factory;
+
+ public Persistence(HibernateConfiguration configuration, String user,
String password) throws SQLException, IOException {
+ configuration.checkConnection(user, password);
+ factory = configuration.createEntityManagerFactory(user,
password);
+ }
+
+ public EntityManager newEntityManager() {
+ return factory.createEntityManager();
+ }
+}

Added: trunk/perfsonar-base3-persistence/src/test/java/entity/Address.java
===================================================================
--- trunk/perfsonar-base3-persistence/src/test/java/entity/Address.java
(rev 0)
+++ trunk/perfsonar-base3-persistence/src/test/java/entity/Address.java
2011-03-06 21:15:17 UTC (rev 5809)
@@ -0,0 +1,81 @@
+package entity;
+
+import javax.persistence.Embeddable;
+
+/**
+ * Used for test cases.
+ *
+ * @author <a
href="mailto:">Blazej
Pietrzak</a>
+ */
+@Embeddable
+public class Address {
+ private String streetAddress;
+ private String city;
+ private String state;
+ private String zip;
+
+ public Address() {
+ }
+
+ public Address(final String sa, final String city,
+ final String state, final String zip) {
+
+ setStreetAddress(sa);
+ setCity(city);
+ setState(state);
+ setZip(zip);
+ }
+
+ public final String getCity() {
+ return city;
+ }
+
+ public final void setCity(final String city) {
+ this.city = city;
+ }
+
+ public final String getState() {
+ return state;
+ }
+
+ public final void setState(final String state) {
+ this.state = state;
+ }
+
+ public final String getStreetAddress() {
+ return streetAddress;
+ }
+
+ public final void setStreetAddress(final String streetAddress) {
+ this.streetAddress = streetAddress;
+ }
+
+ public final String getZip() {
+ return zip;
+ }
+
+ public final void setZip(final String zip) {
+ this.zip = zip;
+ }
+
+ public boolean equals(final Object obj) {
+ if (!(obj instanceof Address))
+ return false;
+
+ final Address addr = (Address) obj;
+ return addr.getCity().equals(getCity())
+ && addr.getState().equals(getState())
+ && addr.getStreetAddress().equals(getStreetAddress())
+ && addr.getZip().equals(getZip());
+ }
+
+ public int hashCode() {
+ return getCity().hashCode() * getState().hashCode()
+ * getStreetAddress().hashCode()
+ * getZip().hashCode();
+ }
+
+ public String toString() {
+ return getStreetAddress() + " " + getZip() + " " + getCity() + " " +
getState();
+ }
+}
\ No newline at end of file

Added: trunk/perfsonar-base3-persistence/src/test/java/entity/Company.java
===================================================================
--- trunk/perfsonar-base3-persistence/src/test/java/entity/Company.java
(rev 0)
+++ trunk/perfsonar-base3-persistence/src/test/java/entity/Company.java
2011-03-06 21:15:17 UTC (rev 5809)
@@ -0,0 +1,127 @@
+package entity;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Embedded;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.NamedQuery;
+import javax.persistence.OneToMany;
+
+/**
+ * Used for test cases.
+ *
+ * @author <a
href="mailto:">Blazej
Pietrzak</a>
+ */
+@Entity
+@NamedQuery(
+ name=Company.FIND_BY_NAME,
+ query="select c from Company c where c.name=:name"
+ )
+public class Company {
+ public static final String FIND_BY_NAME = "findCompanyByName";
+ public static final String NAME = "name";
+
+ @Id
+ @GeneratedValue
+ int id;
+
+ private String name;
+
+ @Embedded
+ private Address address;
+
+ @OneToMany(mappedBy = "job", cascade=CascadeType.ALL)
+ private Collection<Employee> employees;
+
+ public Company() {
+ }
+
+ public Company(final String name, final Address address,
+ final Collection<Employee> employees) {
+ setName(name);
+ setAddress(address);
+ setEmployees(employees);
+ }
+
+ public Address getAddress() {
+ return address;
+ }
+
+ public void setAddress(final Address address) {
+ this.address = address;
+ }
+
+ public Collection<Employee> getEmployees() {
+ if (employees == null) {
+ employees = new ArrayList<Employee>();
+ }
+ return employees;
+ }
+
+ public void setEmployees(final Collection<Employee> newStaff) {
+ if (employees != null) {
+ final Collection<Employee> clone = new
ArrayList<Employee>(employees);
+ for (Employee p : clone)
+ fire(p);
+ }
+
+ for (Employee p : newStaff)
+ hire(p);
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(final int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ public void hire(final Employee p) {
+ getEmployees().add(p);
+ p.setJob(this);
+ }
+
+ public void fire(final Employee p) {
+ getEmployees().remove(p);
+ p.setJob(null);
+ }
+
+ public boolean equals(final Object obj) {
+ if (!(obj instanceof Company))
+ return false;
+
+ final Company company = (Company) obj;
+ if (!(company.getAddress().equals(getAddress())
+ && company.getName().equals(getName())
+ && (company.getEmployees().size() ==
getEmployees().size())))
+ return false;
+
+ for (Employee p : company.getEmployees())
+ if (!getEmployees().contains(p))
+ return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return address.hashCode() * getEmployees().hashCode()
+ * name.hashCode();
+ }
+
+ public String toString() {
+ return getName() + " at " + getAddress() + "; " + getEmployees();
+ }
+}
\ No newline at end of file

Added: trunk/perfsonar-base3-persistence/src/test/java/entity/Company_.java
===================================================================
--- trunk/perfsonar-base3-persistence/src/test/java/entity/Company_.java
(rev 0)
+++ trunk/perfsonar-base3-persistence/src/test/java/entity/Company_.java
2011-03-06 21:15:17 UTC (rev 5809)
@@ -0,0 +1,21 @@
+package entity;
+
+import javax.persistence.metamodel.CollectionAttribute;
+import javax.persistence.metamodel.SingularAttribute;
+import javax.persistence.metamodel.StaticMetamodel;
+
+/**
+ * Used for test cases.
+ *
+ * Represents a static meta model of the Company class used to create
type-safe queries.
+ * It can be either created manually or generated using apt tools like
+ * e.g. hibernate-jpamodelgen
+ *
+ * @author <a
href="mailto:">Blazej
Pietrzak</a>
+ */
+@StaticMetamodel(Company.class)
+public class Company_ {
+ public static volatile SingularAttribute<Company, String> name;
+ public static volatile SingularAttribute<Company, Address> address;
+ public static volatile CollectionAttribute<Company, Employee>
employees;
+}

Added: trunk/perfsonar-base3-persistence/src/test/java/entity/Employee.java
===================================================================
--- trunk/perfsonar-base3-persistence/src/test/java/entity/Employee.java
(rev 0)
+++ trunk/perfsonar-base3-persistence/src/test/java/entity/Employee.java
2011-03-06 21:15:17 UTC (rev 5809)
@@ -0,0 +1,114 @@
+package entity;
+
+import javax.persistence.Embedded;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+import javax.persistence.NamedQuery;
+
+/**
+ * Used for test cases.
+ *
+ * @author <a
href="mailto:">Blazej
Pietrzak</a>
+ */
+@Entity
+@NamedQuery(name
= Employee.ALL, query = "select e from Employee e")
+public class Employee {
+ public static final String ALL = "allEmployees";
+
+ @Id
+ @GeneratedValue
+ int id;
+
+ private String firstName;
+
+ private char middleInitial;
+
+ private String lastName;
+
+ @ManyToOne(optional = true)
+ private Company job;
+
+ @Embedded
+ private Address address;
+
+ public Employee() {
+ }
+
+ public Employee(final String fn, final char mi, final String ln,
+ final Address address) {
+ setFirstName(fn);
+ setMiddleInitial(mi);
+ setLastName(ln);
+ setAddress(address);
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(final String firstName) {
+ this.firstName = firstName;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(final int id) {
+ this.id = id;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(final String lastName) {
+ this.lastName = lastName;
+ }
+
+ public char getMiddleInitial() {
+ return middleInitial;
+ }
+
+ public void setMiddleInitial(final char middleInitial) {
+ this.middleInitial = middleInitial;
+ }
+
+ public final Address getAddress() {
+ return address;
+ }
+
+ public final void setAddress(final Address address) {
+ this.address = address;
+ }
+
+ public Company getJob() {
+ return job;
+ }
+
+ public void setJob(Company job) {
+ this.job = job;
+ }
+
+ public boolean equals(final Object rhs) {
+ if (rhs instanceof Employee) {
+ final Employee other = (Employee) rhs;
+ return other.getLastName().equals(getLastName())
+ && other.getFirstName().equals(getFirstName())
+ && other.getMiddleInitial() == getMiddleInitial();
+ }
+
+ return false;
+ }
+
+ public int hashCode() {
+ return getLastName().hashCode() * getFirstName().hashCode()
+ * getMiddleInitial();
+ }
+
+ public String toString() {
+ return getFirstName() + " " + getMiddleInitial() + ". " +
getLastName();
+ }
+}
\ No newline at end of file

Added:
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/CompanyTest.java
===================================================================
---
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/CompanyTest.java
(rev 0)
+++
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/CompanyTest.java
2011-03-06 21:15:17 UTC (rev 5809)
@@ -0,0 +1,79 @@
+package net.geant.perfsonar.persistence;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.List;
+
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+
+import net.geant.perfsonar.persistence.helper.PersistenceTestBase;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import entity.Company;
+import entity.Company_;
+import entity.Employee;
+
+/**
+ * @author <a
href="mailto:">Blazej
Pietrzak</a>
+ */
+public class CompanyTest extends PersistenceTestBase {
+ private Company company;
+
+ @Before
+ public void givenCompanyWithEmployees() {
+ company = generator.createCompanyWithEmployees();
+
+ em.getTransaction().begin();
+ em.persist(company);
+ em.getTransaction().commit();
+ }
+
+ @After
+ public void tearDown() {
+ company = null;
+ }
+
+ @Test
+ public void findCompanyByName() {
+ //Using CriteriaQuery instead of JPQL is the preferred way,
+ //because it is type-safe. The following query is equivalent to:
+ //"select c from Company where c.name=" + company.getName()
+ final CriteriaBuilder cb = em.getCriteriaBuilder();
+ final CriteriaQuery<Company> query = cb.createQuery(Company.class);
+ query.where(
+ cb.equal(query.from(Company.class).get(Company_.name),
+ company.getName())
+ );
+
+ assertEquals(company, em.createQuery(query).getSingleResult());
+ }
+
+ @Test
+ public void selectAllEmployees() {
+ assertEquals(generator.createEmployees(),
+ em.createNamedQuery(Employee.ALL).getResultList());
+ }
+
+ @Test
+ public void fireAllEmployees() {
+ final List<Employee> people = generator.createEmployees();
+
+ em.getTransaction().begin();
+ for (Employee p : people)
+ company.fire(p);
+ em.persist(company);
+ em.getTransaction().commit();
+
+ //Using JPQL queries or named queries is not type-safe
+ //and thus not preferred. If you must use JPQL consider using
+ //@NamedQuery annotation to group the code with queries together.
+ //In case of refactoring of the entity it is easier to find all
queries.
+ assertEquals(generator.createCompanyWithoutEmployees(),
+ (Company) em.createNamedQuery(Company.FIND_BY_NAME)
+ .setParameter(Company.NAME,
company.getName()).getSingleResult());
+ }
+}
\ No newline at end of file

Added:
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/EmployeeTest.java
===================================================================
---
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/EmployeeTest.java
(rev 0)
+++
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/EmployeeTest.java
2011-03-06 21:15:17 UTC (rev 5809)
@@ -0,0 +1,38 @@
+package net.geant.perfsonar.persistence;
+
+import static org.junit.Assert.*;
+
+import javax.persistence.criteria.CriteriaQuery;
+
+import net.geant.perfsonar.persistence.helper.PersistenceTestBase;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import entity.Employee;
+
+/**
+ * @author <a
href="mailto:">Blazej
Pietrzak</a>
+ */
+public class EmployeeTest extends PersistenceTestBase {
+ @Before
+ public void givenEmployees() {
+ em.getTransaction().begin();
+ for (Employee emp : generator.createEmployees())
+ em.persist(emp);
+ em.getTransaction().commit();
+ }
+
+ @Test
+ public void selectAllEmployees() {
+ //Using CriteriaQuery instead of JPQL is the preferred way,
+ //because it is type-safe. The following query is equivalent to:
+ //select e from Employee e
+ final CriteriaQuery<Employee> query
+ = em.getCriteriaBuilder().createQuery(Employee.class);
+ query.from(Employee.class);
+
+ assertEquals(generator.createEmployees(),
+ em.createQuery(query).getResultList());
+ }
+}
\ No newline at end of file

Added:
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/PersistenceTests.java
===================================================================
---
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/PersistenceTests.java
(rev 0)
+++
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/PersistenceTests.java
2011-03-06 21:15:17 UTC (rev 5809)
@@ -0,0 +1,11 @@
+package net.geant.perfsonar.persistence;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
+
+@RunWith(Suite.class)
+@SuiteClasses({
EmployeeTest.class, CompanyTest.class })
+public class PersistenceTests {
+
+}

Added:
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/helper/DataGenerator.java
===================================================================
---
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/helper/DataGenerator.java
(rev 0)
+++
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/helper/DataGenerator.java
2011-03-06 21:15:17 UTC (rev 5809)
@@ -0,0 +1,45 @@
+package net.geant.perfsonar.persistence.helper;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import entity.Address;
+import entity.Company;
+import entity.Employee;
+
+/**
+ * Generates test data.
+ *
+ * @author <a
href="mailto:">Blazej
Pietrzak</a>
+ */
+public class DataGenerator {
+ public List<Employee> createEmployees() {
+ final List<Employee> result = new ArrayList<Employee>();
+
+ final Employee p1 = new Employee("John", 'B', "Doe",
+ new Address("A Street", "Dallas", "TX", "23001"));
+
+ final Employee p2 = new Employee("FirstName", 'K', "LastName",
+ new Address("B Street", "Washington", "DC", "73456"));
+
+ result.add(p1);
+ result.add(p2);
+
+ return result;
+ }
+
+ public Company createCompanyWithoutEmployees() {
+ return new Company("The Company",
+ new Address("C Street", "Paris", "TX", "77002"),
+ new ArrayList<Employee>());
+ }
+
+ public Company createCompanyWithEmployees() {
+ final Company company = createCompanyWithoutEmployees();
+
+ for (Employee emp : createEmployees())
+ company.hire(emp);
+
+ return company;
+ }
+}

Added:
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/helper/PersistenceTestBase.java
===================================================================
---
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/helper/PersistenceTestBase.java
(rev 0)
+++
trunk/perfsonar-base3-persistence/src/test/java/net/geant/perfsonar/persistence/helper/PersistenceTestBase.java
2011-03-06 21:15:17 UTC (rev 5809)
@@ -0,0 +1,50 @@
+package net.geant.perfsonar.persistence.helper;
+
+import java.net.URI;
+
+import javax.persistence.EntityManager;
+
+import net.geant.perfsonar.persistence.Persistence;
+import net.geant.perfsonar.persistence.HibernateConfiguration;
+
+import org.apache.derby.jdbc.EmbeddedDriver;
+import org.junit.After;
+import org.junit.Before;
+
+import entity.Address;
+import entity.Company;
+import entity.Employee;
+
+/**
+ * Base class for Persistence test cases.
+ *
+ * @author <a
href="mailto:">Blazej
Pietrzak</a>
+ */
+public abstract class PersistenceTestBase {
+ private static final String DB_URI = "jdbc:derby:testdb;create=true";
+ private static final String USERNAME = "sa";
+ private static final String PASSWORD = null;
+
+ protected EntityManager em;
+
+ protected final DataGenerator generator = new DataGenerator();
+
+ @Before
+ public void initPersistence() throws Exception {
+ final HibernateConfiguration config = new HibernateConfiguration();
+ config.setDbUri(new URI(DB_URI));
+ config.setDriver(new EmbeddedDriver());
+ config.setDDL("create");
+ config.addEntity(Company.class);
+ config.addEntity(Employee.class);
+ config.addEntity(Address.class);
+ final Persistence p = new Persistence(config, USERNAME, PASSWORD);
+ em = p.newEntityManager();
+ }
+
+ @After
+ public void releasePersistence() {
+ em.close();
+ em = null;
+ }
+}
\ No newline at end of file



  • [pS-dev] [GEANT/SA2/ps-java-services] r5809 - in trunk/perfsonar-base3-persistence/src: . main main/java main/java/net main/java/net/geant main/java/net/geant/perfsonar main/java/net/geant/perfsonar/logging main/java/net/geant/perfsonar/persistence test test/java test/java/entity test/java/net test/java/net/geant test/java/net/geant/perfsonar test/java/net/geant/perfsonar/persistence test/java/net/geant/perfsonar/persistence/helper, svn-noreply, 03/06/2011

Archive powered by MHonArc 2.6.16.

Top of Page