简体   繁体   English

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

[英]How to create annotation-based Hibernate mappings?

I am writing a Java project that uses Hibernate ORM and Spring Framework. 我正在编写一个使用Hibernate ORM和Spring Framework的Java项目。 Right now, when I add a POJO class, I need to modify my hibernate.cfg.xml file, which looks like this: 现在,当我添加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>

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. 我听说如果使用正确的Hibernate批注,可以避免在hibernate.cfg.xml添加按类的映射。 How can I modify a class to avoid the mappings in an XML file? 如何修改类以避免在XML文件中进行映射? Here is my example POJO file, generated by NetBeans: 这是由NetBeans生成的示例POJO文件:

/*
 * 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 + " ]";
    }

}

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. 使用spring配置,您可以执行以下操作。 (packagestoscan property) (packagestoscan属性)

<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 参考: http : //www.javacodegeeks.com/2013/05/hibernate-3-with-spring.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM