简体   繁体   中英

How can I properly annotate this relationship between two entities using Hibernate & Spring Data JPA?

Goal:

I am building a web app where there is an overview. In this overview, I load classifieds from a backend. Each classified has exactly one thumbnail.

First, the overview loads the classified, then it attempts to look up the associated thumbnail in the relevant Spring Data JPA Repository using the ID of the Classified.

Current state: The Classified table looks OK. The Thumbnail table is missing a reference to the Classified.

Desired state: I want the Thumbnail table to contain a reference to the ID of the classified, so that I can query the Thumbnail of a Classified.

ERD(~ish):

在此处输入图片说明

Entity classes:

Classified:

import javax.persistence.*;

@Entity
public class Classified {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String summary;
    private String description;

    public Classified() { }

    public Classified(String summary, String description) {
        this.summary = summary;
        this.description = description;
    }

    public long getId() {
        return id;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

Thumbnail:

import javax.persistence.*;

@Entity
public class Thumbnail {

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

    @OneToOne
    @JoinColumn(name = "id")
    private Classified classified;

    @Column(name="bytes", columnDefinition="VARBINARY(10000)")
    private byte[] bytes;

    public Thumbnail() {
    }

    public Thumbnail(Classified classified, byte[] bytes) {
        this.classified = classified;
        this.bytes = bytes;
    }
}

Tables (initiated with some sample data):

Classified: 在此处输入图片说明

Thumbnail: 在此处输入图片说明

You should change only the name of JoinColumn in the thumbnail class, for example:

@JoinColumn(name = "classifiedId",referencedColumnName = "id")
private Classified classified;

to give a name for the column

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM