Wednesday, March 19, 2014

JPA and MySQL... quick smart guide(with Eclipse)

Here are to configure a small eclipse project to run JPA capabilities on a mysql database.....

My current configuration is:
JDK 1.6
Eclipse Kepler for JavaEE developer
MySql 5.5
Mysql_jdbc_connector (to connect your java application to mysql db)
EclipseLink 2.5 (provides advanced support for leading relational databases)
all on my Debian Wheezy.....

1)Under Eclipse, create a new "JPA Project".
Insert a custom name. Leaves all the default settings(none target runtime, JPA Version 2.1, Basic JPA Configuration).
Going ahead, setting "EclipseLink 2.5.x" in the Platform combo menu.
Next in the JPA Implementation menu select User Library, then with the button image "Manage Libraries" create twe variables with the relative mapping to three libraries, as above:
-  ECLIPSELINK alias variable that points to $ECLIPSELINK_HOME_DIR/*.jar (where *.jar means some of the libraries under the $ECLIPSELINK_HOME_DIR folder and his subfolders, please see the image above)
- MYSQL_CONNECTOR alias variable that points to $MY_SQL_CONNECTOR_HOME_DIR/mysql-connector-java-5.1.29-bin.jar

Alternatives to the manual mapping of the ECLIPSELINK jars you can click instead on the "Download library..." button and select the version of your Eclipse IDE installed(in this case Eclipse Kepler).
This procedure is automatic and avoids also to download manually the EclipseLink .zip file.



Under the Connection combo menu, click on the "Add connection..."
Select MySQL, Next, Near the Drivers combo menu click on "New Driver Definition".
Under the "Name/Type" tab, select MySQL JDBC Driver, with System Version 5.1.
Under the "JAR List" tab, click on the only showed mysql-connector-java-5.1.0-bin.jar and click on the right on the "Edit JAR Zip..." button.
Select the mysql-connector that you have previously downloaded....
Then click on OK.
Insert your database connection info....:
database name(custom)
URL(complete URL) --> jdbc:mysql://your_database_ip:3306/your_db_name
User name: your db applicative user name
Password: your db applicative password
Click on "Save password" check box
and on the right click on the "Test Connection" button.
Go ahead only if you have a correct response to this db test connection...
If no, solve before this problem. You must have the connection working...


 Then click on "Finish" button.

2) This is an example script used to create my custom table Users
CREATE TABLE Users (
        id INT(5) NOT NULL AUTO_INCREMENT,
        username VARCHAR(20) NOT NULL,
        email    VARCHAR(40) NOT NULL,
        password VARCHAR(20) NOT NULL,               
        PRIMARY KEY(id)
); 

3)This is the content of my persistence.xml(under src/META-INF folder)
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
     version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
     <persistence-unit name="JPATestProject" transaction-type="RESOURCE_LOCAL">
          <class>com.bean.User</class>
          <properties>
              <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/your_db_name"/>
              <property name="javax.persistence.jdbc.user" value="your_db_user_name"/>
              <property name="javax.persistence.jdbc.password" value="db_user_password"/>
              <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
          </properties>
     </persistence-unit>
</persistence>

4)I create 2 classes.
One to map the Users db table.
It is com.bean.User class and contains this:

package com.bean;

import java.io.Serializable;
import java.lang.String;
import javax.persistence.*;

/**
 * Entity implementation class for Entity: User
 * @author Maurizio Franco
 *         http://maurizio-franco.blogspot.it
 *         maurizio.franco@ymail.com

 */
@Entity
@Table(name="Users")
public class User implements Serializable {

      
    @Id @GeneratedValue
    (strategy=GenerationType.IDENTITY)
    private int id;
   
    private String username;
    private String password;
    private String email;
    private static final long serialVersionUID = 1L;

    public User() {
        super();
    }  
    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }  
    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }  
    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }  
    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
  
}

5) The other is the class that tests if all the game works...
com.test.Test is the class and contains this....:

package com.test;

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

import com.bean.User;


/**
 *
 * @author Maurizio Franco
 *         http://maurizio-franco.blogspot.it
 *         maurizio.franco@ymail.com

 *
 */ public class Test {

    private static final String PERSISTENCE_UNIT_NAME = "JPATestProject";
   

    public static void main(String[] args) {
        EntityManagerFactory emf =
                Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
            EntityManager em = emf.createEntityManager();
                        
              //INSER new User
              em.getTransaction().begin();
              User appo = new User () ;
                       
             
              appo.setUsername("username123AAABBB");
              appo.setEmail("provaJPA_123");             
              appo.setPassword("password123");   
              em.persist(appo);            
              em.flush();
              em.getTransaction().commit();
              em.close();
             
              System.out.println("Inserted new User.... with username: " + appo.getUsername() + " - email: " + appo.getEmail());
             
             
//              //SELECT for id.....
//              int userId = 26 ;
//              appo = (User) em.find(User.class, userId);
//             
//              System.out.println("username: " + appo.getUsername() + " - email: " + appo.getEmail());
             
    }

}


Now you are ready to go....:-)

Run Test class and provides to do the insert test of a new User object.

 
Refer to this oracle documentation for other Accessing a JPA Entity using an EntityManager. Or the other Entity Manager capabilities....

Refer to these other links.... Eclipse info, eclipseLink JPA configuration, EclipseLink JPA Examples.


Bye....

PS.: You find the small project of above, available for anonymous download under source forge....
The url to point to checkout is this(ready to run under Eclipse with anonymous username and no password required) :
svn://svn.code.sf.net/p/mauriziofranco/code/StartingWithJPA/trunk/StartingWithJPA
Or you can checkout from command line with this:
svn checkout svn://svn.code.sf.net/p/mauriziofranco/code/StartingWithJPA/trunk/StartingWithJPA mauriziofranco-code

P.P.S.: remember to customize the persistence.xml....

Have a good job.....

3 comments:

  1. Hi, thanks for posting this article! I'm hosting a website in GAE and had some issues running all the JPA features.

    I was able to access entities, but never entities with subqueries or Lists using the @ManyToOne tags. I had to implement my own iterators to retrieve data from related tables.

    Anyway, I never really dove deeply into these issues, mainly because I wanted to switch over to a Compute Engine VM instance; which is what I'm working on right now.

    In my app, I need MySql, Java and JPA support, so I figured I should install Tomcat in order to kill 2 birds with 1 stone, so I would have both java and the apache configured to work properly.

    You don't mention installing tomcat here, but is it implied? What do you recommend for my setup?

    Best regards,
    sb

    ReplyDelete
  2. By the way, my VM is also a Debian Wheezy instance

    ReplyDelete
  3. Hi Sergio,

    sorry for my late response....
    But as you will have certainly already done, installing tomcat is really easy.
    It's a simple archive file to explode. Then, into bin folder, you find startup and shutdown commands to start/stop it.
    This is the quick mode to run tomcat.
    Next step is to know how you need to configure....

    Good luck... and bye...

    ReplyDelete