I am learning Java in 2020 – Beginner – Absolutely Simple Restaurant DB connection using JPA

Operation System : Windows 10

IDE : Eclipse IDE ( Java EE – 4.15.0 )

Java version : 12

Less complicated version : In Java and in Python

Requirements: Java installed, MySQL connector jar ( here) , MySQL

Optional : Eclipse Java EE IDE

Goal

Learn the java persistence architecture ( JPA )

Pseudo-code

  • Create a restaurants database
  • Create a menus table
  • Add new menus to the table
  • Display table on the command line

Terms I learned

Java

In this section I hope to regurgitate all I have learned recently while learning this programming language. There are still areas to explore that are not handled in this post. So bear with me.

JavaEE

I was and am still confused about the different “forms” of Java or subcategories,however after research ( googling) I understood that this form of java is a collection of classes used for building complex and large applications. Not a todo or calender type of application, more like an ecommerce store or logistic management software. Do not mistake this for a programming language like I did at the beginning. The programming language is Java while the Java EE is an API or ,as quoted here, provides an API.

Java SDK

Another confusing term, at least to me. Apparently the SDK stands for Software Development Kit. From the name we can deduce that it is simply a set of tools to aid you while developing in java.

JRE

The Java Runtime Environment is necessary for the setting up a java program. It ensures proper loading of all the resources, classes and other facets required for the program.So one can assume that without JRE you cannot run your “hello world” java program.

JVM

The Java Virtual Machine unlike the resource loader JRE helps us in executing our program. It also allows us to run our program independent of platform since it handles all the complexities behind the various operating systems. So it basically aids us big time, in much simpler terms. According to a stack overflow answer, the resources loaded by the JRE are used by JVM to run the program. Another point is, JVM lives or is created by the JRE. Weird right ?

JAR

I like to visualize it as a zip file/folder, since it holds many associated java classes and resources related to the program. Thus I do not think you can “run” it or is executable. It is simply a box of resources.

WAR

The web application resource file holds a collection of Jar files and other resources that are needed for a web application. So it is a bit more broader than a JAR file, I suppose.

API

During my software development learning journey, the most confusing term after “pointers” was the Application programming interface. Coming from a javascript background, I always assumed it meant the GET,POST, PUT, DELETE requests and nothing else. It isn’t just the calls or requests themselves, rather the tools, classes, methods, functions etc that allow our programs to interact with one another without knowing what goes on behind the curtains ( actual and more extensive implementation). There is an API for triggering a call directly from a website, an API that allows communication between a MySQL database and a java program. It saves us time, energy and brain resources during development. I like to imagine it as me ordering a chocolate cake at a bakery. I do not need to know the ingredients nor do I need to list out the ingredients. The bakers know immediately what I need because of the term “chocolate cake”. I get my cake without knowing how to make it.

Interfaces

With interfaces, we as programmers can define the blueprint of a class without giving it content. A class can use the blueprint by implementing the interface. I imagine an interface being the skeleton without the organs, skin etc. Several classes could implement the same interface but react differently based on their “content”.

JPA Architecture

The java persistence API allows for mapping plain java objects to database tables. They call this object relational mapping. Basic db actions such as create, update, read, delete can be executed in a less complicated manner via this API.

The following are annotations provided by the API, which will also be used in the tutorial below.

Annotations

Keep in mind that there are many more annotations. I just addressed those used in this post.

@Entity

Classes marked with this annotation represent a table in a relational database.

@Table

This allows us to define the name of the table already annotated with @Entity.

@Id

Each table has a primary key whose value remains unmodified once defined. The ID is the most common primary key, in my experience. With this annotation one could explicitly set a property/column of a table as the primary key by annotating with @id.

@GeneratedValue

If you need to configure the generation of the primary key, this will make it possible.

@Column

Other columns aside from the primary key will be needed, you can define them and configure their name using this annotation.

Java Persistence Query Language

It looks like SQL language but it is nahht. This is used to make queries against entity objects ( which correspond to the table), so actions such as fetch, delete, update are possible with this.

Persistence xml file

This file is stored in the META-INF folder and is primarily the configuration file for the JPA. I am yet to understand the components of the xml but in future posts, I will address it.

Static methods

These are methods that are accessible via the class and not the objects of the class. Because the context of a static method is not the object rather the class, it can only access static variables.

Development

Java Package

In this directory you will find subdirectories also known as subpackages. These packages contain java classes. The path of a package is its name together with all the names of its parent packages. A java class’s path is also arranged that way.

backend
	src
		com
			Learnjava
   model
		Book.java

The full path of model will be:

com.learnjava.model

While book.java :

com.learnjava.model.Book

