Basic CRUD Web Aplikasi Menggunakan SpringFramework-MVC, Freemarker, Hibernate dan JPA - JPA Entity Class

Article Index

JPA Entity Class

Perlu diingat, pada project ini kita tidak membuat database table terlebih dahulu. Kita memakai istilah microsoft dengan visual studionya, yaitu: Code First. Yang berarti, struktur table pada database dibuat melalui JPA entity class. Tetapi pada MySQL server kita telah membuat database kosong terlebih dahulu dengan nama db_jpacrud. Database user dan password juga telah kita konfigurasi pada MySQL server.

Sekarang marilah kita memulai membuat source code project web aplikasi JPA-CRUD. Dari Project Explorer pilih folder src/main/java, klik kanan pilih popup menuitem: New -> Package. Namai package tersebut dengan org.fajarapps.jpacrud.entity. Kemudian pilih folder tersebut dan klik kanan pilih popup menuitem: New -> Java Class. Beri nama class tersebut dengan Department. File Department.java akan otomatis dibuat pada package org.fajarapps.jpacrud.entity.

Source code Department.java.

package org.fajarapps.jpacrud.entity;

/* import ... tidak ditampilkan */
@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Table(name = "department", indexes = {@Index(name = "department_x1", columnList = "dept_name", unique = true)})
public class Department
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "dept_id")
    private Integer deptId;

    @Basic
    @NotEmpty(message = "{validation.field.notEmpty}")
    @Size(min = 3, max = 200, message = "{validation.field.size}")
    @Column(name = "dept_name", length = 200, nullable = false)
    private String deptName;

    @Basic
    @Column(name = "description", columnDefinition = "text")
    private String description;

    @Transient
    private Long numberOfPerson;

    @OneToMany(mappedBy = "department", fetch = FetchType.LAZY, targetEntity = Person.class)
    private Collection<Person> persons;

    /**
     * Class default constructor
     */
    public Department() {
    }

    /**
     * Class constructor.
     *
     * @param deptId Department identity
     * @param deptName Department name
     * @param description Description of department
     * @param numberOfPerson The number of employee within a department
     */
    public Department(Integer deptId, String deptName, String description, Long numberOfPerson) {
        this.deptId = deptId;
        this.deptName = deptName;
        this.description = description;
        this.numberOfPerson = numberOfPerson;
    }
/* method: getter, setter, equals, hashCode, dan toString ... tidak ditampilkan */
}

Masih pada package org.fajarapps.jpacrud.entity, buat class baru dengan nama Person. Berikut ini source code Person.java.

package org.fajarapps.jpacrud.entity;

/* import ... tidak ditampilkan */
@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Table(name = "person",
        indexes = {
                @Index(name = "person_x1", columnList = "fullname"),
                @Index(name = "person_x2", columnList = "dept_id"),
                @Index(name = "person_x3", columnList = "gender")
        })
@EntityListeners(AuditingEntityListener.class)
public class Person
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "person_id")
    private Long personId;

    @ManyToOne
    @NotNull(message = "{validation.field.notEmpty}")
    @JoinColumn(name = "dept_id", referencedColumnName = "dept_id", nullable = false)
    private Department department;

    @Basic
    @NotEmpty(message = "{validation.field.notEmpty}")
    @Size(min = 5, max = 200, message = "{validation.field.size}")
    @Column(name = "fullname", length = 200, nullable = false)
    private String fullname;

    @Basic
    @NotEmpty(message = "{validation.field.notEmpty}")
    @Column(columnDefinition = "text", nullable = false)
    private String address;

    @Basic
    @NotEmpty(message = "{validation.field.notEmpty}")
    @Size(min = 5, max = 250, message = "{validation.field.size}")
    @Column(length = 250, nullable = false)
    private String province;

    @Basic
    @Email(message = "{validation.invalid.emailAddress}")
    @Column(name = "email", length = 200)
    private String email;

    @Basic
    @Size(max = 50, message = "{validation.field.maxSize}")
    @Column(name = "home_phone", length = 50)
    private String homePhone;

    @Basic
    @Size(max = 50, message = "{validation.field.maxSize}")
    @Column(name = "work_phone", length = 50)
    private String workPhone;

    @Basic
    @Size(max = 50, message = "{validation.field.maxSize}")
    @Column(name = "mobile_phone", length = 50)
    private String mobilePhone;

    @Basic
    @Column(name = "birth_place", length = 250)
    private String birthPlace;

    @NotNull(message = "{validation.field.notEmpty}")
    @DateTimeFormat(pattern = "dd-MM-yyyy")
    @Temporal(TemporalType.DATE)
    @Column(name = "birth_date")
    private Date birthDate;

    @Basic
    @Enumerated(EnumType.STRING)
    @NotNull(message = "{validation.field.notEmpty}")
    @Column(length = 1, nullable = false)
    private Gender gender;

    @CreatedDate
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "ts_created", columnDefinition = "datetime")
    private Date tsCreated;

    @LastModifiedDate
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "ts_modified", columnDefinition = "datetime")
    private Date tsModified;

    @Version
    @Column(name = "version")
    private Integer version;

/* method: getter, setter, equals, hashCode, dan toString ... tidak ditampilkan */
}

Pada class Person ada satu data type yang tidak dikenal yakni Gender. Sekarang marilah kita membuat data type tersebut. Pilih folder src/main/java, dan buat package baru dengan nama org.fajarapps.jpacrud.domain.types. Masih pada Project Explorer popup menu, pilih popup menuitem: New -> Java Class. Isi field Name dengan Gender dan field Kind dengan Enum.

Melalui popup menuitem: New -> Java Class kita dapat membuat Enum, Interface dan sebagainya. Tetapi pada project ini kita hanya membuat Class, Enum dan Interface saja.

Berikut ini source code Gender.java.

package org.fajarapps.jpacrud.domain.types;

public enum Gender
{
    L("Laki-Laki"),
    P("Perempuan");

    private final String label;

    Gender(String name) {
        this.label = name;
    }

    public String getLabel() {
        return label;
    }
}