JPA with Eclipse and MySQL: Using Java Configuration

The** Java Persistence API** is a standard specification for ORM (Object Relational Mapping) implementations. Also, it shows how to define a PLAIN OLD JAVA OBJECT (POJO) as an entity and how to manage entities with relations.

Key JPA Entities

**1.) **<strong>EntityManagerFactory</strong>: This is a factory class of EntityManager. It creates and manages multiple EntityManager instances.

**2.) **<strong>EntityManger</strong>: This interface manages the persistence operations on entities.

**3.) **<strong>Entity</strong>: Entities are the persistence objects, stores as records in the database.

**4.) **<strong>EntityTransaction</strong>: It has a one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class.

**5.) **<strong>Persistence</strong>: This class contains static methods used to obtain a EntityManagerFactory instance.

**6.) **<strong>Query</strong>: This interface is implemented by each JPA vendor to obtain relational objects that meet the criteria.

Now, let us start our JPA implementations with an example:

Required Maven dependencies:

<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
</dependencies>

Here, to achieve persistence in the application, we need to introduce the persistence.xml, which has to be located in the META-INF directory in the project classpath.

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="JPATest"
transaction-type="RESOURCE_LOCAL">
<class><!-- Entity Class Name --></class>
</persistence-unit>
</persistence>

Here, the persistence unit name must be unique. Also, we can add multiple persistence-units for different units. The transaction type for this persistence unit is RESOURCE_LOCAL.

There are two types of transactions:

  • JTA: The transactions will be managed by the Application Server
  • RESOURCE_LOCAL: The transaction will be managed by the JPA Provider Implementation in use.

Also, specify the class name for entities in this configuration file. There is one more configuration used for the database connection. But for dynamic configuration of database connection, we add that configuration in Java code instead of this XML file.

EntityManager:

public class JpaEntityManager {
private EntityManagerFactory emFactoryObj;
private final String PERSISTENCE_UNIT_NAME = "JPATest";
private final Map<String, String> properties=new HashMap<String, String>();


// This Method Is Used To Retrieve The 'EntityManager' Object
public EntityManager getEntityManager() {

String url = String.format("%s/%s", DBConstants.DB_HOST, DBConstants.DB_NAME);

properties.put("javax.persistence.jdbc.driver",DBConstants.DB_DRIVER);
properties.put("javax.persistence.jdbc.url", url);
properties.put("javax.persistence.jdbc.user", DBConstants.DB_USER);
properties.put("javax.persistence.jdbc.password",DBConstants.DB_PASSWORD);
properties.put("useSSL", DBConstants.DB_USE_SSL);
properties.put("requireSSL", DBConstants.DB_REQUIRED_SSL);
properties.put("serverTimezone",DBConstants.DB_SERVER_TIMEZONE);

emFactoryObj = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME,properties);

return emFactoryObj.createEntityManager();
}
}

Here, you have to add your database related configuration like drive class name, hostname, database name, username, password, etc.

Database schema:

CREATE TABLE user (
  id INTEGER NOT NULL,
  name VARCHAR(255) NOT NULL,  
  age VARCHAR(100) NOT NULL,
  PRIMARY KEY(id)
);

Entity:

Here are some annotations used for JPA implementation.

1.) @Entity: to mark the java class as an entity.

2.) @Table: to specify the table to which this entity class maps.

3.) @Id: to identify a row uniquely (JPA Primary Key).

4.) @Column: to specify the mapped column for a persistent property or field.

**5. **<strong>JPARepository</strong>: used to perform database-related operations.

public class JpaRepository<T, ID> implements AutoCloseable {

private final Class<T> typeParameterClass;
protected EntityManager entityManager;

public JpaRepository(Class<T> typeParameterClass) {
JpaEntityManager dbEntityManager = new JpaEntityManager();
entityManager = dbEntityManager.getEntityManager();
this.typeParameterClass = typeParameterClass;
}
/**
 * Save an entity.
 * @param entity
 * @return the saved entity
 */
public <S extends T> S save(S entity) {
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.getTransaction().commit();
return entity;
}
/**
 * merge an entity.
 *
 * @param entity
 * @return the saved entity
 */
public <S extends T> S merge(S entity) {
entityManager.getTransaction().begin();
entityManager.merge(entity);
entityManager.getTransaction().commit();
return entity;
}
/**
 * Delete an entity
 * 
 * @param id
 */
public void delete(ID id) {
entityManager.remove(id);
}
/**
 * Returns a reference to the entity with the given identifier.
 * 
 * @param id
 * @return
 */
public T findById(ID id) {
T t = entityManager.find(typeParameterClass, id);
return t;
}
/**
 * get single result
 * 
 * @param q
 * @return
 */
public Optional<T> getSingleResult(CriteriaQuery<T> q) {

try {
return Optional.ofNullable(entityManager.createQuery(q).getSingleResult());
} catch (RuntimeException e) {
return Optional.empty();
}
}
/**
 * get single result
 * 
 * @param q
 * @return
 */
public Optional<List<T>> getResultList(CriteriaQuery<T> q) {
try {
return Optional.ofNullable(entityManager.createQuery(q).getResultList());
} catch (RuntimeException e) {
return Optional.empty();
}
}
/**
 * used to close entity manager obj
 */
public void close() {
entityManager.clear();
entityManager.close();
}
}

