Inheritance with jpa

Asked

Viewed 1,330 times

2

Hello, I have a class called Usuario that is abstract and I have the class UsuarioComum and Administrador which they inherit from Usuario, I am using JPA annotations to generate the automatic database, I want to generate the user tables One and Administrator, both with the attributes of Usuario, so I’m using the relationship per to class. See the User class:

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) 
public abstract class Usuario {

   @Id  
   @GeneratedValue
   private Integer id; 
   @Column (length=45)
   private String nome;
   @Column (length=45)
   private String email;
   @Column (length=45)
   private String login;
   @Column (length=45)
   private String senha;

}

administrator class:

@Entity
@NamedQuery(name="Administrador.findAll", query="SELECT a FROM Administrador a")
public class Administrador extends Usuario{

    @OneToMany(mappedBy="Administrador" , cascade = CascadeType.ALL)
    private List<Log> logAdmin;

    public List<Log> getLogAdmin() {
       return logAdmin;
    }

    public void setLogAdmin(List<Log> logAdmin) {
       this.logAdmin = logAdmin;
    }
}

However when I send generate with my Factory, give that: No Identifier specified for Entity: br.com.cinemaonline.model.Administrador

he is not finding the ID is that?

1 answer

3


Next create your persisntence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org    /2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="testes"
    transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <!-- meu provider é o hibernate -->
    <!-- APESAR DA PESSOA NAO SER UMA ENTIDADE COLOQUE ELA AQUI -->
    <class>br.com.drem.entity.Pessoa</class>
    <class>br.com.drem.entity.PessoaFisica</class>
    <class>br.com.drem.entity.PessoaJuridica</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes> 

    <properties>
        <!-- postgres é o nome da minha database (Pode haver vários esquemas nela)-->
        <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost/datajava" />

        <!-- drive do postgresql 9 -->
        <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />

        <!-- ususário da base de dados -->
        <property name="javax.persistence.jdbc.user" value="andremart" />

        <!-- Senha -->
        <property name="javax.persistence.jdbc.password" value="SUA SENHA AQUI" />

        <!-- nome do schema-->
        <property name="hibernate.default_schema" value="SEU ESQUEMA AQUI" />


        <!-- para visualizarmos as querys no console -->
        <property name="hibernate.show_sql" value="true" />

        <!-- para formatamos as querys -->
        <property name="hibernate.format_sql" value="true" />

        <!-- dialeto do banco de dados -->
        <property name="hibernate.dialect"    value="org.hibernate.dialect.PostgreSQLDialect" />

        <!-- metodo para criacao, atualizacao ou exclusao de tables -->
        <property name="hibernate.hbm2ddl.auto" value="create-drop" />


        <property name="hibernate.cache.use_second_level_cache" value="true"/>

        <!--  -->
        <property name="hibernate.cache.use_query_cache" value="true" />
        <property name="hibernate.cache.region.factory_class"
            value="org.hibernate.cache.ehcache.EhCacheRegionFactory" />

    </properties>

</persistence-unit>

Then create your entities as follows

package br.com.drem.entity;

import javax.persistence.MappedSuperclass;
@MappedSuperclass
public class Pessoa {   

private String nome;

private String endereco;

private String cep;

private String obs;

public String getEndereco() {
    return endereco;
}
public void setEndereco(String endereco) {
    this.endereco = endereco;
}
public String getCep() {
    return cep;
}
public void setCep(String cep) {
    this.cep = cep;
}

public String getNome() {
    return nome;
}
public void setNome(String nome) {
    this.nome = nome;
}
public String getObs() {
    return obs;
}
public void setObs(String obs) {
    this.obs = obs;
}

}

@SuppressWarnings("serial")
@Entity
@Table(name = "pessoa_fisica")
public class PessoaFisica extends Pessoa{

/**Campos da entidade*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)

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

private String cpf;
private String matricula;
private String rg;

public String getCpf() {
    return cpf;
}
public void setCpf(String cpf) {
    this.cpf = cpf;
}
public String getMatricula() {
    return matricula;
}
public void setMatricula(String matricula) {
    this.matricula = matricula;
}
public String getRg() {
    return rg;
}
public void setRg(String rg) {
    this.rg = rg;
}

}

  @SuppressWarnings("serial")
  @Entity
  @Table(name = "pessoa_juridica")
  public class PessoaJuridica extends Pessoa {

/**Campos da entidade*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)

@Column(name = "id")
private Long id;
private String cnpj;
private String razaoSocial;
private String inscricaoEstadual;
private String matricula;
public String getCnpj() {
    return cnpj;
}
public void setCnpj(String cnpj) {
    this.cnpj = cnpj;
}
public String getRazaoSocial() {
    return razaoSocial;
}
public void setRazaoSocial(String razaoSocial) {
    this.razaoSocial = razaoSocial;
}
public String getInscricaoEstadual() {
    return inscricaoEstadual;
}
public void setInscricaoEstadual(String inscricaoEstadual) {
    this.inscricaoEstadual = inscricaoEstadual;
}
public String getMatricula() {
    return matricula;
}
public void setMatricula(String matricula) {
    this.matricula = matricula;
}

}

finally an example insertion method

   public class PFisicaDao {
   /**Salvar uma pessoaFisica*/
   public void salvar(PessoaFisica pessoaFisica) {
    EntityManager em = JPAUtil.getEntityManager();
    em.getTransaction().begin();
    em.persist(pessoaFisica);
    em.getTransaction().commit();
    em.close();     
}

and finally your test

    public class TestePessoaFisica {
    public static void main(String[] args) {
    PFisicaDao pessoaDao = new PFisicaDao();
    PessoaFisica pessoaFisica = new PessoaFisica();

    pessoaFisica.setNome("Lulu santos");
    pessoaFisica.setEndereco("Copa cabana");
    pessoaFisica.setCep("7700000");
    pessoaFisica.setCpf("1010101010");
    pessoaFisica.setObs("esse cara canta de mais e toca de mais");
    pessoaFisica.setMatricula("show");
    pessoaFisica.setRg("1010110");

    pessoaDao.salvar(pessoaFisica);

}

}

in your database will generate the following tables

pessoaFisica
pessoaJuridica

POSTGRESQL 9 WAS USED IN THIS EXAMPLE

SERVES?

  • but then this generating in the database which tables? generates only juridical and physical person? with all attributes of person? or generates the table Person together? 'Cause I don’t want to

  • Generates the person together but in case, if you leave your Abstract Person class it will never be populated is not?

  • but it will generate the table person, and I do not want, that’s why we use the TABLE_PER_CLASS , pq it generates table only the subclasses, but in my case it is giving a problem there that I have no idea.

  • I’ll test it here and tell you...

  • blz, thank you..

  • This person class depending on your system may be abstract

  • I decided to just put @Mappedsuperclass in the User class

  • OK give it a like then.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.