JPA: Entity Relationships Mapping Example

  • The direction of a relationship can be
    bidirectional–owning side and inverse side
    unidirectional–owning side only
  • Owning side specifies the physical mapping
    CascadeType(ALL, PERSIST, MERGE, REMOVE, REFRESH)
    FetchType(LAZY, EAGER)

bidirectional @one to many

@Entity
@Table(name = "course")
public class Course {
    /** Attributes for Course **/
    @Id
    @Column(name = "courseid")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int courseId;
    
    @Basic
    @Column(name = "employeeid")
    private String employeeId;
    
    @Column(name = "coursename")
    private String courseName;
    
    @Temporal(TemporalType.DATE)
    @Column(name = "fromdate")
    @DateTimeFormat(pattern = "dd/MM/yyyy")
    private Date fromDate;
    
    @NotNull
    @Column(name = "gstincluded", nullable = false, columnDefinition = "TINYINT", length = 1)
    private boolean gstIncluded;
    
    /** Container for CourseApplicationActions **/
    @OneToMany(mappedBy="course", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    /**Owning side(mappedBy) specifies the physical mapping (CascadeType & FetchType)**/
    private List<CourseEvent> courseEvent = new ArrayList<CourseEvent>();
    
    ...
}

CourseEvent

@Entity
public class CourseEvent {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "courseeventid")
    private int courseEventId;
    
    // Reverse Relation
    @ManyToOne
    @JoinColumn(name = "courseid")
    private Course course;
    
    ... 
}

Many to Many

@Entity
public class Author {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @Column(name = "full_name", nullable = false)
    private String fullName;

    @ManyToMany(mappedBy = "authors")
    private List<Book> books = new ArrayList<>();

}
@Entity
public class Book {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @Column(name = "title", nullable = false)
    private String title;

    @ManyToMany
    @JoinTable(name = "Book_Author",
        joinColumns = {
            @JoinColumn(
                name = "book_id", 
                referencedColumnName = "id"
            )
        },
        inverseJoinColumns = {
            @JoinColumn(
                name = "author_id", 
                referencedColumnName = "id"
            )
        }
    )
    private List<Author> authors = new ArrayList<>();
}

user

@Entity
@Table(name = "user")
public class User {
    //persistence attribute and Transient
    @Id
    @Column(name = "userid")
    private String userId;
    
    @ManyToMany(targetEntity = Role.class, cascade = CascadeType.ALL, fetch=FetchType.EAGER)
    @JoinTable(name = "userrole", 
    joinColumns = {@JoinColumn(name = "userid", referencedColumnName = "userid") }, 
    inverseJoinColumns = {@JoinColumn(name = "roleid", referencedColumnName = "roleid") })
    private List<Role> roleSet;
    
    @Transient
    private ArrayList<String> roleIds = new ArrayList<String>();
    
    //constructor
    public User() {
    }

    public User(String userId) {
        this.userId = userId;
    }
    
    //getter & setter
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    
    public List<Role> getRoleSet() {
        return roleSet;
    } 
    public void setRoleSet(ArrayList<Role> roleSet) {
        this.roleSet = roleSet;
    }

    public ArrayList<String> getRoleIds() {
        ArrayList<Role> rList = (ArrayList<Role>) this.getRoleSet();
        ArrayList<String> roleIds = new ArrayList<String>();
        for (Role role : rList) {
            roleIds.add(role.getRoleId());
        }
        return roleIds;
    }
    public void setRoleIds(ArrayList<String> roleIds) {
        this.roleIds = roleIds;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,482评论 0 23
  • 孩子们,陪伴呵护我们的爸妈咱们是最熟悉不过啦。你眼中的爸妈是怎样的呢?这不,瞧瞧咱们的靓妈俊爸在孩子们的眼中是怎样...
    陌上花gyx阅读 3,738评论 0 0
  • 1.4 健身 注意~每个人身体条件不同,动作准确与否的判断依据应是目标部位感觉强烈。 1.前弓步 30*3 左腿不...
    Julie30阅读 1,430评论 0 0