Friday, June 21, 2013

JPA table and column mappings tutorial

In the simplest case mapping an entity to a table needs only @Entity and @Id annotations to be specified. This approach is used if table and its columns names are identical to entity and its properties names.

But what if names are different?

This post is available in Russian.

Let's modify the application created in "JPA and Hibernate basics tutorial" post.

Create jpa_table_column_mappings_tutorial database and artists table with artist_id, artist_name and artist_genre columns:
CREATE DATABASE jpa_table_column_mappings_tutorial;
USE jpa_table_column_mappings_tutorial;

CREATE TABLE artists (
artist_id INT PRIMARY KEY,
artist_name VARCHAR(30),
artist_genre VARCHAR(20)
);

Now table and its columns names differ from entity and its properties names.
To map an entity to a table we should add @Table annotation with table name to Artist class.
To map entity properties to table columns we should add @Column annotation with column name to every entity property:
package com.jpa.table.column.mappings.tutorial.domain;

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

@Entity
@Table(name = "artists")
public class Artist {

    @Id
    @Column(name = "artist_id")
    private int id;

    @Column(name = "artist_name")
    private String name;

    @Column(name = "artist_genre")
    private String genre;

    public Artist() {

    }

    public Artist(int id, String name, String genre) {
        this.id = id;
        this.name = name;
        this.genre = genre;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGenre() {
        return genre;
    }

    public void setGenre(String genre) {
        this.genre = genre;
    }

    @Override
    public String toString() {
        return "Artist{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", genre='" + genre + '\'' +
                '}';
    }
}

Other application files remain unchanged.

JpaTableColumnMappingsTutorial class is similar to JpaHibernateBasicsTutorial class described in "JPA and Hibernate basics tutorial" post:
package com.jpa.table.column.mappings.tutorial;

import com.jpa.table.column.mappings.tutorial.domain.Artist;
import com.jpa.table.column.mappings.tutorial.service.ArtistService;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;

public class JpaTableColumnMappingsTutorial {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("JpaTableColumnMappingsTutorial");
        EntityManager em = emf.createEntityManager();
        ArtistService service = new ArtistService(em);

        System.out.println("--- Create and persist artist ---");
        em.getTransaction().begin();
        Artist artist = service.createArtist(1, "Franz Ferdinand", "Rock");
        em.getTransaction().commit();
        System.out.println(String.format("Persisted: %s\n", artist));

        System.out.println("--- Find artist ---");
        artist = service.findArtist(1);
        System.out.println(String.format("Found: %s\n", artist));

        System.out.println("--- Find all artists ---");
        List<Artist> artists = service.findAllArtists();
        for (Artist foundArtist : artists) {
            System.out.println(String.format("Found: %s\n", foundArtist));
        }

        System.out.println("--- Update artist ---");
        em.getTransaction().begin();
        artist = service.changeArtistGenre(1, "Indie Rock");
        em.getTransaction().commit();
        System.out.println(String.format("Updated: %s\n", artist));

        System.out.println("--- Remove artist ---");
        em.getTransaction().begin();
        service.removeArtist(1);
        em.getTransaction().commit();
        artist = service.findArtist(1);
        System.out.println(String.format("Found: %s\n", artist));
    }
}

Execute main() method:

















Application produced the same output as created in "JPA and Hibernate basics tutorial" post, which means we have successfully mapped entity and its properties with @Table and @Column annotations.

Folder structure:




Application source code is available at https://code.google.com/p/jpa-table-column-mappings-tutorial/.

Recommended posts:

4 comments:

  1. It's very easy to code that type de code
    but it's not easy to do a veritable project with gwt/spring/hibernate and using an entity containing a collection of other entities etc ...

    ReplyDelete
    Replies
    1. I think it depends on project and requirements. I've worked in one that successfully used Spring, Hibernate and Portlets frameworks and widely used entities with different collections using appropriate fetching strategies.

      Delete
  2. I've followed this tutorial.
    It's very helpfull.
    Thanks

    ReplyDelete