JPA Standalone Example with Many to Many..

.. using the Sakila Database!


Prerequisities

Make sure you are running MySQL Server in your local with Sakila database loaded..

Here is my directory layout..

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
 
    <modelVersion>4.0.0</modelVersion>
    <packaging>jar</packaging>
 
    <groupId>biz.tugay</groupId>
    <artifactId>learningjpa</artifactId>
    <version>1.0-SNAPSHOT</version>
 
    <dependencies>
 
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.1.1</version>
        </dependency>
 
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.1.0.Final</version>
            <scope>runtime</scope>
        </dependency>
 
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.1.0.Final</version>
            <scope>runtime</scope>
        </dependency>
 
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>5.1.0.Final</version>
            <scope>runtime</scope>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
            <scope>runtime</scope>
        </dependency>
 
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
            <scope>runtime</scope>
        </dependency>
 
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
             version="2.1">
    <persistence-unit name="testdb" transaction-type="RESOURCE_LOCAL">
        <properties/>
    </persistence-unit>
</persistence>

hibernate.properties
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/sakila
hibernate.connection.username=root
hibernate.connection.password=root
hibernate.connection.useUnicode=true
hibernate.connection.characterEncoding=utf-8
hibernate.show_sql=false
hibernate.hbm2ddl.auto=update
 
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=10
hibernate.c3p0.timeout=300
hibernate.c3p0.max_statements=5
hibernate.c3p0.unreturnedConnectionTimeout=2

PersistenceUtil.java
package biz.tugay.learningjpa;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 10/16/2016
 * Time: 4:06 PM
 */
public class PersistenceUtil {
 
    private static EntityManagerFactory entityManagerFactory;
 
    private PersistenceUtil() {
        // Do not allow initialization!
    }
 
    public static void openFactory() {
        entityManagerFactory = Persistence.createEntityManagerFactory("testdb");
    }
 
    public static EntityManager getEntityManager() {
        final EntityManager entityManager = entityManagerFactory.createEntityManager();
        return entityManager;
    }
 
    public static void closeFactory() {
        entityManagerFactory.close();
    }
}

Actor.java
package biz.tugay.learningjpa.model;
 
import javax.persistence.*;
import java.util.Collection;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 10/23/2016
 * Time: 9:49 AM
 */
 
@Entity
public class Actor {
 
    private Integer id;
    private String firstname;
    private String lastname;
 
    private Collection<Film> films;
 
    @Id
    @Column(name = "actor_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer actor_id) {
        this.id = actor_id;
    }
 
    @Basic
    @Column(name = "first_name")
    public String getFirstname() {
        return firstname;
    }
 
    public void setFirstname(String first_name) {
        this.firstname = first_name;
    }
 
    @Basic
    @Column(name = "last_name")
    public String getLastname() {
        return lastname;
    }
 
    public void setLastname(String last_name) {
        this.lastname = last_name;
    }
 
    @ManyToMany
    @JoinTable(name = "film_actor",
            joinColumns = @JoinColumn(name = "actor_id"),
            inverseJoinColumns = @JoinColumn(name = "film_id")
    )
    public Collection<Film> getFilms() {
        return films;
    }
 
    public void setFilms(Collection<Film> films) {
        this.films = films;
    }
}

Film.java
package biz.tugay.learningjpa.model;
 
import javax.persistence.*;
import java.util.Collection;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 10/23/2016
 * Time: 10:03 AM
 */
 
@Entity
public class Film {
 
    private Integer id;
    private String title;
 
    private Collection<Actor> actors;
 
    @Id
    @Column(name = "film_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer film_id) {
        this.id = film_id;
    }
 
    @Basic
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    @ManyToMany
    @JoinTable(name = "film_actor",
            joinColumns = @JoinColumn(name = "film_id"),
            inverseJoinColumns = @JoinColumn(name = "actor_id"))
    public Collection<Actor> getActors() {
        return actors;
    }
 
    public void setActors(Collection<Actor> actors) {
        this.actors = actors;
    }
}

BasePersistenceTest.java
package biz.tugay.learningjpa;
 
import org.junit.After;
import org.junit.Before;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 10/23/2016
 * Time: 10:12 AM
 */
public class BasePersistenceTest {
 
    @Before
    public void init() {
        PersistenceUtil.openFactory();
    }
 
    @After
    public void destroy() {
        PersistenceUtil.closeFactory();
    }
}

ActorTest.java
package biz.tugay.learningjpa;
 
import biz.tugay.learningjpa.model.Actor;
import biz.tugay.learningjpa.model.Film;
import org.junit.Test;
 
import javax.persistence.EntityManager;
import java.util.Collection;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 10/23/2016
 * Time: 9:56 AM
 */
public class ActorTest extends BasePersistenceTest{
 
    @Test
    public void testGetFilmsOfActorWithId() {
        final EntityManager entityManager = PersistenceUtil.getEntityManager();
        final Actor actor = entityManager.find(Actor.class, 1);
        final Collection<Film> films = actor.getFilms();
        for (Film film : films) {
            System.out.println(film.getTitle());
        }
    }
}

FilmTest.java
package biz.tugay.learningjpa;
 
import biz.tugay.learningjpa.model.Actor;
import biz.tugay.learningjpa.model.Film;
import org.junit.Test;
 
import javax.persistence.EntityManager;
import java.util.Collection;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 10/23/2016
 * Time: 10:13 AM
 */
public class FilmTest extends BasePersistenceTest {
 
    @Test
    public void testGetActorsOfFilmWithId() {
        final EntityManager entityManager = PersistenceUtil.getEntityManager();
        final Film film = entityManager.find(Film.class, 1);
        final Collection<Actor> actors = film.getActors();
        for (Actor actor : actors) {
            System.out.println(actor.getFirstname() + " " + actor.getLastname());
        }
    }
}

In Action
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running biz.tugay.learningjpa.ActorTest
ACADEMY DINOSAUR
ANACONDA CONFESSIONS
ANGELS LIFE
BULWORTH COMMANDMENTS
CHEAPER CLYDE
COLOR PHILADELPHIA
ELEPHANT TROJAN
GLEAMING JAWBREAKER
HUMAN GRAFFITI
KING EVOLUTION
LADY STAGE
LANGUAGE COWBOY
MULHOLLAND BEAST
OKLAHOMA JUMANJI
RULES HUMAN
SPLASH GUMP
VERTIGO NORTHWEST
WESTWARD SEABISCUIT
WIZARD COLDBLOODED
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.825 sec
 
Running biz.tugay.learningjpa.FilmTest
PENELOPE GUINESS
CHRISTIAN GABLE
LUCILLE TRACY
SANDRA PECK
JOHNNY CAGE
MENA TEMPLE
WARREN NOLTE
OPRAH KILMER
ROCK DUKAKIS
MARY KEITEL
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.14 sec
 
Results :
 
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.594 s
[INFO] Finished at: 2016-10-23T11:49:50+03:00
[INFO] Final Memory: 15M/225M
[INFO] ------------------------------------------------------------------------
 
Process finished with exit code 0