d33tah
d33tah

Reputation: 11598

How to create annotation-based Hibernate mappings?

I am writing a Java project that uses Hibernate ORM and Spring Framework. Right now, when I add a POJO class, I need to modify my hibernate.cfg.xml file, which looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <mapping class="somepackage.class1"/>
        <mapping class="somepackage.class2"/>
        <!-- etc. -->
    </session-factory>
</hibernate-configuration>

Then, I create an annotation-based class. I heard that I could avoid adding per-class mappings in hibernate.cfg.xml if I used proper Hibernate annotations. How can I modify a class to avoid the mappings in an XML file? Here is my example POJO file, generated by NetBeans:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package somepackage.pojo;

import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 *
 * @author D
 */
@Entity
@Table(name = "ACCOUNT")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Account.findAll", query = "SELECT a FROM Account a"),
    @NamedQuery(name = "Account.findByLogin", query = "SELECT a FROM Account a WHERE a.login = :login"),
    @NamedQuery(name = "Account.findByPassword", query = "SELECT a FROM Account a WHERE a.password = :password")})
public class Account implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 100)
    @Column(name = "LOGIN", nullable = false, length = 100)
    private String login;
    @Size(max = 128)
    @Column(name = "PASSWORD", length = 128)
    private String password;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "author")
    private Collection<Comment> commentCollection;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "author")
    private Collection<Article> articleCollection;

    public Account() {
    }

    public Account(String login) {
        this.login = login;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @XmlTransient
    public Collection<Comment> getCommentCollection() {
        return commentCollection;
    }

    public void setCommentCollection(Collection<Comment> commentCollection) {
        this.commentCollection = commentCollection;
    }

    @XmlTransient
    public Collection<Article> getArticleCollection() {
        return articleCollection;
    }

    public void setArticleCollection(Collection<Article> articleCollection) {
        this.articleCollection = articleCollection;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (login != null ? login.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Account)) {
            return false;
        }
        Account other = (Account) object;
        if ((this.login == null && other.login != null) || (this.login != null && !this.login.equals(other.login))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "somepackage.pojo.Account[ login=" + login + " ]";
    }

}

Upvotes: 0

Views: 1003

Answers (1)

Zeus
Zeus

Reputation: 6566

I'd suggest you export the hibernate configuration to the spring configuration because of the flexibility that spring provides. Your concern is to not declare the class in the configuration every time you create a new entity. Using spring configuration you can do the following. (packagestoscan property)

<bean id="sessionFactory"
     class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
          <property name="dataSource" ref="dataSource" />
          <property name="packagesToScan" value="org.baeldung.spring.persistence.model" />
          <property name="hibernateProperties">
             <props>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
             </props>
          </property>
       </bean>

Ref: http://www.javacodegeeks.com/2013/05/hibernate-3-with-spring.html

Upvotes: 1

Related Questions