How can I implement an Enum with JPA using separate Mysql Tables

I'm really new using JPA and still dont get how to achieve this, I would be glad to any suggestion or solution.

Mysql tables:

CREATE TABLE REAL_STATE_TYPES (
real_state_type_id INT(6) NOT NULL,
real_state_type VARCHAR(50) NOT NULL,
PRIMARY KEY (real_state_type_id)
);

CREATE TABLE REAL_STATES (
address VARCHAR(30) NOT NULL,
admin_id VARCHAR(15) NOT NULL,
real_state_type_id INT(6) NOT NULL,
block VARCHAR(3) NOT NULL,
internal_id INT(5) NOT NULL,
PRIMARY KEY (address, block, internal_id),
FOREIGN KEY (real_state_type_id) REFERENCES REAL_STATE_TYPES (real_state_type_id),
FOREIGN KEY (admin_id) REFERENCES ADMINS (admin_id)
);

so REAL_STATE has the id of REAL_STATE_TYPE, if I would want to keep this table's relationship how can I map them in the java code through JPA.

My java classes are:

import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name= "real_state_types")
public class RealStateType implements Serializable{

    private static final long serialVersionUID = 5442745398170857199L;
    @Id
    @Column(name= "real_state_type_id ")
    private int realStateTypeId;
    @Column(name= "real_state_type")
    @Enumerated(EnumType.STRING)
    private RealStateEnum realStateType;
    @OneToOne(mappedBy = "realStateType", cascade = {CascadeType.ALL})
    private RealState realState;

And:

import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "real_states")
public class RealState {
    @EmbeddedId
    private RealStateID realStateID;
    @Column(name = "real_state_type_id")
    private RealStateType realStateType;
    @ManyToOne
    @JoinColumn(name = "admin_id")
    private Admin admin;
}


Read more here: https://stackoverflow.com/questions/67538924/how-can-i-implement-an-enum-with-jpa-using-separate-mysql-tables

Content Attribution

This content was originally published by Clown at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: