In order to use annotations for mapping in Hibernate we need to annotate our persistent classes. We’ll be replacing the XML mapping configuration with annotations. Let’s reuse the code we have already done in this post. We’ll remove the message.hbm.xml and add annotation to the Message class for mapping. Here’s the listing for Message class.

import javax.persistence.*
@Table(name = "MESSAGES")
public class Message {

    @Column(name = "MESSAGE_ID")
    private Long id;

    @Column(name = "MESSAGE_TEXT")
    private String text;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "NEXT_MESSAGE_ID")
    private Message nextMessage;

    public Message(){}

    public Message(String text){

    public Long getId() {
        return id;

    private void setId(Long id) { = id;

    public String getText() {
        return text;

    public void setText(String text) {
        this.text = text;

    public Message getNextMessage() {
        return nextMessage;

    public void setNextMessage(Message nextMessage) {
        this.nextMessage = nextMessage;

and for the same, we’ll have to edit the hibernate.cfg.xml to add the annotated class to the Hibernate configuration.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

        <!--Logging configuration-->
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>

        <!--Mapping files-->
        <mapping class="hello.Message"/>