You can also use JPA Criteria API queries, which provide an alternative way for defining JPA queries and is mainly useful for building dynamic queries whose exact structure is only known at runtime.

Now, all configuration is done. So, let us start to test this application.

public class JPADemo {

public static void main(String[] args) {
User user=new User();
user.setId(1);
user.setAge(20);
user.setName("Abc");

try(JpaRepository userJpaRepository=new JpaRepository<BlenderMaster, Long>(BlenderMaster.class)){
userJpaRepository.save(user);
}catch (Exception e) {
e.printStackTrace();
}
}
}

Here, we added the JPA Repository resource in a try catch, so resource will be closed automatically after use. After running this application, one new user entry will be added in the MySQL database.

Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!

Further reading

Java Programming Masterclass for Software Developers

JSP, Servlets and JDBC for Beginners: Build a Database App

Java 8 New Features In Simple Way

Java In-Depth: Become a Complete Java Engineer!

Java for Absolute Beginners

Java Programming for Complete Beginners - Learn in 250 Steps

Learn Java Programming Crash Course

Apache Spark for Java Developers

#java #mysql #jpa #maven #database #api #web-development

What is GEEK

Buddha Community

JPA with Eclipse and MySQL: Using Java Configuration
Tyrique  Littel

Tyrique Littel

1600135200

How to Install OpenJDK 11 on CentOS 8

What is OpenJDK?

OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE). It contains the virtual machine, the Java Class Library, and the Java compiler. The difference between the Oracle OpenJDK and Oracle JDK is that OpenJDK is a source code reference point for the open-source model. Simultaneously, the Oracle JDK is a continuation or advanced model of the OpenJDK, which is not open source and requires a license to use.

In this article, we will be installing OpenJDK on Centos 8.

#tutorials #alternatives #centos #centos 8 #configuration #dnf #frameworks #java #java development kit #java ee #java environment variables #java framework #java jdk #java jre #java platform #java sdk #java se #jdk #jre #open java development kit #open source #openjdk #openjdk 11 #openjdk 8 #openjdk runtime environment

Joe  Hoppe

Joe Hoppe

1595905879

Best MySQL DigitalOcean Performance – ScaleGrid vs. DigitalOcean Managed Databases

HTML to Markdown

MySQL is the all-time number one open source database in the world, and a staple in RDBMS space. DigitalOcean is quickly building its reputation as the developers cloud by providing an affordable, flexible and easy to use cloud platform for developers to work with. MySQL on DigitalOcean is a natural fit, but what’s the best way to deploy your cloud database? In this post, we are going to compare the top two providers, DigitalOcean Managed Databases for MySQL vs. ScaleGrid MySQL hosting on DigitalOcean.

At a glance – TLDR
ScaleGrid Blog - At a glance overview - 1st pointCompare Throughput
ScaleGrid averages almost 40% higher throughput over DigitalOcean for MySQL, with up to 46% higher throughput in write-intensive workloads. Read now

ScaleGrid Blog - At a glance overview - 2nd pointCompare Latency
On average, ScaleGrid achieves almost 30% lower latency over DigitalOcean for the same deployment configurations. Read now

ScaleGrid Blog - At a glance overview - 3rd pointCompare Pricing
ScaleGrid provides 30% more storage on average vs. DigitalOcean for MySQL at the same affordable price. Read now

MySQL DigitalOcean Performance Benchmark
In this benchmark, we compare equivalent plan sizes between ScaleGrid MySQL on DigitalOcean and DigitalOcean Managed Databases for MySQL. We are going to use a common, popular plan size using the below configurations for this performance benchmark:

Comparison Overview
ScaleGridDigitalOceanInstance TypeMedium: 4 vCPUsMedium: 4 vCPUsMySQL Version8.0.208.0.20RAM8GB8GBSSD140GB115GBDeployment TypeStandaloneStandaloneRegionSF03SF03SupportIncludedBusiness-level support included with account sizes over $500/monthMonthly Price$120$120

As you can see above, ScaleGrid and DigitalOcean offer the same plan configurations across this plan size, apart from SSD where ScaleGrid provides over 20% more storage for the same price.

To ensure the most accurate results in our performance tests, we run the benchmark four times for each comparison to find the average performance across throughput and latency over read-intensive workloads, balanced workloads, and write-intensive workloads.

Throughput
In this benchmark, we measure MySQL throughput in terms of queries per second (QPS) to measure our query efficiency. To quickly summarize the results, we display read-intensive, write-intensive and balanced workload averages below for 150 threads for ScaleGrid vs. DigitalOcean MySQL:

ScaleGrid MySQL vs DigitalOcean Managed Databases - Throughput Performance Graph

For the common 150 thread comparison, ScaleGrid averages almost 40% higher throughput over DigitalOcean for MySQL, with up to 46% higher throughput in write-intensive workloads.

#cloud #database #developer #digital ocean #mysql #performance #scalegrid #95th percentile latency #balanced workloads #developers cloud #digitalocean droplet #digitalocean managed databases #digitalocean performance #digitalocean pricing #higher throughput #latency benchmark #lower latency #mysql benchmark setup #mysql client threads #mysql configuration #mysql digitalocean #mysql latency #mysql on digitalocean #mysql throughput #performance benchmark #queries per second #read-intensive #scalegrid mysql #scalegrid vs. digitalocean #throughput benchmark #write-intensive

JPA with Eclipse and MySQL: Using Java Configuration

The** Java Persistence API** is a standard specification for ORM (Object Relational Mapping) implementations. Also, it shows how to define a PLAIN OLD JAVA OBJECT (POJO) as an entity and how to manage entities with relations.

Key JPA Entities

**1.) **<strong>EntityManagerFactory</strong>: This is a factory class of EntityManager. It creates and manages multiple EntityManager instances.

**2.) **<strong>EntityManger</strong>: This interface manages the persistence operations on entities.

**3.) **<strong>Entity</strong>: Entities are the persistence objects, stores as records in the database.

**4.) **<strong>EntityTransaction</strong>: It has a one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class.

**5.) **<strong>Persistence</strong>: This class contains static methods used to obtain a EntityManagerFactory instance.

**6.) **<strong>Query</strong>: This interface is implemented by each JPA vendor to obtain relational objects that meet the criteria.

Now, let us start our JPA implementations with an example:

Required Maven dependencies:

<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
</dependencies>

Here, to achieve persistence in the application, we need to introduce the persistence.xml, which has to be located in the META-INF directory in the project classpath.

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="JPATest"
transaction-type="RESOURCE_LOCAL">
<class><!-- Entity Class Name --></class>
</persistence-unit>
</persistence>

Here, the persistence unit name must be unique. Also, we can add multiple persistence-units for different units. The transaction type for this persistence unit is RESOURCE_LOCAL.

There are two types of transactions:

  • JTA: The transactions will be managed by the Application Server
  • RESOURCE_LOCAL: The transaction will be managed by the JPA Provider Implementation in use.

Also, specify the class name for entities in this configuration file. There is one more configuration used for the database connection. But for dynamic configuration of database connection, we add that configuration in Java code instead of this XML file.

EntityManager:

public class JpaEntityManager {
private EntityManagerFactory emFactoryObj;
private final String PERSISTENCE_UNIT_NAME = "JPATest";
private final Map<String, String> properties=new HashMap<String, String>();


// This Method Is Used To Retrieve The 'EntityManager' Object
public EntityManager getEntityManager() {

String url = String.format("%s/%s", DBConstants.DB_HOST, DBConstants.DB_NAME);

properties.put("javax.persistence.jdbc.driver",DBConstants.DB_DRIVER);
properties.put("javax.persistence.jdbc.url", url);
properties.put("javax.persistence.jdbc.user", DBConstants.DB_USER);
properties.put("javax.persistence.jdbc.password",DBConstants.DB_PASSWORD);
properties.put("useSSL", DBConstants.DB_USE_SSL);
properties.put("requireSSL", DBConstants.DB_REQUIRED_SSL);
properties.put("serverTimezone",DBConstants.DB_SERVER_TIMEZONE);

emFactoryObj = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME,properties);

return emFactoryObj.createEntityManager();
}
}

Here, you have to add your database related configuration like drive class name, hostname, database name, username, password, etc.

Database schema:

CREATE TABLE user (
  id INTEGER NOT NULL,
  name VARCHAR(255) NOT NULL,  
  age VARCHAR(100) NOT NULL,
  PRIMARY KEY(id)
);

Entity:

Here are some annotations used for JPA implementation.

