如何创建基于注释的Hibernate映射?

时间:2014-12-09 20:26:13

标签: java spring hibernate hibernate-annotations

我正在编写一个使用Hibernate ORM和Spring Framework的Java项目。现在,当我添加一个POJO类时,我需要修改我的hibernate.cfg.xml文件,如下所示:

<?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>

然后,我创建了一个基于注释的类。我听说如果使用正确的Hibernate注释,我可以避免在hibernate.cfg.xml中添加每类映射。如何修改类以避免XML文件中的映射?这是我的示例POJO文件,由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 + " ]";
    }

}

1 个答案:

答案 0 :(得分:1)

我建议您将hibernate配置导出到spring配置,因为spring提供了灵活性。您关注的是每次创建新实体时都不在配置中声明类。使用弹簧配置,您可以执行以下操作。 (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>

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

相关问题