如何使用hibernate映射类属性?

时间:2016-11-24 19:43:39

标签: java hibernate mapping hibernate-mapping

当我尝试在Contact类中的电话上映射电话时,它会出现以下错误:

  

SessionFactory对象的初始创建失败。错误:org.hibernate.MappingException:无法确定以下类型:com.livro.capitulo3.crudannotations.Telephone,在表:contact,对于列:[org.hibernate.mapping.Column(numPhone)]   关闭插入操作时出错。消息:null   java.lang.ExceptionInInitializerError   映射类如下:

//类Contato

package com.livro.capitulo3.crudannotations;

import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.ManyToAny;

@Entity
@Table(name = "contato")
public class ContatoAnnotations {

    @Id
    @GeneratedValue
    @Column(name = "codigo")
    private Integer codigo;

    @Column(name = "nome", length = 50, nullable = true)
    private String  nome;

    @Column(name = "telefone", length = 50, nullable = true)
    private String  telefone;

    @Column(name = "email", length = 50, nullable = true)
    private String  email;

    @Column(name = "dt_cad", nullable = true)
    private Date        dataCadastro;

    @Column(name = "obs", nullable = true)
    private String  observacao;


    //Como ficaria a annotation aqui???? Só vou persistir esta tabela
    @OneToMany
    private Telefone numTelefone;
    ...
    //Getters e Setters

}

//班级电话:

package com.livro.capitulo3.crudannotations;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "contato")
public class Telefone {
    @Id
    @GeneratedValue
    @Column(name = "numero")
    private String numero;
    @Column(name = "tipo")
    private String tipo;

    public String getNumero() {
        return numero;
    }

    public void setNumero(String numero) {
        this.numero = numero;
    }

    public String getTipo() {
        return tipo;
    }

    public void setTipo(String tipo) {
        this.tipo = tipo;
    }

}

我不知道如何做这个映射。救命!感谢!!!

2 个答案:

答案 0 :(得分:0)

如果您使用@OneToMany注释,则应该是ListSet之类的集合:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "contacto")
private List<Telefone> numTelefone = new ArrayList<>();

同时更改Telephone实体的表名称,它必须与contacto不同:

@Entity
@Table(name = "tel")
public class Telefone {...}

答案 1 :(得分:0)

因为您没有正确映射它。有几种方法可以做到:https://en.m.wikibooks.org/wiki/Java_Persistence/OneToMany