Loading…
Transcript

Repositorios

O que é um Repositório?

public interface RepositorioUsuario extends JpaRepository<Usuario,Long> {

public Usuario findById(Long id);

public String findNameById(Long id);

public Usuario findByNameAndId(String name, Long id);

}

Onde está a mágica?

Java APT Annotation Processing Tool

Properties

Banco usado H2 Memória

#Database Configuration

db.driver=org.h2.Driver

db.url=jdbc:h2:mem:datajpa

db.username=sa

db.password=

#Hibernate Configuration

hibernate.dialect=org.hibernate.dialect.H2Dialect

hibernate.hbm2ddl.auto=create-drop

hibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy

hibernate.show_sql=false

hibernate.format_sql=true

Persistência - JPA

Metadado Anotações

Java Persistence API

História

ORM -> Object Relational Mapping

Entidades

Configuração

Persistência com JPA, Spring Data e Hibernate

@Entity

Beans

Inversão de Controle

DataSource

TransactionManager

EntityManager

Pattern Factory

Em Scala isto Seria:

case class Cidade(id:Long,nome:String)

@Entity

public class Cidade {

@Id

private Long id;

private String nome;

public Cidade(){

}

public Cidade(Long id, String nome) {

this.id = id;

this.nome = nome;

}

public Long getId() {

return id;

}

public void setId(Long id) {

this.id = id;

}

public String getNome() {

return nome;

}

public void setNome(String nome) {

this.nome = nome;

}

@Override

public boolean equals(Object o) {

if (this == o) return true;

if (!(o instanceof Cidade)) return false;

Cidade cidade = (Cidade) o;

if (id != null ? !id.equals(cidade.id) : cidade.id != null) return false;

if (nome != null ? !nome.equals(cidade.nome) : cidade.nome != null) return false;

return true;

}

@Override

public int hashCode() {

int result = id != null ? id.hashCode() : 0;

result = 31 * result + (nome != null ? nome.hashCode() : 0);

return result;

}

}

Relacionamentos

Propriedades do Relacionamento

Fetch Type

Optional

OrphanRemoval

CascadeType

mappedBy

Um pra muitos 1 -> *

Muitos para um * -> 1

Um pra um 1 -> 1

Muitos para muitos * -> *

@OneToOne

@OneToMany

@OneToOne(cascade = CascadeType.ALL, optional = false, fetch = FetchType.EAGER, orphanRemoval = true)

@PrimaryKeyJoinColumn

private Rua rua;

@OneToMany(fetch= FetchType.LAZY,

cascade = CascadeType.ALL, mappedBy="usuario")

public List<Endereco> endereco = Collections.<Endereco>emptyList();

  • get
  • set
  • add
  • remove

@ManyToOne

@ManyToOne(fetch= FetchType.LAZY)

@JoinColumn(name = "usuario_id")

private Usuario usuario;

JoinColumn

http://twitter.com/dirceusprof