JPA Mapping Examples..

Just a few of them..

One To One

@Entity
@Table(name = "customer")
public class Customer {
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int customer_id;
 
    @OneToOne(targetEntity = Address.class)
    @JoinColumn(name = "address_id")
    private Address address;
 
@SuppressWarnings("UnusedDeclaration")
@Entity
@Table(name = "address")
public class Address {
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int address_id;
 
    @OneToOne(mappedBy = "address", targetEntity = Customer.class)
    private Customer customer;

One To Many

@Entity
@Table(name = "address")
public class Address {
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int address_id;
 
    @Basic
    private String address;
 
    @ManyToOne(targetEntity = City.class)
    @JoinColumn(name = "city_id")
    private City city;
 
@Entity
@Table(name = "city")
public class City {
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int city_id;
 
    @OneToMany(mappedBy = "city", targetEntity = Address.class)
    private List<Address> addressList;

Many To Many

@Entity
public class Actor {
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int actor_id;
 
    @ManyToMany
    @JoinTable(name = "film_actor",
            joinColumns = @JoinColumn(name = "actor_id"),
            inverseJoinColumns = @JoinColumn(name = "film_id")
    )
    private Collection<Film> films;
 
@Entity
@Table(name = "film")
public class Film {
 
    @Id
    private int film_id;
 
    @ManyToMany
    @JoinTable(name = "film_actor",
        joinColumns = @JoinColumn(name = "film_id"),
        inverseJoinColumns = @JoinColumn(name = "actor_id")
    )
    private Collection<Actor> actors;