Example:
import javax.persistence.*;
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
@Temporal(TemporalType.DATE)
@Column(name = "hire_date")
private Date hireDate;
@Transient
private String temporaryData;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
// Getters and setters omitted for brevity
}
@Entity
@Table(name = "departments")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name", nullable = false)
private String name;
@OneToMany(mappedBy = "department")
private List<Employee> employees;
// Getters and setters omitted for brevity
}
In this example:
@Entity
, @Table
, @Id
, @GeneratedValue
, @Column
, @Temporal
, and @Transient
annotations are used in the Employee
class.@ManyToOne
and @JoinColumn
annotations are used to establish a many-to-one relationship between Employee
and Department
entities.@OneToMany
annotation in the Department
class establishes a one-to-many relationship with Employee
entities, specifying the mappedBy attribute to refer to the field in the Employee
class that owns the relationship.