250 likes | 461 Views
Java Persistence Architecture. Julio M. Faerman. Mapeamento O-R. P lain O ld J ava O bject. Mapeamento Objeto-Relacional. SGBDR. Convenções. Anotações. XML. Java Persistence Architecture. XML. Anotações. Convenções. Object. JPA javax.persistence. MySQL.
E N D
Java Persistence Architecture Julio M. Faerman
Java Persistence Architecture Mapeamento O-R Plain Old Java Object Mapeamento Objeto-Relacional SGBDR Convenções Anotações XML
Java Persistence Architecture Java Persistence Architecture XML Anotações Convenções Object JPA javax.persistence MySQL Hibernate, Toplink, OpenJPA, EclipseLink Convenções Anotações XML
Java Persistence Architecture Java Persistence Architecture
Java Persistence Architecture Ciclo de vida de entidades
Java Persistence Architecture Ciclo de vida de entidades
Java Persistence Architecture META-INF/persistence.xml
Java Persistence Architecture Entidades • @Entity • Construtor sem argumentos public ou protected • Não final • Serializable*
Java Persistence Architecture Chaves Primárias • @Id • @GeneratedValue • GenerationType.IDENTITY • GenerationType.SEQUENCE • GenerationType.TABLE • GenerationType.AUTO • @SequenceGenerator
Java Persistence Architecture PKs Compostas • @EmbeddedID @Embeddable class PkEntidade{ long pk1; long pk2; } @Entity Class Entidade{ @EmbeddedId PkEntidade id; } • @IdClass class PkEntidade{ long pk1; long pk2; } @Entity @IdClass(PkEntidade.class) Class Entidade{ @Id pk1; @Id pk2; }
Java Persistence Architecture Propriedades • Primitivos e Wrappers • Numericos • @Column(scale = 4, precision = 15) • Temporais • @Temporal(TemporalType.TIMESTAMP) • Enumerados • @Enumerated(EnumType.STRING) • @Transient / transient
Java Persistence Architecture Hello World JPA
Java Persistence Architecture Relacionamentos @OneToOne Pessoa Passaporte pessoa.getPassaporte(); Pessoa Passaporte passaporte.getPessoa(); Pessoa Passaporte passaporte.getPessoa(); pessoa.getPassaporte(); • @OneToOne • Dono (owner) da associação • Tabela que vai ter a FK @OneToOne(mappedBy=“passaporte”)
Java Persistence Architecture @OneToMany / @ManyToOne @ManyToOne Departamento dpt = pessoa.getDepartamento(); @OneToMany List<Peca> peacas = carro.getPecas(); @OneToMany( cascade=CascadeType.ALL) O lado many sempre é owner e não declara mappedBy.
Java Persistence Architecture Relacionamentos @ManyToMany Escola Predio N N Set<Escola> escolas = predio.getEscolas(); Set<Predio> predios = escola.getPredios(); - Qualquer lado pode ser owner
Java Persistence Architecture Herança @Inheritance( strategy=InheritanceType.SINGLE_TABLE) @Inheritance( strategy=InheritanceType.JOINED) @Inheritance( strategy=InheritanceType.TABLE_PER_CLASS)
Java Persistence Architecture Controle do esquema do banco • @Table • @SecondaryTables • @Column • @JoinTable • @JoinColumn • @UniqueConstraint
Java Persistence Architecture Consultas JPQL • SELECT select p from PessoaFisica as p where p.passaporte.numero = :numero • UPDATE update Filial f set f.status = ’especial' where f.vendas > 1000000 • DELETE delete from filial f where f.vendas = 0 AND f.funcionarios IS EMPTY
Java Persistence Architecture Consultas Nomeadas @Entity @NamedQueries({ @NamedQuery(name="pf.todas",query="select pf from PessoaFisica pf"), @NamedQuery(name="pf.porPassaporte", query="select p from PessoaFisica p where p.passaporte.numero = :numero")}) public class PessoaFisica extends Pessoa {… Query query = em.createNamedQuery("pf.porPassaporte"); query.setParameter("numero", "123456"); PessoaFisica p = (PessoaFisica) query.getSingleResult();
Java Persistence Architecture Consultas Nativas (SQL) @Entity public class Order { @Id protected int id; protected long quantity; @ManyToOne protected Item item; ... } .. em.createNativeQuery( “select * from Order”,”OrderResults”); @SqlResultSetMapping( name="OrderResults", entities={ @EntityResult( entityClass=Order.class, fields={ @FieldResult(name="id", column="order_id"), @FieldResult(name="quantity", column="order_quantity"), @FieldResult(name="item", column="order_item") } ), @EntityResult( entityClass=Item.class, fields={ @FieldResult(name="id", column="item_id"), @FieldResult(name="name", column="item_name"), })})
Java Persistence Architecture orm.xml (JSR 220, chap. 10) <?xml version="1.0" encoding="UTF-8" ?> <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0"> <description>JPOX JPA tutorial</description> <package>org.jpox.tutorial.jpa</package> <entity class="org.jpox.samples.metadata.store.Product" name="Product"> <table name="JPA_PRODUCTS"/> <attributes> <id name="id"> <generated-value strategy="TABLE"/> </id> <basic name="name"> <column name="PRODUCT_NAME" length="100"/> </basic> <basic name="description"> <column length="255"/> </basic> </attributes> </entity> </entity-mappings>
Java Persistence Architecture hbm.xml <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="events.Event" table="EVENTS"> <id name="id" column="EVENT_ID"> <generator class="native"/> </id> <property name="date" type="timestamp" column="EVENT_DATE"/> <property name="title"/> </class> </hibernate-mapping> http://www.hibernate.org/hib_docs/reference/en/html/
Java Persistence Architecture Persistencia completa usando JPA
Java Persistence Architecture Dúvidas ?