1.) @Entity: to mark the java class as an entity.

2.) @Table: to specify the table to which this entity class maps.

3.) @Id: to identify a row uniquely (JPA Primary Key).

4.) @Column: to specify the mapped column for a persistent property or field.

**5. **<strong>JPARepository</strong>: used to perform database-related operations.

public class JpaRepository<T, ID> implements AutoCloseable {

private final Class<T> typeParameterClass;
protected EntityManager entityManager;

public JpaRepository(Class<T> typeParameterClass) {
JpaEntityManager dbEntityManager = new JpaEntityManager();
entityManager = dbEntityManager.getEntityManager();
this.typeParameterClass = typeParameterClass;
}
/**
 * Save an entity.
 * @param entity
 * @return the saved entity
 */
public <S extends T> S save(S entity) {
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.getTransaction().commit();
return entity;
}
/**
 * merge an entity.
 *
 * @param entity
 * @return the saved entity
 */
public <S extends T> S merge(S entity) {
entityManager.getTransaction().begin();
entityManager.merge(entity);
entityManager.getTransaction().commit();
return entity;
}
/**
 * Delete an entity
 * 
 * @param id
 */
public void delete(ID id) {
entityManager.remove(id);
}
/**
 * Returns a reference to the entity with the given identifier.
 * 
 * @param id
 * @return
 */
public T findById(ID id) {
T t = entityManager.find(typeParameterClass, id);
return t;
}
/**
 * get single result
 * 
 * @param q
 * @return
 */
public Optional<T> getSingleResult(CriteriaQuery<T> q) {

try {
return Optional.ofNullable(entityManager.createQuery(q).getSingleResult());
} catch (RuntimeException e) {
return Optional.empty();
}
}
/**
 * get single result
 * 
 * @param q
 * @return
 */
public Optional<List<T>> getResultList(CriteriaQuery<T> q) {
try {
return Optional.ofNullable(entityManager.createQuery(q).getResultList());
} catch (RuntimeException e) {
return Optional.empty();
}
}
/**
 * used to close entity manager obj
 */
public void close() {
entityManager.clear();
entityManager.close();
}
}

You can also use JPA Criteria API queries, which provide an alternative way for defining JPA queries and is mainly useful for building dynamic queries whose exact structure is only known at runtime.

Now, all configuration is done. So, let us start to test this application.

public class JPADemo {

public static void main(String[] args) {
User user=new User();
user.setId(1);
user.setAge(20);
user.setName("Abc");

try(JpaRepository userJpaRepository=new JpaRepository<BlenderMaster, Long>(BlenderMaster.class)){
userJpaRepository.save(user);
}catch (Exception e) {
e.printStackTrace();
}
}
}

Here, we added the JPA Repository resource in a try catch, so resource will be closed automatically after use. After running this application, one new user entry will be added in the MySQL database.

Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!

Further reading

Java Programming Masterclass for Software Developers

JSP, Servlets and JDBC for Beginners: Build a Database App

Java 8 New Features In Simple Way

Java In-Depth: Become a Complete Java Engineer!

Java for Absolute Beginners

Java Programming for Complete Beginners - Learn in 250 Steps

Learn Java Programming Crash Course

Apache Spark for Java Developers

#java #mysql #jpa #maven #database #api #web-development

Java Hibernate JPA Tutorial for Beginners (Eclipse + MySQL)

How to get started using Hibernate and JPA for developing database-driven applications in Java. You will see Hibernate makes it easier to code data access layer with Java.

Read text-based version here: http://www.codejava.net/frameworks/hibernate/java-hibernate-jpa-annotations-tutorial-for-beginners

#eclipse #mysql #java #jpa #hibernate

Samanta  Moore

Samanta Moore

1620458875

Going Beyond Java 8: Local Variable Type Inference (var) - DZone Java

According to some surveys, such as JetBrains’s great survey, Java 8 is currently the most used version of Java, despite being a 2014 release.

What you are reading is one in a series of articles titled ‘Going beyond Java 8,’ inspired by the contents of my book, Java for Aliens. These articles will guide you step-by-step through the most important features introduced to the language, starting from version 9. The aim is to make you aware of how important it is to move forward from Java 8, explaining the enormous advantages that the latest versions of the language offer.

In this article, we will talk about the most important new feature introduced with Java 10. Officially called local variable type inference, this feature is better known as the **introduction of the word **var. Despite the complicated name, it is actually quite a simple feature to use. However, some observations need to be made before we can see the impact that the introduction of the word var has on other pre-existing characteristics.

#java #java 11 #java 10 #java 12 #var #java 14 #java 13 #java 15 #verbosity