Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

java - Need an example of a primary-key @OneToOne mapping in Hibernate

Can somebody please give me an example of a unidirectional @OneToOne primary-key mapping in Hibernate ? I've tried numerous combinations, and so far the best thing I've gotten is this :

@Entity
@Table(name = "paper_cheque_stop_metadata")
@org.hibernate.annotations.Entity(mutable = false)
public class PaperChequeStopMetadata implements Serializable, SecurityEventAware {

private static final long serialVersionUID = 1L;

@Id
@JoinColumn(name = "paper_cheque_id")
@OneToOne(cascade = {}, fetch = FetchType.EAGER, optional = false, targetEntity = PaperCheque.class)
private PaperCheque paperCheque;
}

Whenever Hibernate tries to automatically generate the schema for the above mapping, it tries to create the primary key as a blob, instead of as a long, which is the id type of PaperCheque. Can somebody please help me ? If I can't get an exact solution, something close would do, but I'd appreciate any response.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I saved this discussion when I implemented a couple of @OneToOne mappings, I hope it can be of use to you too, but we don't let Hibernate create the database for us.

Note the GenericGenerator annotation.

Anyway, I have this code working:

@Entity
@Table(name = "message")
public class Message implements java.io.Serializable
{
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "message_id")
    public MessageContent getMessageContent()
    {
        return messageContent;
    }
}

@Entity
@Table(name = "message_content")

@GenericGenerator(name = "MessageContent", strategy = "foreign",
    parameters =
    {
      @org.hibernate.annotations.Parameter
      (
        name = "property", value = "message"
      )
    }
)
public class MessageContent implements java.io.Serializable
{
    @Id
    @Column(name = "message_id", unique = true, nullable = false)
    // See http://forum.hibernate.org/viewtopic.php?p=2381079
    @GeneratedValue(generator = "MessageContent")
    public Integer getMessageId()
    {
            return this.messageId;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...