Note that the src directory is not a java package, but subdirectories are the packages. Furthermore, do not forget to declare that the class belongs to a specific package. For example, the following line has to be appended right before the public class Book{ .

package com.learnjava.model

Concept

Meal table columns

Id

primary key, not null, auto-increment , unique , required

Number_sold

int, default = 0, not null

Dish_price

float , not null , required

Dish_name

varchar , not null, required

Actions/ Services

printTable

print out all the rows of the table

populateTable

add content to the table

Solution

Run MySQL Server from Command Line

If you have WAMP already installed, you can simply switch it on since it does it for you. Otherwise find the mysqld executable ( mysqld.exe) in your installed mysql source directory. Test it by running mysql on the cmd e.g. mysql –user root .

Config File

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" 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_2.xsd">
	<persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
		<class>com.tutorialspoint.eclipselink.entity.Menu</class>
		<properties>
			<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/restaurants?&serverTimezone=UTC"/>
			<property name="javax.persistence.jdbc.user" value="root"/>
			<property name="eclipselink.logging.level" value="FINE"/>
			<property name="eclipselink.ddl-generation" value="create-tables"/>
		</properties>
	</persistence-unit>
</persistence>

Menu Entity

package com.tutorialspoint.eclipselink.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity  @Table(name="menus")
public class Menu {
	@Id 
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;
	
	@Column(name="name", nullable=false, length=50)
	private String dish_name;
	
	@Column(name="price", nullable=false, precision=3)
	private float dish_price = (float) 0.0;
	
	@Column(name="sold", nullable=false)
	private int number_sold = 0;
	
	
	
	public int getId() {
		return this.id;
	}
	public void setId(int newid) {
		this.id = newid;
	}
	public String getName() {
		return this.dish_name;
	}
	public void setName(String name) {
		this.dish_name = name;
	}
	public float getDishPrice() {
		return this.dish_price;
	}
	public void setDishPrice(float dishPrice) {
		this.dish_price = dishPrice;
	}
	public int getNumberSold() {
		return this.number_sold;
	}
	public void setNumberSold(int sold) {
		this.number_sold = sold;
	}
	public String printRow() {
		return "| "  + this.id + " | " + this.dish_name + " | " + this.dish_price + " | " + this.number_sold;
	}
}

Services

Add data to tables

package com.blog.jpa.restaurant;



import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.tutorialspoint.eclipselink.entity.Menu;


public class PopulateTable {
	
	
	public static void main(String[] args) {
		
		
			EntityManagerFactory entitymanagerfactory = Persistence.createEntityManagerFactory("Eclipselink_JPA");
			EntityManager entitymanager = entitymanagerfactory.createEntityManager();
			entitymanager.getTransaction().begin();
			String[][] values = {{"Egusi Soup and Eba", "24.5"}, { "Porridge Yam", "12"}, {"Porridge Beans", "13"}};
			for (int i = 0; i < values.length; i++) {
				
					String[] row = values[i];
					String dishName = row[0];
					String dishPrice = row[1];
					float floatDishPrice = Float.parseFloat(dishPrice);
					Menu menu = new Menu();
					menu.setName(dishName);
					menu.setDishPrice(floatDishPrice);
					
					entitymanager.persist(menu);
					
					
			}
			entitymanager.getTransaction().commit();
			entitymanager.close();
			entitymanagerfactory.close();
			
	}
}

Display table

package com.blog.jpa.restaurant;

import java.util.Collection;
import java.util.Iterator;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.tutorialspoint.eclipselink.entity.Menu;

public class PrintTable {
	public static void main(String[] args) {
		
		
		EntityManagerFactory entitymanagerfactory = Persistence.createEntityManagerFactory("Eclipselink_JPA");
		EntityManager entitymanager = entitymanagerfactory.createEntityManager();
		Query query = entitymanager.createQuery("SELECT e FROM Menu e");
		Collection<Menu> menus =   query.getResultList();
		Iterator<Menu> iterator = menus.iterator();
		while(iterator.hasNext()) {
			
				String row = iterator.next().printRow();
				System.out.println(row);
				
		}
		
	
}
}

Result

If you are using eclipse, simply click the green arrow button with the print table service class open.

| 1 | Egusi Soup and Eba | 24.5 | 0
| 52 | Porridge Yam | 12.0 | 0
| 53 | Porridge Beans | 13.0 | 0
| 51 | Egusi Soup and Eba | 24.5 | 0
What have I observed ?

This solution looks significantly cleaner and more direct to the point compared to this.

Author Notes

This is most likely not the cleanest implementation, just a heads up.

Full Code

here

Links

  1. Building Back-End Web Apps with Java, JPA and JSF
  2. JPA Entity Classes
  3. Java Enterprise Edition (Java EE)
  4. Differences between JDK and Java SDK
  5. What is the JRE? Introduction to the Java Runtime Environment
  6. What is the difference between the JRE and JVM?
  7. JAR (file format)
  8. WAR (file format)
  9. Summary of Implementations
  10. Introduction to JPA Architecture
  11. Entities
  12. Annotation Type GeneratedValue
  13. Java Persistence Query Language
  14. A beginner’s guide to JPA persistence.xml file
  15. What Is Java Static Method?
  16. Defining JPA Entities
  17. Default Column Values in JPA
  18. javax.persistence.Column – JPA annotation
  19. java : convert float to String and String to float
  20. How do persist and merge work in JPA
  21. Iterating through a Collection in Java