Mapping domain objects using JPA

Take a look at the following steps to learn about mapping the domain objects:

  1. Let's begin by mapping our Event.java file so all the domain objects will use JPA, as follows:
//src/main/java/com/packtpub/springsecurity/domain/Event.java

import javax.persistence.*;
@Entity
@Table(name = "events")
public class Event implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@NotEmpty(message = "Summary is required")
private String summary;
@NotEmpty(message = "Description is required")
private String description;
@NotNull(message = "When is required")
private Calendar when;
@NotNull(message = "Owner is required")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="owner", referencedColumnName="id")
private CalendarUser owner;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="attendee", referencedColumnName="id")
private CalendarUser attendee;
  1. We need to create a Role.java file with the following contents:
//src/main/java/com/packtpub/springsecurity/domain/Role.java

import javax.persistence.*;
@Entity
@Table(name = "role")
public class Role implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "roles")
private Set<CalendarUser> users;
  1. The Role object will be used to map authorities to our CalendarUser table. Let's map our CalendarUser.java file, now that we have a Role.java file:
//src/main/java/com/packtpub/springsecurity/domain/CalendarUser.java

import javax.persistence.*;
import java.io.Serializable;
import java.util.Set;
@Entity
@Table(name = "calendar_users")
public class CalendarUser implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String firstName;
private String lastName;
private String email;
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_role",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;

At this point, we have mapped our domain objects with the required JPA annotation, including @Entity and @Table to define the RDBMS location, as well as structural, reference, and association mapping annotations.

The application will not work at this point, but this can still be considered a marker point before we continue on to the next steps of conversion.

You should be starting with the source from chapter05.02-calendar.