简体   繁体   中英

Hibernate annotation OnetoOne relationship

I have a critical issue. I have a table

TICKETINFO

TICKETINFOID pk, REMARK varchar(128), TICKETDATE timestamp

it has a corresponding class with hibernate annotation which somewhat looks like this

@Entity
@Table(name = "TICKETINFO")
public class Ticketinfo implements Serializable {

    @Id
    @Column(name = "TICKETINFOID")
    private Long id;
    @Column(name = "TICKETDATE")
    private String date;
    @column(name = "REMARK")
    private string remark;

    //getters and setters
}

now my work is that i need to create a child table of TICKETINFO table

TICKETINFO_REMARK

TICKETINFO_REMARK_ID pk, TICKETINFOID fk, REMARK varchar(128)

and TICKETINFOID will be foreign key from TICKETINFO table and have to populate the REMARK field of TICKETINFO_REMARK along with the REMARK field of TICKETINFO for the corresponding TICKETINFOID.

For 1 TICKETINFOID there will be one REMARK and it could be null. The datatype of REMARK in Ticketinfo.java have to keep it as string.I can add extra logic but cannot change the existing flow.

Please help me as I am in a terrible mess....

It sounds like a One-To-One would do the trick for the linking up of the child table. For the remark itself, you'll probably want to hijack the accessors and mutators as I don't think Hibernate handles what you want out of the box. If you have something as an attribute of another table, faking it this way isn't orthogonal or best practice. If you can't change it, leave it as it is unless you have a VERY good reason for writing weird fudges into your code.

You can make REMARK field as @Transient and use @PreUpdate @PrePersist and @PostLoad methods to load and save remark field from/to one-to-one mapped TICKETINFO_REMARK entity. The same could be done on TICKETINFO_REMARK side.

Here is quick example, it is not tested, just to give you an idea.

@Entity
@Table(name = "TICKETINFO")
public class Ticketinfo implements Serializable {

    @Id
    @Column(name = "TICKETINFOID")
    private Long id;
    @Column(name = "TICKETDATE")
    private String date;
    @Transient
    private string remark;
    @OneToOne
    @PrimaryKeyJoinColumn
    private TicketinfoRemark ticketInfoRemark;

    @PostLoad
    public void postLoad() {
        if (ticketInfoRemark != null)
            this.remark = ticketInfoRemark.getRemark();
    }

    @PreUpdate
    @PrePersist
    public void prePersist() {
       if (ticketInfoRemark != null)
           ticketInfoRemark.setRemark(this.remark);
    }
    //getters and setters
}

Hope it helps.

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