Java EclipseLink Essentials

in #utopian-io7 years ago (edited)

What Will I Learn?

  • Basic JPA Configurations
  • Create tables from Java classes
  • Write CRUD methods

Requirements

  • Basic Java Knowledge
  • Basic Database Knowledge

Difficulty

  • Intermediate

Tools

  • Eclipse Neon
  • Oracle XE

Tutorial Contents

This tutorial focuses on introduction of EclipseLink. We are going to add libraries, configure persistence.xml, create data access object for a sample entity and do CRUD operations.

Essential Terminology

JPA (Java Persistence API) : As the name suggests, it's an API provided by Oracle to do database operations. Before JPA, every ORM tool (such as EclipseLink, TopLink, Hibernate) has its own rules. Now JPA supplies all ORM tools an API.

ORM (Object - Relational Mapping): As you know databases which we generally use has relational model and Java has object-oriented model. What ORM does is to bridge these two architectures. For instance when you create an object in Java, it is mapped as table in database. (We will use EclipseLink in this tutorial.)

JDBC Driver: JDBC Drivers create new database connections and operate them through commands. (We will use OJDBC since we use Oracle Database)

1. Create a New Workspace

create a workspace.png

2.New Project From Eclipse

First, create a new Project as usual but choose JPA Project this time.
2 - new jpa.png

Then write project name and don't change anything else.
2 - new jpa_2.png

In this part we need two things in Build Path. EclipseLink and OJDBC Driver. Choose Eclipse Link from the combo box above and click Download Library.
2 - new jpa_3.png

Choose EclipseLink's newest version and finish downloading. After downloading EclipseLink, download OJDBC jar from this link. Copy *.jar file to a stable path and click Manage Libraries now.
2 - new jpa_5.png

In the User Libraries page create a new library (I named "Ojdbc") and click "Add External JARs". Choose driver jar and finish.

Then click Add Connection. Choose Oracle, give a name to your connection and click New Driver Definition. Choose Oracle Thin Driver 11 and in the JAR List tab remove existing jar and add ojdbc jar.
2 - new jpa_6.png

In the properties tab, make this changes. (xe stands for my database name Oracle Express) After you fill textfields test your connection. If you got success message finish it. This connection will be listed in Eclipse Connections.
2 - new jpa_7.png

3. persistence.xml Configuration

In the Connection tab choose transaction type as Resource Local and click Populate from connection and choose your connection from the list.
In the Schema Generation choose Database Action as Drop and Create.

4. Create YourFirst Entity

Up to now we added our libraries, created a workspace and started project. Now we will create an entity that will be mapped as table in database. Right click on your project and create a JPA Entity.
3-entity_1.png

Add these three fields to your entity and select ID as Key.3-entity_2.png

When you finish your Entity class wil be created. Let me explain this. This JPA Entity is basically a Java Class. The only essential difference is that it has Entity annotation. It makes this class JPA entity, in other words mappable by database. That's all. Let's go on.
Another annotation in this class is Id. It makes sure Key field is unique. But ID need some configuration. Add these to lines to create sequence generator.

@Id
@SequenceGenerator(name="SEQ_GEN", allocationSize=1, initialValue=1)
@GeneratedValue(generator="SEQ_GEN", strategy=GenerationType.SEQUENCE)
5. Create Your DAO

At first, create an Interface names "ICrud" with T as generic under "com.daos" package. This interface will have our essential method signs. Write these in interface.

    public Boolean create(T entity);

    public T read(Long id);

    public Boolean update(T entity);

    public Boolean delete(Long id);

Now create a class named "ProductDao" and implement ICrud interface with PRODUCT entity name instead of T. Before filling method bodies write these codes in your class.

    EntityManagerFactory emf = null;
    EntityManager em = null;

    public ProductDao() {
        emf = Persistence.createEntityManagerFactory("SteemItDatabase");
        em = emf.createEntityManager();
    }

Finally, it's time to fill methods.

    @Override
    public Boolean create(PRODUCT entity) {
        try {
            em.getTransaction().begin();
            em.persist(entity);
            em.getTransaction().commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public PRODUCT read(Long id) {
        try {
            PRODUCT product = em.find(PRODUCT.class, id);
            return product;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Boolean update(PRODUCT entity) {
        try {
            em.getTransaction().begin();
            em.merge(entity);
            em.getTransaction().commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Boolean delete(Long id) {

        try {
            PRODUCT product = read(id);
            em.getTransaction().begin();
            em.remove(product);
            em.getTransaction().commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
5. Create - Read - Update - Delete

Create a test class.

Create
PRODUCT product = new PRODUCT();
product.setNAME("iPhone 7 Plus");
product.setTYPE("Smartphone");
new ProductDao().create(product);

When you run this code it will create a row.

create.png

Read
PRODUCT product = new ProductDao().read(1L);
System.out.println("Name:" + product.getNAME() + " Category:" + product.getTYPE());

When you run this code, it will give following output.

DQmQg88ydbZboMgy6F515tWhHP1fiPcgofNSeUSUn9AjbHc_1680x8400.png

Update
PRODUCT product = new ProductDao().read(1L);
        product.setNAME("iPhone 8");
        new ProductDao().update(product);

When you run this code, it will update Name field.

Delete
new ProductDao().delete(1L);

When you run this code, it will delete the row you want.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Coin Marketplace

STEEM 0.27
TRX 0.21
JST 0.039
BTC 97225.46
ETH 3729.86
USDT 1.00
SBD 3.91