JPA in Eclipse and MySQL. Simple example: Main program to write and read a database table

I show you how to create a JPA program in Eclipse accessing a simple MySQL Employee table. A main method writes a new record to that table, then retrieve all records. No internet drivers, no web server stuff, no Java EE. Basic example. (No Hello World!!!)

Assumes you know how to create a:
– database in MySQL, and you have one already created.
– connection to that database in Eclipse, and have done so.
– table in it: (I give you SQL statements which I use in phpmyadmin)
– (driver for MySQL is assumed to be working, and I show you how to download and include EclipseLink driver; no other dependencies!!! Yay!)

Tutorial Eclipse JPA MySQL:

1. mysql: create and populate a table:

CREATE TABLE employees (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30),
started INT
);

INSERT INTO employees (name, started) VALUES
(‘John Smith’, 2014),(‘Mary Doe’, 2017),(‘Frank Jones’, 2016);

SELECT * FROM employees;

 

2. (make a connection in Eclipse to this)

3. New JPA project/ Project name: jpa-eclipse-mysql / Next/Next/Platform: EclipseLink 2.5.x/ JPA Implementation: Type: User Library/ EclipseLink 2.5.2 (you may have to click the little “download library” icon to the right/ Connection (select the connection that you created in step 2)/ Add driver library to build path/Finish

4. New/JPA Entities from Table/ Select Employees table/ Next/ Next (skip the Table Associations stuff)/ Key generator: Identity/ Package:mystuff/Finish

5. Create mystuff.EMF.java with (Note that, in this file, I’m using jpa-eclipse-mysql because when I created the project with that name, Eclipse generated that same name in persistence.xml (persistence unit name):
package mystuff;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public final class EMF {
private static final EntityManagerFactory emfInstance =
Persistence.createEntityManagerFactory(“jpa-eclipse-mysql”);

private EMF() {}

public static EntityManagerFactory get() {
return emfInstance;
}
}

6. create mystuff.MyMain.java:
package mystuff;

import java.util.List;
import javax.persistence.*;

public class MyMain {

public static void main(String[] args) {

System.out.println(“Hello…”);

EntityManager em = EMF.get().createEntityManager();

Employee employee = new Employee();
employee.setName(“Tom Stevens”);
employee.setStarted(2017);

System.out.println(“writing newly created object as a database record…”);
// store current one
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(employee);
em.flush();
tx.commit();
System.out.println(“one written.”);

System.out.println(“\nretrieving all records…”);
Query q = em.createQuery(“select e from Employee e”);
// type safety warning left as an exercise for you:
List<Employee> lis = q.getResultList();
System.out.println(“found:” + lis.size());
for (Employee e: lis) {
System.out.println(“found:” + e.getId() + ‘ ‘ + e.getName() + e.getStarted());
}
System.out.println(“all retrieved.”);

em.close();
System.out.println(“bye!”);
}
}

 

7. Add your database connection info to properties in persistence.xml so it has 4 new properties 1. the driver, 2. the database name 3. the username for that database 4. the password. Mine now says:
<?xml version=”1.0″ encoding=”UTF-8″?>
<persistence version=”2.1″ xmlns=”http://xmlns.jcp.org/xml/ns/persistence&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd”&gt;
<persistence-unit name=”jpa-eclipse-mysql”>
<class>mystuff.Employee</class>

<properties>
<property name=”javax.persistence.jdbc.driver” value=”com.mysql.jdbc.Driver” />
<property name=”javax.persistence.jdbc.url” value=”jdbc:mysql://localhost:3306/flashcardsquiz” />
<property name=”javax.persistence.jdbc.user” value=”flashcardsquiz” />
<property name=”javax.persistence.jdbc.password” value=”password” />
</properties>

</persistence-unit>
</persistence>

8. Right click on MyMain.java, run as a java application. Here’s my output:

Hello…
[EL Info]: 2017-10-15 20:21:53.677–ServerSession(351962798)–EclipseLink, version: Eclipse Persistence Services – 2.5.2.v20140319-9ad6abd
Sun Oct 15 20:21:54 EDT 2017 WARN: Establishing SSL connection without server’s identity verification is not recommended.
Sun Oct 15 20:21:54 EDT 2017 WARN: Establishing SSL connection without server’s identity verification is not recommended.
[EL Info]: connection: 2017-10-15 20:21:54.678–ServerSession(351962798)–file:/jpa-eclipse-mysql/build/classes/_jpa-eclipse-mysql login successful
writing newly created object as a database record…
one written.

retrieving all records…
found:4
found:1 John Smith2014
found:2 Mary Doe2017
found:3 Frank Jones2016
found:4 Tom Stevens2017
all retrieved.
bye!

If you found this useful, you might like to leave a thanks in a comment below. Share the luv! 🙂

 

Advertisements

About SunKing2

Former web developer, guitar player, started Piano 2012 -yes still doing it! Recovery, sobriety, mental health advocate.
This entry was posted in Eclipse, java, jpa, Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s