Hibernate SVN: r18865 - in core/trunk/entitymanager/src/test: bundles/war/WEB-INF and 9 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-02-23 18:55:06 -0500 (Tue, 23 Feb 2010)
New Revision: 18865
Added:
core/trunk/entitymanager/src/test/bundles/war/WEB-INF/
core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/
core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/META-INF/
core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/META-INF/orm.xml
core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/META-INF/persistence.xml
core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/org/
core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/
core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/ejb/
core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/ejb/test/
core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/ejb/test/pack/
core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/ejb/test/pack/war/
core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/ejb/test/pack/war/Mouse.hbm.xml
Removed:
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Prcontra.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/PrcontraPK.java
Modified:
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/StaticMetadataTest.java
Log:
HHH-4942 Rectified some problem with earlier commit. Some files got deleted which should not have been. And some files were wrongly added
Added: core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/META-INF/orm.xml
===================================================================
--- core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/META-INF/orm.xml (rev 0)
+++ core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/META-INF/orm.xml 2010-02-23 23:55:06 UTC (rev 18865)
@@ -0,0 +1,36 @@
+<?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 orm_1_0.xsd"
+ version="1.0"
+ >
+ <persistence-unit-metadata>
+ <persistence-unit-defaults>
+ <entity-listeners>
+ <entity-listener class="org.hibernate.ejb.test.pack.defaultpar.IncrementListener">
+ <pre-persist method-name="increment"/>
+ </entity-listener>
+ </entity-listeners>
+
+ </persistence-unit-defaults>
+ </persistence-unit-metadata>
+ <package>org.hibernate.ejb.test.pack.defaultpar</package>
+ <entity class="Lighter" access="FIELD" metadata-complete="true">
+ <attributes>
+ <id name="name">
+ <column name="fld_id"/>
+ </id>
+
+ <basic name="power"></basic>
+ </attributes>
+ </entity>
+ <entity class="ApplicationServer">
+ <entity-listeners>
+ <entity-listener class="OtherIncrementListener">
+ <pre-persist method-name="increment"/>
+ </entity-listener>
+ </entity-listeners>
+
+ </entity>
+</entity-mappings>
Added: core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/META-INF/persistence.xml
===================================================================
--- core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/META-INF/persistence.xml (rev 0)
+++ core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/META-INF/persistence.xml 2010-02-23 23:55:06 UTC (rev 18865)
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- example of a default persistence.xml -->
+<persistence 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"
+ version="2.0">
+ <persistence-unit name="defaultpar">
+ <class>org.hibernate.ejb.test.pack.defaultpar.Lighter</class>
+ <properties>
+ <property name="hibernate.dialect" value="${db.dialect}"/>
+ <property name="hibernate.connection.driver_class" value="${jdbc.driver}"/>
+ <property name="hibernate.connection.username" value="${jdbc.user}"/>
+ <property name="hibernate.connection.password" value="${jdbc.pass}"/>
+
+ <property name="hibernate.connection.url" value="${jdbc.url}"/>
+ <property name="hibernate.connection.isolation" value="${jdbc.isolation}"/>
+ <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
+ <property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider"/>
+ </properties>
+ </persistence-unit>
+</persistence>
+
Added: core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/ejb/test/pack/war/Mouse.hbm.xml
===================================================================
--- core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/ejb/test/pack/war/Mouse.hbm.xml (rev 0)
+++ core/trunk/entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/ejb/test/pack/war/Mouse.hbm.xml 2010-02-23 23:55:06 UTC (rev 18865)
@@ -0,0 +1,20 @@
+<?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
+ package="org.hibernate.ejb.test.pack.war"
+ >
+
+ <class name="Mouse">
+
+ <id name="id">
+ <generator class="native"/>
+ </id>
+ <property name="name"/>
+
+ </class>
+
+</hibernate-mapping>
+
Deleted: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Prcontra.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Prcontra.java 2010-02-23 22:18:43 UTC (rev 18864)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Prcontra.java 2010-02-23 23:55:06 UTC (rev 18865)
@@ -1,1487 +0,0 @@
-// $Id:$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.ejb.test.metadata;
-
-import java.io.Serializable;
-import java.math.BigInteger;
-import java.util.Date;
-import javax.persistence.Column;
-import javax.persistence.EmbeddedId;
-import javax.persistence.Entity;
-import javax.persistence.Table;
-import javax.persistence.Temporal;
-import javax.persistence.TemporalType;
-
-import org.hibernate.annotations.Formula;
-
-@Entity
-@Table(name = "PRCONTRA", schema = "MUVALE")
-public class Prcontra implements Serializable {
- private static final long serialVersionUID = -4996315772144793755L;
- @EmbeddedId
- protected PrcontraPK prcontraPK;
- @Column(name = "DOC", nullable = false, insertable = false, updatable = false)
- private BigInteger doc;
- @Column(name = "NIF", nullable = false, insertable = false, updatable = false)
- private String nif;
- @Column(name = "ANNO")
- private BigInteger anno;
-// @Column(name = "NIF",insertable=false, updatable=false,nullable=false)
- // private String nif;
- @Column(name = "PRSSEM")
- private BigInteger prssem;
- @Column(name = "NISSEM")
- private BigInteger nissem;
- @Column(name = "COSSEM")
- private BigInteger cossem;
- @Column(name = "REGIMEN")
- private BigInteger regimen;
- @Column(name = "CONTACTO")
- private String contacto;
- @Column(name = "TELEFONO")
- private String telefono;
- @Column(name = "FAX")
- private String fax;
- @Column(name = "NUTRA")
- private BigInteger nutra;
- @Column(name = "NUTRAT")
- private BigInteger nutrat;
- @Column(name = "CNAE")
- private BigInteger cnae;
- @Column(name = "GREMP")
- private BigInteger gremp;
- @Column(name = "A1")
- private Character a1;
- @Column(name = "F_ALTA")
- @Temporal(TemporalType.TIMESTAMP)
- private Date fAlta;
- @Column(name = "F_BAJA")
- @Temporal(TemporalType.TIMESTAMP)
- private Date fBaja;
- @Column(name = "PRECIO")
- private Float precio;
- @Column(name = "MPAGO")
- private BigInteger mpago;
- @Column(name = "PERIO")
- private BigInteger perio;
- @Column(name = "CTABANCO")
- private String ctabanco;
- @Column(name = "QUIENFIRMA")
- private String quienfirma;
- @Column(name = "DNIFIRMA")
- private String dnifirma;
- @Column(name = "CARGOFIRMA")
- private String cargofirma;
- @Column(name = "F_ESCRITURA")
- @Temporal(TemporalType.TIMESTAMP)
- private Date fEscritura;
- @Column(name = "NOTARIO")
- private String notario;
- @Column(name = "POBLANOT")
- private String poblanot;
- @Column(name = "PROTOCOLO")
- private String protocolo;
- @Column(name = "LUGARFIRMA")
- private String lugarfirma;
- @Column(name = "CONTF")
- private BigInteger contf;
- @Column(name = "BLOQUEO")
- private Character bloqueo;
- @Column(name = "FACTURA")
- private Character factura;
- @Column(name = "ENPODER")
- private String enpoder;
- @Column(name = "CPAR1")
- private Character cpar1;
- @Column(name = "CPAR2")
- private Character cpar2;
- @Column(name = "CPAR3")
- private Character cpar3;
- @Column(name = "CPAR4")
- private Character cpar4;
- @Column(name = "CPAR5")
- private Character cpar5;
- @Column(name = "CPAR6")
- private Character cpar6;
- @Column(name = "CPAR7")
- private Character cpar7;
- @Column(name = "CPAR8")
- private Character cpar8;
- @Column(name = "CPAR9")
- private Character cpar9;
- @Column(name = "SPP1")
- private Character spp1;
- @Column(name = "SPP2")
- private Character spp2;
- @Column(name = "SPP3")
- private Character spp3;
- @Column(name = "RR")
- private Character rr;
- @Column(name = "TIPOC")
- private String tipoc;
- @Column(name = "PTRAB")
- private String ptrab;
- @Column(name = "PCURSO")
- private String pcurso;
- @Column(name = "USUALT")
- private BigInteger usualt;
- @Column(name = "F_USU")
- @Temporal(TemporalType.TIMESTAMP)
- private Date fUsu;
- @Column(name = "FIRMADO")
- private Character firmado;
- @Column(name = "VS")
- private Character vs;
- @Column(name = "CENTRA")
- private BigInteger centra;
- @Column(name = "RT")
- private BigInteger rt;
- @Column(name = "F1")
- private Character f1;
- @Column(name = "IPC")
- private Character ipc;
- @Column(name = "NR")
- private BigInteger nr;
- @Column(name = "COORD")
- private BigInteger coord;
- @Column(name = "OBSERV")
- private String observ;
- @Column(name = "TM")
- private BigInteger tm;
- @Column(name = "RE")
- private BigInteger re;
- @Column(name = "UMOVIL")
- private Character umovil;
- @Column(name = "ADS")
- private BigInteger ads;
- @Column(name = "F_DESCARGA")
- @Temporal(TemporalType.TIMESTAMP)
- private Date fDescarga;
- @Column(name = "GRUPO_EMP")
- private BigInteger grupoEmp;
- @Column(name = "OBSERV1")
- private String observ1;
- @Column(name = "OBSERV2")
- private String observ2;
- @Column(name = "F_LLAMADA1")
- @Temporal(TemporalType.TIMESTAMP)
- private Date fLlamada1;
- @Column(name = "NA1")
- private Character na1;
- @Column(name = "CONST")
- private Character const1;
- @Column(name = "F_EVR")
- @Temporal(TemporalType.TIMESTAMP)
- private Date fEvr;
- @Column(name = "F_PLAN")
- @Temporal(TemporalType.TIMESTAMP)
- private Date fPlan;
- @Column(name = "F_MEMORIA")
- @Temporal(TemporalType.TIMESTAMP)
- private Date fMemoria;
- @Column(name = "F_RENOVE")
- @Temporal(TemporalType.TIMESTAMP)
- private Date fRenove;
- @Column(name = "INCI")
- private Character inci;
- @Column(name = "F_ENV_PLAN")
- @Temporal(TemporalType.TIMESTAMP)
- private Date fEnvPlan;
- @Column(name = "A1_DOC_IMP")
- private Float a1DocImp;
- @Column(name = "A1_DOC_NTRA")
- private Float a1DocNtra;
- @Column(name = "A1_RM_IMP")
- private Float a1RmImp;
- @Column(name = "A1_RM_NTRA")
- private Float a1RmNtra;
- @Column(name = "NA1_DOC_IMP")
- private Float na1DocImp;
- @Column(name = "NA1_DOC_NTRA")
- private Float na1DocNtra;
- @Column(name = "NA1_RM_IMP")
- private Float na1RmImp;
- @Column(name = "NA1_RM_NTRA")
- private Float na1RmNtra;
- @Column(name = "CONST_DOC_IMP")
- private Float constDocImp;
- @Column(name = "CONST_DOC_NTRA")
- private Float constDocNtra;
- @Column(name = "CONST_RM_IMP")
- private Float constRmImp;
- @Column(name = "CONST_RM_NTRA")
- private String constRmNtra;
- @Column(name = "TIENE_PRE")
- private Character tienePre;
- @Column(name = "ACEPTA_PRE")
- private Character aceptaPre;
- @Column(name = "F_PRE")
- @Temporal(TemporalType.TIMESTAMP)
- private Date fPre;
- @Column(name = "NHORAS")
- private BigInteger nhoras;
- @Column(name = "CHORA")
- private Float chora;
- @Column(name = "IND_UNICO")
- private BigInteger indUnico;
- @Column(name = "NUMEROI")
- private BigInteger numeroi;
- @Column(name = "RENOVI")
- private BigInteger renovi;
- @Column(name = "TIPOI")
- private BigInteger tipoi;
- @Column(name = "TARIFA")
- private Float tarifa;
- @Column(name = "IPC_PORC")
- private Float ipcPorc;
- @Column(name = "F_REC_MEM")
- @Temporal(TemporalType.TIMESTAMP)
- private Date fRecMem;
- @Column(name = "F_REC_PLAN")
- @Temporal(TemporalType.TIMESTAMP)
- private Date fRecPlan;
- @Column(name = "IPC_IMP")
- private Float ipcImp;
- @Column(name = "UMOVIL_IMP")
- private Float umovilImp;
- @Column(name = "QUIENFIRMA2")
- private String quienfirma2;
- @Column(name = "DNIFIRMA2")
- private String dnifirma2;
- @Column(name = "CARGOFIRMA2")
- private String cargofirma2;
- @Column(name = "DOMIC_ENV")
- private String domicEnv;
- @Column(name = "PROVI_ENV")
- private BigInteger proviEnv;
- @Column(name = "POBLA_ENV")
- private BigInteger poblaEnv;
- @Column(name = "DISPO_ENV")
- private BigInteger dispoEnv;
- @Column(name = "MUT_ORIGEN")
- private BigInteger mutOrigen;
- @Column(name = "COD_CONCIERTO")
- private String codConcierto;
- @Column(name = "N_PEDIDO")
- private String nPedido;
- @Column(name = "D_FACTURA")
- private BigInteger dFactura;
- @Column(name = "D_VENCIMIENTO")
- private String dVencimiento;
- @Column(name = "CON_NRM_RH")
- private BigInteger conNrmRh;
- @Column(name = "CON_NRM_RT")
- private BigInteger conNrmRt;
-
- @Column(name = "CON_PRECIO_RM_EXCESO")
- private Float conPrecioRmExceso;
- @Column(name = "CON_NTRA_DOC_RH")
- private BigInteger conNtraDocRh;
- @Column(name = "CON_IMPDOC_RHIGIENICO")
- private Float conImpDocRhigienico;
- @Column(name = "CON_IMPRM_RHIGIENICO")
- private Float conImprmRhigienico;
- @Column(name = "CON_NTRA_DOC_RT")
- private BigInteger conNtraDocRt;
- @Column(name = "CON_IMPDOC_RTIPOLOGIAS")
- private Float conImpdocRTipologias;
- @Column(name = "CON_IMPRM_RTIPOLOGIAS")
- private Float conImprmRtipologias;
- @Column(name = "CON_IMP_UMOVIL")
- private Float conImpUmovil;
- @Column(name = "CON_PRECIO_SME")
- private Float conPrecioSme;
-
-
- @Formula(value = "(select pago.texto from muvale.mpago pago where pago.mpago=mpago)")
- private String textoMpago;
-
- @Formula(value = "(" +
- "muvale.nutra_nif(" +
- " to_char(F_ALTA,'RRRR')," +
- " to_char(F_ALTA,'MM')," +
- " nif) " +
- ")")
- private Integer totalAfiliados;
-
- // Modo de pago
- @Formula(value = "(select p.DOM_DESCRIPCION from prevencion.prv_dominios_prevencion p where p.dom_campo='TPRECIO' and p.dom_valor=tarifa)")
- private String modo;
-
- // Impagado
- @Formula(value = "( SELECT distinct 1 " +
- " FROM MUVALE.PRFAC A " +
- " inner join MUVALE.PRECIB R on A.ANNO = R.ANNO and A.NUMFAC = R.NUMFAC and A.SERIE = R.SERIE" +
- " WHERE A.SERIE = 10" +
- " AND R.NUM = (SELECT MAX(R1.NUM) " +
- " FROM MUVALE.PRECIB R1 " +
- " WHERE R.ANNO = R1.ANNO " +
- " AND R.NUMFAC = R1.NUMFAC " +
- " AND R.SERIE = R1.SERIE " +
- " AND R.LIN = R1.LIN) " +
- " AND R.COBRADO IN ('I','J') " +
- " and a.numero = numero and a.renov = renov and a.tipo = tipo)")
- private Integer impagado;
-
- @Formula(value = "( " +
- " select count( r.rec_codigo ) " +
- " from prevencion.vds_reconocimiento r " +
- " where r.rec_numero= NUMERO " +
- " and r.rec_tipo = 2 " +
- " and r.rec_fecha between F_ALTA and nvl(F_BAJA,sysdate) " +
- " and r.rec_estado>0 " +
- " and r.rec_tiprec in(0,1,3,10,15,16,17) )")
- //Los mismos que en VdsReconocimientoDAO.FILTRO_TIPO_DE_RECONOCIMENTO
- private Long numReconRealizados;
-
- @Formula(value = "( " +
- " nvl(CON_NRM_RH,0) + nvl(CON_NRM_RT,0) " +
- " )")
- private Long numReconPrevistos;
-
- //END-ENTITY-MOD
-
-
- public Prcontra() {
- }
-
- public Prcontra(PrcontraPK prcontraPK) {
- this.prcontraPK = prcontraPK;
-
- }
-
- public Prcontra(BigInteger numero, BigInteger renov, BigInteger tipo) {
- this.prcontraPK = new PrcontraPK( numero, renov, tipo );
- }
-
- public Prcontra(BigInteger numero, BigInteger renov, BigInteger tipo, Date fAlta, Character bloqueo) {
- this.prcontraPK = new PrcontraPK( numero, renov, tipo );
- this.fAlta = fAlta;
- this.bloqueo = bloqueo;
- }
-
- public PrcontraPK getPrcontraPK() {
- return prcontraPK;
- }
-
- public void setPrcontraPK(PrcontraPK prcontraPK) {
- this.prcontraPK = prcontraPK;
- }
-
- public BigInteger getAnno() {
- return anno;
- }
-
- public void setAnno(BigInteger anno) {
- this.anno = anno;
- }
-
-// public String getNif() {
-// return nif;
-// }
-//
-// public void setNif(String nif) {
-// this.nif = nif;
-// }
-
- public BigInteger getPrssem() {
- return prssem;
- }
-
- public void setPrssem(BigInteger prssem) {
- this.prssem = prssem;
- }
-
- public BigInteger getNissem() {
- return nissem;
- }
-
- public void setNissem(BigInteger nissem) {
- this.nissem = nissem;
- }
-
- public BigInteger getCossem() {
- return cossem;
- }
-
- public void setCossem(BigInteger cossem) {
- this.cossem = cossem;
- }
-
- public BigInteger getRegimen() {
- return regimen;
- }
-
- public void setRegimen(BigInteger regimen) {
- this.regimen = regimen;
- }
-
- public String getContacto() {
- return contacto;
- }
-
- public void setContacto(String contacto) {
- this.contacto = contacto;
- }
-
- public String getTelefono() {
- return telefono;
- }
-
- public void setTelefono(String telefono) {
- this.telefono = telefono;
- }
-
- public String getFax() {
- return fax;
- }
-
- public void setFax(String fax) {
- this.fax = fax;
- }
-
- public BigInteger getNutra() {
- return nutra;
- }
-
- public void setNutra(BigInteger nutra) {
- this.nutra = nutra;
- }
-
- public BigInteger getNutrat() {
- return nutrat;
- }
-
- public void setNutrat(BigInteger nutrat) {
- this.nutrat = nutrat;
- }
-
- public BigInteger getCnae() {
- return cnae;
- }
-
- public void setCnae(BigInteger cnae) {
- this.cnae = cnae;
- }
-
- public BigInteger getGremp() {
- return gremp;
- }
-
- public void setGremp(BigInteger gremp) {
- this.gremp = gremp;
- }
-
- public Character getA1() {
- return a1;
- }
-
- public void setA1(Character a1) {
- this.a1 = a1;
- }
-
- public Date getFAlta() {
- return fAlta;
- }
-
- public void setFAlta(Date fAlta) {
- this.fAlta = fAlta;
- }
-
- public Date getFBaja() {
- return fBaja;
- }
-
- public void setFBaja(Date fBaja) {
- this.fBaja = fBaja;
- }
-
- public Float getPrecio() {
- return precio;
- }
-
- public void setPrecio(Float precio) {
- this.precio = precio;
- }
-
- public BigInteger getMpago() {
- return mpago;
- }
-
- public void setMpago(BigInteger mpago) {
- this.mpago = mpago;
- }
-
- public BigInteger getPerio() {
- return perio;
- }
-
- public void setPerio(BigInteger perio) {
- this.perio = perio;
- }
-
- public String getCtabanco() {
- return ctabanco;
- }
-
- public void setCtabanco(String ctabanco) {
- this.ctabanco = ctabanco;
- }
-
- public String getQuienfirma() {
- return quienfirma;
- }
-
- public void setQuienfirma(String quienfirma) {
- this.quienfirma = quienfirma;
- }
-
- public String getDnifirma() {
- return dnifirma;
- }
-
- public void setDnifirma(String dnifirma) {
- this.dnifirma = dnifirma;
- }
-
- public String getCargofirma() {
- return cargofirma;
- }
-
- public void setCargofirma(String cargofirma) {
- this.cargofirma = cargofirma;
- }
-
- public Date getFEscritura() {
- return fEscritura;
- }
-
- public void setFEscritura(Date fEscritura) {
- this.fEscritura = fEscritura;
- }
-
- public String getNotario() {
- return notario;
- }
-
- public void setNotario(String notario) {
- this.notario = notario;
- }
-
- public String getPoblanot() {
- return poblanot;
- }
-
- public void setPoblanot(String poblanot) {
- this.poblanot = poblanot;
- }
-
- public String getProtocolo() {
- return protocolo;
- }
-
- public void setProtocolo(String protocolo) {
- this.protocolo = protocolo;
- }
-
- public String getLugarfirma() {
- return lugarfirma;
- }
-
- public void setLugarfirma(String lugarfirma) {
- this.lugarfirma = lugarfirma;
- }
-
- public BigInteger getContf() {
- return contf;
- }
-
- public void setContf(BigInteger contf) {
- this.contf = contf;
- }
-
- public Character getBloqueo() {
- return bloqueo;
- }
-
- public void setBloqueo(Character bloqueo) {
- this.bloqueo = bloqueo;
- }
-
- public Character getFactura() {
- return factura;
- }
-
- public void setFactura(Character factura) {
- this.factura = factura;
- }
-
- public String getEnpoder() {
- return enpoder;
- }
-
- public void setEnpoder(String enpoder) {
- this.enpoder = enpoder;
- }
-
- public Character getCpar1() {
- return cpar1;
- }
-
- public void setCpar1(Character cpar1) {
- this.cpar1 = cpar1;
- }
-
- public Character getCpar2() {
- return cpar2;
- }
-
- public void setCpar2(Character cpar2) {
- this.cpar2 = cpar2;
- }
-
- public Character getCpar3() {
- return cpar3;
- }
-
- public void setCpar3(Character cpar3) {
- this.cpar3 = cpar3;
- }
-
- public Character getCpar4() {
- return cpar4;
- }
-
- public void setCpar4(Character cpar4) {
- this.cpar4 = cpar4;
- }
-
- public Character getCpar5() {
- return cpar5;
- }
-
- public void setCpar5(Character cpar5) {
- this.cpar5 = cpar5;
- }
-
- public Character getCpar6() {
- return cpar6;
- }
-
- public void setCpar6(Character cpar6) {
- this.cpar6 = cpar6;
- }
-
- public Character getCpar7() {
- return cpar7;
- }
-
- public void setCpar7(Character cpar7) {
- this.cpar7 = cpar7;
- }
-
- public Character getCpar8() {
- return cpar8;
- }
-
- public void setCpar8(Character cpar8) {
- this.cpar8 = cpar8;
- }
-
- public Character getCpar9() {
- return cpar9;
- }
-
- public void setCpar9(Character cpar9) {
- this.cpar9 = cpar9;
- }
-
- public Character getSpp1() {
- return spp1;
- }
-
- public void setSpp1(Character spp1) {
- this.spp1 = spp1;
- }
-
- public Character getSpp2() {
- return spp2;
- }
-
- public void setSpp2(Character spp2) {
- this.spp2 = spp2;
- }
-
- public Character getSpp3() {
- return spp3;
- }
-
- public void setSpp3(Character spp3) {
- this.spp3 = spp3;
- }
-
- public Character getRr() {
- return rr;
- }
-
- public void setRr(Character rr) {
- this.rr = rr;
- }
-
- public String getTipoc() {
- return tipoc;
- }
-
- public void setTipoc(String tipoc) {
- this.tipoc = tipoc;
- }
-
- public String getPtrab() {
- return ptrab;
- }
-
- public void setPtrab(String ptrab) {
- this.ptrab = ptrab;
- }
-
- public String getPcurso() {
- return pcurso;
- }
-
- public void setPcurso(String pcurso) {
- this.pcurso = pcurso;
- }
-
- public BigInteger getUsualt() {
- return usualt;
- }
-
- public void setUsualt(BigInteger usualt) {
- this.usualt = usualt;
- }
-
- public Date getFUsu() {
- return fUsu;
- }
-
- public void setFUsu(Date fUsu) {
- this.fUsu = fUsu;
- }
-
- public Character getFirmado() {
- return firmado;
- }
-
- public void setFirmado(Character firmado) {
- this.firmado = firmado;
- }
-
- public Character getVs() {
- return vs;
- }
-
- public void setVs(Character vs) {
- this.vs = vs;
- }
-
- public BigInteger getCentra() {
- return centra;
- }
-
- public void setCentra(BigInteger centra) {
- this.centra = centra;
- }
-
- public BigInteger getRt() {
- return rt;
- }
-
- public void setRt(BigInteger rt) {
- this.rt = rt;
- }
-
- public Character getF1() {
- return f1;
- }
-
- public void setF1(Character f1) {
- this.f1 = f1;
- }
-
- public Character getIpc() {
- return ipc;
- }
-
- public void setIpc(Character ipc) {
- this.ipc = ipc;
- }
-
- public BigInteger getNr() {
- return nr;
- }
-
- public void setNr(BigInteger nr) {
- this.nr = nr;
- }
-
- public BigInteger getCoord() {
- return coord;
- }
-
- public void setCoord(BigInteger coord) {
- this.coord = coord;
- }
-
- public String getObserv() {
- return observ;
- }
-
- public void setObserv(String observ) {
- this.observ = observ;
- }
-
- public BigInteger getTm() {
- return tm;
- }
-
- public void setTm(BigInteger tm) {
- this.tm = tm;
- }
-
- public BigInteger getRe() {
- return re;
- }
-
- public void setRe(BigInteger re) {
- this.re = re;
- }
-
- public Character getUmovil() {
- return umovil;
- }
-
- public void setUmovil(Character umovil) {
- this.umovil = umovil;
- }
-
- public BigInteger getAds() {
- return ads;
- }
-
- public void setAds(BigInteger ads) {
- this.ads = ads;
- }
-
- public Date getFDescarga() {
- return fDescarga;
- }
-
- public void setFDescarga(Date fDescarga) {
- this.fDescarga = fDescarga;
- }
-
- public BigInteger getGrupoEmp() {
- return grupoEmp;
- }
-
- public void setGrupoEmp(BigInteger grupoEmp) {
- this.grupoEmp = grupoEmp;
- }
-
- public String getObserv1() {
- return observ1;
- }
-
- public void setObserv1(String observ1) {
- this.observ1 = observ1;
- }
-
- public String getObserv2() {
- return observ2;
- }
-
- public void setObserv2(String observ2) {
- this.observ2 = observ2;
- }
-
- public Date getFLlamada1() {
- return fLlamada1;
- }
-
- public void setFLlamada1(Date fLlamada1) {
- this.fLlamada1 = fLlamada1;
- }
-
- public Character getNa1() {
- return na1;
- }
-
- public void setNa1(Character na1) {
- this.na1 = na1;
- }
-
- public Character getConst1() {
- return const1;
- }
-
- public void setConst1(Character const1) {
- this.const1 = const1;
- }
-
- public Date getFEvr() {
- return fEvr;
- }
-
- public void setFEvr(Date fEvr) {
- this.fEvr = fEvr;
- }
-
- public Date getFPlan() {
- return fPlan;
- }
-
- public void setFPlan(Date fPlan) {
- this.fPlan = fPlan;
- }
-
- public Date getFMemoria() {
- return fMemoria;
- }
-
- public void setFMemoria(Date fMemoria) {
- this.fMemoria = fMemoria;
- }
-
- public Date getFRenove() {
- return fRenove;
- }
-
- public void setFRenove(Date fRenove) {
- this.fRenove = fRenove;
- }
-
- public Character getInci() {
- return inci;
- }
-
- public void setInci(Character inci) {
- this.inci = inci;
- }
-
- public Date getFEnvPlan() {
- return fEnvPlan;
- }
-
- public void setFEnvPlan(Date fEnvPlan) {
- this.fEnvPlan = fEnvPlan;
- }
-
- public Float getA1DocImp() {
- return a1DocImp;
- }
-
- public void setA1DocImp(Float a1DocImp) {
- this.a1DocImp = a1DocImp;
- }
-
- public Float getA1DocNtra() {
- return a1DocNtra;
- }
-
- public void setA1DocNtra(Float a1DocNtra) {
- this.a1DocNtra = a1DocNtra;
- }
-
- public Float getA1RmImp() {
- return a1RmImp;
- }
-
- public void setA1RmImp(Float a1RmImp) {
- this.a1RmImp = a1RmImp;
- }
-
- public Float getA1RmNtra() {
- return a1RmNtra;
- }
-
- public void setA1RmNtra(Float a1RmNtra) {
- this.a1RmNtra = a1RmNtra;
- }
-
- public Float getNa1DocImp() {
- return na1DocImp;
- }
-
- public void setNa1DocImp(Float na1DocImp) {
- this.na1DocImp = na1DocImp;
- }
-
- public Float getNa1DocNtra() {
- return na1DocNtra;
- }
-
- public void setNa1DocNtra(Float na1DocNtra) {
- this.na1DocNtra = na1DocNtra;
- }
-
- public Float getNa1RmImp() {
- return na1RmImp;
- }
-
- public void setNa1RmImp(Float na1RmImp) {
- this.na1RmImp = na1RmImp;
- }
-
- public Float getNa1RmNtra() {
- return na1RmNtra;
- }
-
- public void setNa1RmNtra(Float na1RmNtra) {
- this.na1RmNtra = na1RmNtra;
- }
-
- public Float getConstDocImp() {
- return constDocImp;
- }
-
- public void setConstDocImp(Float constDocImp) {
- this.constDocImp = constDocImp;
- }
-
- public Float getConstDocNtra() {
- return constDocNtra;
- }
-
- public void setConstDocNtra(Float constDocNtra) {
- this.constDocNtra = constDocNtra;
- }
-
- public Float getConstRmImp() {
- return constRmImp;
- }
-
- public void setConstRmImp(Float constRmImp) {
- this.constRmImp = constRmImp;
- }
-
- public String getConstRmNtra() {
- return constRmNtra;
- }
-
- public void setConstRmNtra(String constRmNtra) {
- this.constRmNtra = constRmNtra;
- }
-
- public Character getTienePre() {
- return tienePre;
- }
-
- public void setTienePre(Character tienePre) {
- this.tienePre = tienePre;
- }
-
- public Character getAceptaPre() {
- return aceptaPre;
- }
-
- public void setAceptaPre(Character aceptaPre) {
- this.aceptaPre = aceptaPre;
- }
-
- public Date getFPre() {
- return fPre;
- }
-
- public void setFPre(Date fPre) {
- this.fPre = fPre;
- }
-
- public BigInteger getNhoras() {
- return nhoras;
- }
-
- public void setNhoras(BigInteger nhoras) {
- this.nhoras = nhoras;
- }
-
- public Float getChora() {
- return chora;
- }
-
- public void setChora(Float chora) {
- this.chora = chora;
- }
-
- public BigInteger getIndUnico() {
- return indUnico;
- }
-
- public void setIndUnico(BigInteger indUnico) {
- this.indUnico = indUnico;
- }
-
- public BigInteger getNumeroi() {
- return numeroi;
- }
-
- public void setNumeroi(BigInteger numeroi) {
- this.numeroi = numeroi;
- }
-
- public BigInteger getRenovi() {
- return renovi;
- }
-
- public void setRenovi(BigInteger renovi) {
- this.renovi = renovi;
- }
-
- public BigInteger getTipoi() {
- return tipoi;
- }
-
- public void setTipoi(BigInteger tipoi) {
- this.tipoi = tipoi;
- }
-
- public Float getTarifa() {
- return tarifa;
- }
-
- public void setTarifa(Float tarifa) {
- this.tarifa = tarifa;
- }
-
- public Float getIpcPorc() {
- return ipcPorc;
- }
-
- public void setIpcPorc(Float ipcPorc) {
- this.ipcPorc = ipcPorc;
- }
-
- public Date getFRecMem() {
- return fRecMem;
- }
-
- public void setFRecMem(Date fRecMem) {
- this.fRecMem = fRecMem;
- }
-
- public Date getFRecPlan() {
- return fRecPlan;
- }
-
- public void setFRecPlan(Date fRecPlan) {
- this.fRecPlan = fRecPlan;
- }
-
- public Float getIpcImp() {
- return ipcImp;
- }
-
- public void setIpcImp(Float ipcImp) {
- this.ipcImp = ipcImp;
- }
-
- public Float getUmovilImp() {
- return umovilImp;
- }
-
- public void setUmovilImp(Float umovilImp) {
- this.umovilImp = umovilImp;
- }
-
- public String getQuienfirma2() {
- return quienfirma2;
- }
-
- public void setQuienfirma2(String quienfirma2) {
- this.quienfirma2 = quienfirma2;
- }
-
- public String getDnifirma2() {
- return dnifirma2;
- }
-
- public void setDnifirma2(String dnifirma2) {
- this.dnifirma2 = dnifirma2;
- }
-
- public String getCargofirma2() {
- return cargofirma2;
- }
-
- public void setCargofirma2(String cargofirma2) {
- this.cargofirma2 = cargofirma2;
- }
-
- public String getDomicEnv() {
- return domicEnv;
- }
-
- public void setDomicEnv(String domicEnv) {
- this.domicEnv = domicEnv;
- }
-
- public BigInteger getProviEnv() {
- return proviEnv;
- }
-
- public void setProviEnv(BigInteger proviEnv) {
- this.proviEnv = proviEnv;
- }
-
- public BigInteger getPoblaEnv() {
- return poblaEnv;
- }
-
- public void setPoblaEnv(BigInteger poblaEnv) {
- this.poblaEnv = poblaEnv;
- }
-
- public BigInteger getDispoEnv() {
- return dispoEnv;
- }
-
- public void setDispoEnv(BigInteger dispoEnv) {
- this.dispoEnv = dispoEnv;
- }
-
- public BigInteger getMutOrigen() {
- return mutOrigen;
- }
-
- public void setMutOrigen(BigInteger mutOrigen) {
- this.mutOrigen = mutOrigen;
- }
-
- public String getCodConcierto() {
- return codConcierto;
- }
-
- public void setCodConcierto(String codConcierto) {
- this.codConcierto = codConcierto;
- }
-
- public String getNPedido() {
- return nPedido;
- }
-
- public void setNPedido(String nPedido) {
- this.nPedido = nPedido;
- }
-
- public BigInteger getDFactura() {
- return dFactura;
- }
-
- public void setDFactura(BigInteger dFactura) {
- this.dFactura = dFactura;
- }
-
- public String getDVencimiento() {
- return dVencimiento;
- }
-
- public void setDVencimiento(String dVencimiento) {
- this.dVencimiento = dVencimiento;
- }
-
- @Override
- public int hashCode() {
- int hash = 0;
- hash += ( prcontraPK != null ? prcontraPK.hashCode() : 0 );
- return hash;
- }
-
- @Override
- public boolean equals(Object object) {
- if ( !( object instanceof Prcontra ) ) {
- return false;
- }
- Prcontra other = ( Prcontra ) object;
- if ( this.prcontraPK != other.prcontraPK
- && ( this.prcontraPK == null || !this.prcontraPK
- .equals( other.prcontraPK ) ) ) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- return "org.kyrian.entity.muvale.Prcontra[prcontraPK=" + prcontraPK
- + "]";
- }
- //START-ENTITY-MOD
-
- public String getTextoMpago() {
- return textoMpago;
- }
-
- public void setTextoMpago(String textoMpago) {
- this.textoMpago = textoMpago;
- }
-
- public Integer getTotalAfiliados() {
- return totalAfiliados;
- }
-
- public void setTotalAfiliados(Integer totalAfiliados) {
- this.totalAfiliados = totalAfiliados;
- }
-
- public String getModo() {
- return modo;
- }
-
- public void setModo(String modo) {
- this.modo = modo;
- }
-
- public Integer getImpagado() {
- return impagado;
- }
-
- public void setImpagado(Integer impagado) {
- this.impagado = impagado;
- }
-
- public Long getNumReconRealizados() {
- return numReconRealizados;
- }
-
- public void setNumReconRealizados(Long numReconRealizados) {
- this.numReconRealizados = numReconRealizados;
- }
-
- public Long getNumReconPrevistos() {
- return numReconPrevistos;
- }
-
- public void setNumReconPrevistos(Long numReconPrevistos) {
- this.numReconPrevistos = numReconPrevistos;
- }
-
- public BigInteger getConNrmRh() {
- return conNrmRh;
- }
-
- public BigInteger getConNrmRt() {
- return conNrmRt;
- }
-
- public void setConNrmRh(BigInteger conNrmRh) {
- this.conNrmRh = conNrmRh;
- }
-
- public void setConNrmRt(BigInteger conNrmRt) {
- this.conNrmRt = conNrmRt;
- }
-
- public Float getConPrecioRmExceso() {
- return conPrecioRmExceso;
- }
-
- public BigInteger getConNtraDocRh() {
- return conNtraDocRh;
- }
-
- public Float getConImpDocRhigienico() {
- return conImpDocRhigienico;
- }
-
- public Float getConImprmRhigienico() {
- return conImprmRhigienico;
- }
-
- public BigInteger getConNtraDocRt() {
- return conNtraDocRt;
- }
-
- public Float getConImpdocRTipologias() {
- return conImpdocRTipologias;
- }
-
- public Float getConImprmRtipologias() {
- return conImprmRtipologias;
- }
-
- public Float getConImpUmovil() {
- return conImpUmovil;
- }
-
- public Float getConPrecioSme() {
- return conPrecioSme;
- }
-
- public void setConPrecioRmExceso(Float conPrecioRmExceso) {
- this.conPrecioRmExceso = conPrecioRmExceso;
- }
-
- public void setConNtraDocRh(BigInteger conNtraDocRh) {
- this.conNtraDocRh = conNtraDocRh;
- }
-
- public void setConImpDocRhigienico(Float conImpDocRhigienico) {
- this.conImpDocRhigienico = conImpDocRhigienico;
- }
-
- public void setConImprmRhigienico(Float conImprmRhigienico) {
- this.conImprmRhigienico = conImprmRhigienico;
- }
-
- public void setConNtraDocRt(BigInteger conNtraDocRt) {
- this.conNtraDocRt = conNtraDocRt;
- }
-
- public void setConImpdocRTipologias(Float conImpdocRTipologias) {
- this.conImpdocRTipologias = conImpdocRTipologias;
- }
-
- public void setConImprmRtipologias(Float conImprmRtipologias) {
- this.conImprmRtipologias = conImprmRtipologias;
- }
-
- public void setConImpUmovil(Float conImpUmovil) {
- this.conImpUmovil = conImpUmovil;
- }
-
- public void setConPrecioSme(Float conPrecioSme) {
- this.conPrecioSme = conPrecioSme;
- }
-
- public BigInteger getDoc() {
- return doc;
- }
-
- public String getNif() {
- return nif;
- }
-
- public void setDoc(BigInteger doc) {
- this.doc = doc;
- }
-
- public void setNif(String nif) {
- this.nif = nif;
- }
-}
-
-
Deleted: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/PrcontraPK.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/PrcontraPK.java 2010-02-23 22:18:43 UTC (rev 18864)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/PrcontraPK.java 2010-02-23 23:55:06 UTC (rev 18865)
@@ -1,104 +0,0 @@
-// $Id:$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.ejb.test.metadata;
-
-import java.io.Serializable;
-import java.math.BigInteger;
-import javax.persistence.Column;
-import javax.persistence.Embeddable;
-
-/**
- * @author Hardy Ferentschik
- */
-@Embeddable
-public class PrcontraPK implements Serializable {
- private static final long serialVersionUID = 7441961985141369232L;
- @Column(name = "NUMERO", nullable = false)
- private BigInteger numero;
- @Column(name = "RENOV", nullable = false)
- private BigInteger renov;
- @Column(name = "TIPO", nullable = false)
- private BigInteger tipo;
-
- public PrcontraPK() {
- }
-
- public PrcontraPK(BigInteger numero, BigInteger renov, BigInteger tipo) {
- this.numero = numero;
- this.renov = renov;
- this.tipo = tipo;
- }
-
- public BigInteger getNumero() {
- return numero;
- }
-
- public void setNumero(BigInteger numero) {
- this.numero = numero;
- }
-
- public BigInteger getRenov() {
- return renov;
- }
-
- public void setRenov(BigInteger renov) {
- this.renov = renov;
- }
-
- public BigInteger getTipo() {
- return tipo;
- }
-
- public void setTipo(BigInteger tipo) {
- this.tipo = tipo;
- }
-
- @Override
- public int hashCode() {
- int hash = 0;
- hash += ( numero != null ? numero.hashCode() : 0 );
- hash += ( renov != null ? renov.hashCode() : 0 );
- hash += ( tipo != null ? tipo.hashCode() : 0 );
- return hash;
- }
-
- @Override
- public boolean equals(Object object) {
- if ( !( object instanceof PrcontraPK ) ) {
- return false;
- }
- PrcontraPK other = ( PrcontraPK ) object;
- if ( this.numero != other.numero && ( this.numero == null || !this.numero.equals( other.numero ) ) ) {
- return false;
- }
- if ( this.renov != other.renov && ( this.renov == null || !this.renov.equals( other.renov ) ) ) {
- return false;
- }
- if ( this.tipo != other.tipo && ( this.tipo == null || !this.tipo.equals( other.tipo ) ) ) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- return "org.kyrian.entity.muvale.PrcontraPK[numero=" + numero + ", renov=" + renov + ", tipo=" + tipo + "]";
- }
-}
-
-
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/StaticMetadataTest.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/StaticMetadataTest.java 2010-02-23 22:18:43 UTC (rev 18864)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/StaticMetadataTest.java 2010-02-23 23:55:06 UTC (rev 18865)
@@ -37,10 +37,6 @@
*/
public class StaticMetadataTest extends TestCase {
- public void testEmbeddedId() throws Exception {
- assertNotNull( Prcontra_.prcontraPK );
- }
-
public void testInjections() throws Exception {
// Address (embeddable)
assertNotNull( Address_.address1 );
@@ -140,9 +136,7 @@
Cattish.class,
Feline.class,
Garden.class,
- Flower.class,
- Prcontra.class,
- PrcontraPK.class
+ Flower.class
};
}
}
\ No newline at end of file
14 years, 12 months
Hibernate SVN: r18864 - in core/trunk: core/src/main/java/org/hibernate/event/def and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: gbadner
Date: 2010-02-23 17:18:43 -0500 (Tue, 23 Feb 2010)
New Revision: 18864
Added:
core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Info.java
core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Party.java
core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Plan.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/AbstractReadOnlyTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Course.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Enrolment.hbm.xml
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Enrolment.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyCriteriaQueryTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Student.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/StudentDTO.java
Removed:
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/criteria/
Modified:
core/trunk/core/src/main/java/org/hibernate/engine/EntityEntry.java
core/trunk/core/src/main/java/org/hibernate/event/def/DefaultFlushEntityEventListener.java
core/trunk/core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java
core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Contract.java
core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/ContractVariation.hbm.xml
core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/ImmutableTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/DataPoint.hbm.xml
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyProxyTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionLazyNonLazyTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyVersionedNodesTest.java
Log:
HHH-4810 : Persistent immutable and read-only entities are updated before being deleted
Modified: core/trunk/core/src/main/java/org/hibernate/engine/EntityEntry.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/engine/EntityEntry.java 2010-02-23 21:52:59 UTC (rev 18863)
+++ core/trunk/core/src/main/java/org/hibernate/engine/EntityEntry.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -46,6 +46,7 @@
private LockMode lockMode;
private Status status;
+ private Status previousStatus;
private final Serializable id;
private Object[] loadedState;
private Object[] deletedState;
@@ -72,6 +73,7 @@
final boolean disableVersionIncrement,
final boolean lazyPropertiesAreUnfetched) {
this.status=status;
+ this.previousStatus = null;
this.loadedState=loadedState;
this.id=id;
this.rowId=rowId;
@@ -91,6 +93,7 @@
final Serializable id,
final EntityMode entityMode,
final Status status,
+ final Status previousStatus,
final Object[] loadedState,
final Object[] deletedState,
final Object version,
@@ -104,6 +107,7 @@
this.id = id;
this.entityMode = entityMode;
this.status = status;
+ this.previousStatus = previousStatus;
this.loadedState = loadedState;
this.deletedState = deletedState;
this.version = version;
@@ -130,7 +134,10 @@
if (status==Status.READ_ONLY) {
loadedState = null; //memory optimization
}
- this.status = status;
+ if ( this.status != status ) {
+ this.previousStatus = this.status;
+ this.status = status;
+ }
}
public Serializable getId() {
@@ -220,6 +227,7 @@
* exists in the database
*/
public void postDelete() {
+ previousStatus = status;
status = Status.GONE;
existsInDatabase = false;
}
@@ -246,20 +254,31 @@
return loadedState[propertyIndex];
}
- public boolean requiresDirtyCheck(Object entity) {
-
- boolean isMutableInstance =
- status != Status.READ_ONLY &&
- persister.isMutable();
-
- return isMutableInstance && (
+ public boolean requiresDirtyCheck(Object entity) {
+ return isModifiableEntity() && (
getPersister().hasMutableProperties() ||
!FieldInterceptionHelper.isInstrumented( entity ) ||
FieldInterceptionHelper.extractFieldInterceptor( entity).isDirty()
);
-
}
+ /**
+ * Can the entity be modified?
+ *
+ * The entity is modifiable if all of the following are true:
+ * <ul>
+ * <li>the entity class is mutable</li>
+ * <li>the entity is not read-only</li>
+ * <li>if the current status is Status.DELETED, then the entity was not read-only when it was deleted</li>
+ * </ul>
+ * @return true, if the entity is modifiable; false, otherwise,
+ */
+ public boolean isModifiableEntity() {
+ return ( status != Status.READ_ONLY ) &&
+ ! ( status == Status.DELETED && previousStatus == Status.READ_ONLY ) &&
+ getPersister().isMutable();
+ }
+
public void forceLocked(Object entity, Object nextVersion) {
version = nextVersion;
loadedState[ persister.getVersionProperty() ] = version;
@@ -318,6 +337,7 @@
oos.writeObject( id );
oos.writeObject( entityMode.toString() );
oos.writeObject( status.toString() );
+ oos.writeObject( ( previousStatus == null ? "" : previousStatus.toString() ) );
// todo : potentially look at optimizing these two arrays
oos.writeObject( loadedState );
oos.writeObject( deletedState );
@@ -344,12 +364,17 @@
static EntityEntry deserialize(
ObjectInputStream ois,
SessionImplementor session) throws IOException, ClassNotFoundException {
+ String previousStatusString = null;
return new EntityEntry(
( session == null ? null : session.getFactory() ),
( String ) ois.readObject(),
( Serializable ) ois.readObject(),
EntityMode.parse( ( String ) ois.readObject() ),
Status.parse( ( String ) ois.readObject() ),
+ ( ( previousStatusString = ( String ) ois.readObject() ).length() == 0 ?
+ null :
+ Status.parse( previousStatusString )
+ ),
( Object[] ) ois.readObject(),
( Object[] ) ois.readObject(),
ois.readObject(),
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/DefaultFlushEntityEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/DefaultFlushEntityEventListener.java 2010-02-23 21:52:59 UTC (rev 18863)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/DefaultFlushEntityEventListener.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -38,7 +38,6 @@
import org.hibernate.engine.EntityEntry;
import org.hibernate.engine.EntityKey;
import org.hibernate.engine.Nullability;
-import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.engine.Status;
import org.hibernate.engine.Versioning;
@@ -254,10 +253,24 @@
if ( log.isTraceEnabled() ) {
if ( status == Status.DELETED ) {
- log.trace(
+ if ( ! persister.isMutable() ) {
+ log.trace(
+ "Updating immutable, deleted entity: " +
+ MessageHelper.infoString( persister, entry.getId(), session.getFactory() )
+ );
+ }
+ else if ( ! entry.isModifiableEntity() ) {
+ log.trace(
+ "Updating non-modifiable, deleted entity: " +
+ MessageHelper.infoString( persister, entry.getId(), session.getFactory() )
+ );
+ }
+ else {
+ log.trace(
"Updating deleted entity: " +
MessageHelper.infoString( persister, entry.getId(), session.getFactory() )
);
+ }
}
else {
log.trace(
@@ -303,7 +316,9 @@
values,
dirtyProperties,
event.hasDirtyCollection(),
- entry.getLoadedState(),
+ ( status == Status.DELETED && ! entry.isModifiableEntity() ?
+ persister.getPropertyValues( entity, entityMode ) :
+ entry.getLoadedState() ),
entry.getVersion(),
nextVersion,
entity,
@@ -447,7 +462,7 @@
}
private boolean hasDirtyCollections(FlushEntityEvent event, EntityPersister persister, Status status) {
- if ( isCollectionDirtyCheckNecessary(persister, status) ) {
+ if ( isCollectionDirtyCheckNecessary(persister, status ) ) {
DirtyCollectionSearchVisitor visitor = new DirtyCollectionSearchVisitor(
event.getSession(),
persister.getPropertyVersionability()
@@ -463,8 +478,8 @@
}
private boolean isCollectionDirtyCheckNecessary(EntityPersister persister, Status status) {
- return status==Status.MANAGED &&
- persister.isVersioned() &&
+ return status==Status.MANAGED &&
+ persister.isVersioned() &&
persister.hasCollections();
}
@@ -503,8 +518,28 @@
if ( !cannotDirtyCheck ) {
// dirty check against the usual snapshot of the entity
dirtyProperties = persister.findDirty( values, loadedState, entity, session );
-
}
+ else if ( entry.getStatus() == Status.DELETED && ! event.getEntityEntry().isModifiableEntity() ) {
+ // A non-modifiable (e.g., read-only or immutable) entity needs to be have
+ // references to transient entities set to null before being deleted. No other
+ // fields should be updated.
+ if ( values != entry.getDeletedState() ) {
+ throw new IllegalStateException(
+ "Entity has status Status.DELETED but values != entry.getDeletedState"
+ );
+ }
+ // Even if loadedState == null, we can dirty-check by comparing currentState and
+ // entry.getDeletedState() because the only fields to be updated are those that
+ // refer to transient entities that are being set to null.
+ // - currentState contains the entity's current property values.
+ // - entry.getDeletedState() contains the entity's current property values with
+ // references to transient entities set to null.
+ // - dirtyProperties will only contain properties that refer to transient entities
+ final Object[] currentState =
+ persister.getPropertyValues( event.getEntity(), event.getSession().getEntityMode() );
+ dirtyProperties = persister.findDirty( entry.getDeletedState(), currentState, entity, session );
+ cannotDirtyCheck = false;
+ }
else {
// dirty check against the database snapshot, if possible/necessary
final Object[] databaseSnapshot = getDatabaseSnapshot(session, persister, id);
Modified: core/trunk/core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java 2010-02-23 21:52:59 UTC (rev 18863)
+++ core/trunk/core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -63,6 +63,7 @@
import org.hibernate.engine.Mapping;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor;
+import org.hibernate.engine.Status;
import org.hibernate.engine.ValueInclusion;
import org.hibernate.engine.Versioning;
import org.hibernate.exception.JDBCExceptionHelper;
@@ -2751,8 +2752,21 @@
final boolean[] propsToUpdate;
final String[] updateStrings;
- if ( entityMetamodel.isDynamicUpdate() && dirtyFields != null ) {
- // For the case of dynamic-update="true", we need to generate the UPDATE SQL
+ EntityEntry entry = session.getPersistenceContext().getEntry( object );
+
+ // Ensure that an immutable or non-modifiable entity is not being updated unless it is
+ // in the process of being deleted.
+ if ( entry == null && ! isMutable() ) {
+ throw new IllegalStateException( "Updating immutable entity that is not in session yet!" );
+ }
+ if ( entry != null && ! isModifiableEntity( entry ) && entry.getStatus() != Status.DELETED ) {
+ throw new IllegalStateException( "Updating non-modifiable entity that is not being deleted!" );
+ }
+ if ( ( entityMetamodel.isDynamicUpdate() || ! isModifiableEntity( entry ) ) && dirtyFields != null ) {
+ // For the following cases we need to generate the UPDATE SQL
+ // - dynamic-update="true"
+ // - a non-modifiable entity (e.g., read-only or immutable) needs to have
+ // references to transient entities set to null before being deleted
propsToUpdate = getPropertiesToUpdate( dirtyFields, hasDirtyCollection );
// don't need to check laziness (dirty checking algorithm handles that)
updateStrings = new String[span];
@@ -3595,6 +3609,11 @@
return entityMetamodel.isMutable();
}
+ private boolean isModifiableEntity(EntityEntry entry) {
+
+ return ( entry == null ? isMutable() : entry.isModifiableEntity() );
+ }
+
public boolean isAbstract() {
return entityMetamodel.isAbstract();
}
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Contract.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Contract.java 2010-02-23 21:52:59 UTC (rev 18863)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Contract.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -3,7 +3,10 @@
import java.io.Serializable;
import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
+import java.util.Set;
public class Contract implements Serializable {
@@ -11,17 +14,38 @@
private String customerName;
private String type;
private List variations;
+ private Contract parent;
+ private Set subcontracts;
+ private Set plans;
+ private Set parties;
+ private Set infos;
public Contract() {
super();
}
- public Contract(String customerName, String type) {
+ public Contract(Plan plan, String customerName, String type) {
+ plans = new HashSet();
+ plans.add( plan );
+ if ( plan != null ) {
+ plan.getContracts().add( this );
+ }
this.customerName = customerName;
this.type = type;
variations = new ArrayList();
+ subcontracts = new HashSet();
+ parties = new HashSet();
+ infos = new HashSet();
}
+ public Set getPlans() {
+ return plans;
+ }
+
+ public void setPlans(Set plans) {
+ this.plans = plans;
+ }
+
public String getCustomerName() {
return customerName;
}
@@ -54,4 +78,55 @@
this.variations = variations;
}
+ public Contract getParent() {
+ return parent;
+ }
+
+ public void setParent(Contract parent) {
+ this.parent = parent;
+ }
+
+ public Set getSubcontracts() {
+ return subcontracts;
+ }
+
+ public void setSubcontracts(Set subcontracts) {
+ this.subcontracts = subcontracts;
+ }
+
+ public void addSubcontract(Contract subcontract) {
+ subcontracts.add( subcontract );
+ subcontract.setParent( this );
+ }
+
+ public Set getParties() {
+ return parties;
+ }
+
+ public void setParties(Set parties) {
+ this.parties = parties;
+ }
+
+ public void addParty(Party party) {
+ parties.add( party );
+ party.setContract( this );
+ }
+
+ public void removeParty(Party party) {
+ parties.remove( party );
+ party.setContract( null );
+ }
+
+ public Set getInfos() {
+ return infos;
+ }
+
+ public void setInfos(Set infos) {
+ this.infos = infos;
+ }
+
+ public void addInfo(Info info) {
+ infos.add( info );
+ info.setContract( this );
+ }
}
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/ContractVariation.hbm.xml
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/ContractVariation.hbm.xml 2010-02-23 21:52:59 UTC (rev 18863)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/ContractVariation.hbm.xml 2010-02-23 22:18:43 UTC (rev 18864)
@@ -10,7 +10,34 @@
-->
<hibernate-mapping package="org.hibernate.test.immutable">
-
+ <class name="Info" mutable="true">
+ <id name="id">
+ <generator class="increment"/>
+ </id>
+ <property name="text"/>
+ <many-to-one name="contract" not-null="false"/>
+ </class>
+
+ <class name="Plan" mutable="false">
+ <id name="id">
+ <generator class="increment"/>
+ </id>
+ <property name="description" not-null="true"/>
+ <set name="contracts" table="plan_contract" inverse="false" mutable="true" cascade="all" fetch="join">
+ <key column="plan"/>
+ <many-to-many column="contract" class="Contract"/>
+ </set>
+ </class>
+
+ <class name="Party" mutable="false">
+ <id name="id">
+ <generator class="increment"/>
+ </id>
+ <!-- <many-to-one name="contract" update="false" insert="false"/> -->
+ <many-to-one name="contract" not-null="true"/>
+ <property name="name" not-null="true"/>
+ </class>
+
<class name="Contract" mutable="false">
<id name="id">
<generator class="increment"/>
@@ -22,8 +49,27 @@
<key column="contract"/>
<one-to-many class="ContractVariation"/>
</bag>
+ <!-- <many-to-one name="parent" /> -->
+ <many-to-one name="parent" update="false" insert="false"/>
+ <set name="subcontracts" inverse="false"
+ mutable="true" cascade="all" fetch="join">
+ <key column="parent"/>
+ <one-to-many class="Contract"/>
+ </set>
+ <set name="plans" table="plan_contract" inverse="true" mutable="true" cascade="none">
+ <key column="contract"/>
+ <many-to-many column="plan" class="Plan"/>
+ </set>
+ <set name="parties" inverse="true" mutable="true" cascade="all" fetch="join">
+ <key column="contract"/>
+ <one-to-many class="Party"/>
+ </set>
+ <set name="infos" inverse="true" mutable="true" cascade="all" fetch="join">
+ <key column="contract"/>
+ <one-to-many class="Info"/>
+ </set>
</class>
-
+
<class name="ContractVariation" mutable="false">
<composite-id>
<key-many-to-one name="contract"/>
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/ImmutableTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/ImmutableTest.java 2010-02-23 21:52:59 UTC (rev 18863)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/ImmutableTest.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -33,6 +33,8 @@
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
import org.hibernate.criterion.Projections;
import org.hibernate.junit.functional.FunctionalTestCase;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
@@ -46,6 +48,11 @@
super(str);
}
+ public void configure(Configuration cfg) {
+ cfg.setProperty( Environment.GENERATE_STATISTICS, "true");
+ cfg.setProperty( Environment.STATEMENT_BATCH_SIZE, "0" );
+ }
+
public String[] getMappings() {
return new String[] { "immutable/ContractVariation.hbm.xml" };
}
@@ -55,11 +62,14 @@
}
public void testPersistImmutable() {
- Contract c = new Contract("gavin", "phone");
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
cv2.setText("more expensive");
+
+ clearCounts();
+
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist(c);
@@ -70,6 +80,10 @@
t.commit();
s.close();
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
@@ -90,10 +104,64 @@
assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
}
+ public void testPersistUpdateImmutableInSameTransaction() {
+ Contract c = new Contract( null, "gavin", "phone");
+ ContractVariation cv1 = new ContractVariation(1, c);
+ cv1.setText("expensive");
+ ContractVariation cv2 = new ContractVariation(2, c);
+ cv2.setText("more expensive");
+
+ clearCounts();
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.persist(c);
+ // c, cv1, and cv2 were added to s by s.persist(c) (not hibernate), so they are modifiable
+ assertFalse( s.isReadOnly( c ) );
+ assertFalse( s.isReadOnly( cv1 ) );
+ assertFalse( s.isReadOnly( cv2 ) );
+ c.setCustomerName( "gail" );
+ t.commit();
+ s.close();
+
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
+ s = openSession();
+ t = s.beginTransaction();
+ c = (Contract) s.createCriteria(Contract.class).uniqueResult();
+ // c was loaded into s by hibernate, so it should be read-only
+ assertTrue( s.isReadOnly( c ) );
+ assertEquals( c.getCustomerName(), "gavin" );
+ assertEquals( c.getVariations().size(), 2 );
+ Iterator it = c.getVariations().iterator();
+ cv1 = (ContractVariation) it.next();
+ assertEquals( cv1.getText(), "expensive" );
+ cv2 = (ContractVariation) it.next();
+ assertEquals( cv2.getText(), "more expensive" );
+ // cv1 and cv2 were loaded into s by hibernate, so they should be read-only
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertTrue( s.isReadOnly( cv2 ) );
+ s.delete(c);
+ assertEquals( s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ t.commit();
+ s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
+ }
+
public void testSaveImmutable() {
- Contract c = new Contract("gavin", "phone");
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
@@ -108,6 +176,10 @@
t.commit();
s.close();
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
@@ -128,10 +200,15 @@
assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
}
public void testSaveOrUpdateImmutable() {
- Contract c = new Contract("gavin", "phone");
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
@@ -146,6 +223,10 @@
t.commit();
s.close();
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
@@ -166,10 +247,15 @@
assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
}
public void testImmutable() {
- Contract c = new Contract("gavin", "phone");
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
@@ -183,7 +269,11 @@
assertFalse( s.isReadOnly( cv2 ) );
t.commit();
s.close();
-
+
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
@@ -201,7 +291,11 @@
assertTrue( s.isReadOnly( cv1 ) );
assertFalse( s.contains( cv2 ) );
s.close();
-
+
+ assertInsertCount( 0 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
@@ -222,10 +316,15 @@
assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
}
public void testPersistAndUpdateImmutable() {
- Contract c = new Contract("gavin", "phone");
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
@@ -241,6 +340,10 @@
t.commit();
s.close();
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
@@ -259,6 +362,10 @@
assertFalse( s.contains( cv2 ) );
s.close();
+ assertInsertCount( 0 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
@@ -279,10 +386,15 @@
assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
}
public void testUpdateAndDeleteManagedImmutable() {
- Contract c = new Contract("gavin", "phone");
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
@@ -293,6 +405,10 @@
t.commit();
s.close();
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
@@ -314,10 +430,15 @@
assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
}
public void testGetAndDeleteManagedImmutable() {
- Contract c = new Contract("gavin", "phone");
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
@@ -328,6 +449,10 @@
t.commit();
s.close();
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
c = (Contract) s.get( Contract.class, c.getId() );
@@ -349,10 +474,15 @@
assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
}
public void testDeleteDetachedImmutable() {
- Contract c = new Contract("gavin", "phone");
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
@@ -363,33 +493,26 @@
t.commit();
s.close();
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
s.delete( c );
- /*
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
- // c was loaded into s by hibernate, so it should be read-only
- assertTrue( s.isReadOnly( c ) );
- assertEquals( c.getCustomerName(), "gavin" );
- assertEquals( c.getVariations().size(), 2 );
- Iterator it = c.getVariations().iterator();
- cv1 = (ContractVariation) it.next();
- assertEquals( cv1.getText(), "expensive" );
- cv2 = (ContractVariation) it.next();
- assertEquals( cv2.getText(), "more expensive" );
- // cv1 and cv2 were loaded into s by hibernate, so they should be read-only
- assertTrue( s.isReadOnly( cv1 ) );
- assertTrue( s.isReadOnly( cv2 ) );
- s.delete(c);
- assertEquals( s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
- assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
- */
+ assertNull( c );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
}
public void testDeleteDetachedModifiedImmutable() {
- Contract c = new Contract("gavin", "phone");
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
@@ -400,35 +523,26 @@
t.commit();
s.close();
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
c.setCustomerName( "sherman" );
s.delete( c );
- /*
- c = (Contract) s.createCriteria(Contract.class).uniqueResult();
- // c was loaded into s by hibernate, so it should be read-only
- assertTrue( s.isReadOnly( c ) );
- assertEquals( c.getCustomerName(), "gavin" );
- assertEquals( c.getVariations().size(), 2 );
- Iterator it = c.getVariations().iterator();
- cv1 = (ContractVariation) it.next();
- assertEquals( cv1.getText(), "expensive" );
- cv2 = (ContractVariation) it.next();
- assertEquals( cv2.getText(), "more expensive" );
- // cv1 and cv2 were loaded into s by hibernate, so they should be read-only
- assertTrue( s.isReadOnly( cv1 ) );
- assertTrue( s.isReadOnly( cv2 ) );
- s.delete(c);
- assertEquals( s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
- assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
- */
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
}
public void testImmutableParentEntityWithUpdate() {
- Contract c = new Contract("gavin", "phone");
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
@@ -439,6 +553,10 @@
t.commit();
s.close();
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
c.setCustomerName("foo bar");
@@ -454,6 +572,8 @@
assertFalse( s.isReadOnly( cv2 ) );
s.close();
+ assertUpdateCount( 0 );
+
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
@@ -469,10 +589,15 @@
assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
}
public void testImmutableChildEntityWithUpdate() {
- Contract c = new Contract("gavin", "phone");
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
@@ -483,6 +608,10 @@
t.commit();
s.close();
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
cv1 = (ContractVariation) c.getVariations().iterator().next();
@@ -498,6 +627,8 @@
assertFalse( s.isReadOnly( cv2 ) );
s.close();
+ assertUpdateCount( 0 );
+
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
@@ -513,10 +644,15 @@
assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
}
public void testImmutableCollectionWithUpdate() {
- Contract c = new Contract("gavin", "phone");
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
@@ -527,6 +663,9 @@
t.commit();
s.close();
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+
s = openSession();
t = s.beginTransaction();
c.getVariations().add( new ContractVariation(3, c) );
@@ -542,6 +681,8 @@
s.close();
}
+ assertUpdateCount( 0 );
+
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
@@ -557,10 +698,70 @@
assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
}
+ public void testUnmodifiedImmutableParentEntityWithMerge() {
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
+ ContractVariation cv1 = new ContractVariation(1, c);
+ cv1.setText("expensive");
+ ContractVariation cv2 = new ContractVariation(2, c);
+ cv2.setText("more expensive");
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.persist(c);
+ t.commit();
+ s.close();
+
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
+ s = openSession();
+ t = s.beginTransaction();
+ c = ( Contract ) s.merge( c );
+ // c was loaded into s by hibernate in the merge process, so it is read-only
+ assertTrue( s.isReadOnly( c ) );
+ assertTrue( Hibernate.isInitialized( c.getVariations() ) );
+ Iterator it = c.getVariations().iterator();
+ cv1 = (ContractVariation) it.next();
+ cv2 = (ContractVariation) it.next();
+ // cv1 and cv2 were loaded into s by hibernate in the merge process, so they are read-only
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertTrue( s.isReadOnly( cv2 ) );
+ t.commit();
+ s.close();
+
+ assertUpdateCount( 0 );
+
+ s = openSession();
+ t = s.beginTransaction();
+ c = (Contract) s.createCriteria(Contract.class).uniqueResult();
+ assertEquals( c.getCustomerName(), "gavin" );
+ assertEquals( c.getVariations().size(), 2 );
+ it = c.getVariations().iterator();
+ cv1 = (ContractVariation) it.next();
+ assertEquals( cv1.getText(), "expensive" );
+ cv2 = (ContractVariation) it.next();
+ assertEquals( cv2.getText(), "more expensive" );
+ s.delete(c);
+ assertEquals( s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ t.commit();
+ s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
+ }
+
public void testImmutableParentEntityWithMerge() {
- Contract c = new Contract("gavin", "phone");
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
@@ -571,6 +772,10 @@
t.commit();
s.close();
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
c.setCustomerName("foo bar");
@@ -587,6 +792,8 @@
t.commit();
s.close();
+ assertUpdateCount( 0 );
+
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
@@ -602,10 +809,16 @@
assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
+
}
public void testImmutableChildEntityWithMerge() {
- Contract c = new Contract("gavin", "phone");
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
@@ -616,6 +829,10 @@
t.commit();
s.close();
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
cv1 = (ContractVariation) c.getVariations().iterator().next();
@@ -633,6 +850,8 @@
t.commit();
s.close();
+ assertUpdateCount( 0 );
+
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
@@ -648,10 +867,15 @@
assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
}
public void testImmutableCollectionWithMerge() {
- Contract c = new Contract("gavin", "phone");
+ clearCounts();
+
+ Contract c = new Contract( null, "gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
cv1.setText("expensive");
ContractVariation cv2 = new ContractVariation(2, c);
@@ -662,6 +886,11 @@
t.commit();
s.close();
+ assertInsertCount( 3 );
+ assertUpdateCount( 0 );
+
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
c.getVariations().add( new ContractVariation(3, c) );
@@ -693,6 +922,28 @@
assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 3 );
}
+
+ protected void clearCounts() {
+ getSessions().getStatistics().clear();
+ }
+
+ protected void assertInsertCount(int expected) {
+ int inserts = ( int ) getSessions().getStatistics().getEntityInsertCount();
+ assertEquals( "unexpected insert count", expected, inserts );
+ }
+
+ protected void assertUpdateCount(int expected) {
+ int updates = ( int ) getSessions().getStatistics().getEntityUpdateCount();
+ assertEquals( "unexpected update counts", expected, updates );
+ }
+
+ protected void assertDeleteCount(int expected) {
+ int deletes = ( int ) getSessions().getStatistics().getEntityDeleteCount();
+ assertEquals( "unexpected delete counts", expected, deletes );
+ }
}
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Info.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Info.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Info.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -0,0 +1,43 @@
+//$Id: Contract.java 7222 2005-06-19 17:22:01Z oneovthafew $
+package org.hibernate.test.immutable;
+
+import java.io.Serializable;
+
+public class Info implements Serializable {
+
+ private long id;
+ private String text;
+ private Contract contract;
+
+ public Info() {
+ super();
+ }
+
+ public Info(String text) {
+ this.text = text;
+ }
+
+ public String getText() {
+ return text;
+ }
+
+ public void setText(String text) {
+ this.text = text;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public Contract getContract() {
+ return contract;
+ }
+
+ public void setContract(Contract contract ) {
+ this.contract = contract;
+ }
+}
\ No newline at end of file
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Party.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Party.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Party.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -0,0 +1,47 @@
+//$Id: Contract.java 7222 2005-06-19 17:22:01Z oneovthafew $
+package org.hibernate.test.immutable;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+public class Party implements Serializable {
+
+ private long id;
+ private Contract contract;
+ private String name;
+
+ public Party() {
+ super();
+ }
+
+ public Party(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public Contract getContract() {
+ return contract;
+ }
+
+ public void setContract(Contract contract) {
+ this.contract = contract;
+ }
+}
\ No newline at end of file
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Plan.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Plan.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/Plan.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -0,0 +1,80 @@
+//$Id: ContractVariation.java 7222 2005-06-19 17:22:01Z oneovthafew $
+package org.hibernate.test.immutable;
+
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+public class Plan implements Serializable {
+
+ private long id;
+ private String description;
+ private Set contracts;
+
+ public Plan() {
+ this( null );
+ }
+
+ public Plan(String description) {
+ this.description = description;
+ contracts = new HashSet();
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Set getContracts() {
+ return contracts;
+ }
+
+ public void setContracts(Set contracts) {
+ this.contracts = contracts;
+ }
+
+ public void addContract(Contract contract) {
+ if ( ! contracts.add( contract ) ) {
+ return;
+ }
+ if ( contract.getParent() != null ) {
+ addContract( contract.getParent() );
+ }
+ contract.getPlans().add( this );
+ for ( Iterator it=contract.getSubcontracts().iterator(); it.hasNext(); ) {
+ Contract sub = ( Contract ) it.next();
+ addContract( sub );
+ }
+ }
+
+ public void removeContract(Contract contract) {
+ if ( contract.getParent() != null ) {
+ contract.getParent().getSubcontracts().remove( contract );
+ contract.setParent( null );
+ }
+ removeSubcontracts( contract );
+ contract.getPlans().remove( this );
+ contracts.remove( contract );
+ }
+
+ public void removeSubcontracts(Contract contract) {
+ for ( Iterator it=contract.getSubcontracts().iterator(); it.hasNext(); ) {
+ Contract sub = ( Contract ) it.next();
+ removeSubcontracts( sub );
+ sub.getPlans().remove( this );
+ contracts.remove( sub );
+ }
+ }
+}
\ No newline at end of file
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/AbstractReadOnlyTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/AbstractReadOnlyTest.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/AbstractReadOnlyTest.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -0,0 +1,79 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.test.readonly;
+
+import org.hibernate.CacheMode;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.junit.functional.FunctionalTestCase;
+
+/**
+ *
+ * @author Gail Badner
+ */
+public abstract class AbstractReadOnlyTest extends FunctionalTestCase {
+
+ public AbstractReadOnlyTest(String str) {
+ super(str);
+ }
+
+ public void configure(Configuration cfg) {
+ cfg.setProperty( Environment.GENERATE_STATISTICS, "true");
+ cfg.setProperty( Environment.STATEMENT_BATCH_SIZE, "0" );
+ }
+
+ public org.hibernate.classic.Session openSession() {
+ org.hibernate.classic.Session s = super.openSession();
+ s.setCacheMode( getSessionCacheMode() );
+ return s;
+ }
+
+ protected CacheMode getSessionCacheMode() {
+ return CacheMode.IGNORE;
+ }
+
+ public String getCacheConcurrencyStrategy() {
+ return null;
+ }
+
+ protected void clearCounts() {
+ getSessions().getStatistics().clear();
+ }
+
+ protected void assertInsertCount(int expected) {
+ int inserts = ( int ) getSessions().getStatistics().getEntityInsertCount();
+ assertEquals( "unexpected insert count", expected, inserts );
+ }
+
+ protected void assertUpdateCount(int expected) {
+ int updates = ( int ) getSessions().getStatistics().getEntityUpdateCount();
+ assertEquals( "unexpected update counts", expected, updates );
+ }
+
+ protected void assertDeleteCount(int expected) {
+ int deletes = ( int ) getSessions().getStatistics().getEntityDeleteCount();
+ assertEquals( "unexpected delete counts", expected, deletes );
+ }
+}
\ No newline at end of file
Copied: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Course.java (from rev 18852, core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/criteria/Course.java)
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Course.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Course.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -0,0 +1,22 @@
+//$Id: Course.java 5686 2005-02-12 07:27:32Z steveebersole $
+package org.hibernate.test.readonly;
+
+/**
+ * @author Gavin King
+ */
+public class Course {
+ private String courseCode;
+ private String description;
+ public String getCourseCode() {
+ return courseCode;
+ }
+ public void setCourseCode(String courseCode) {
+ this.courseCode = courseCode;
+ }
+ public String getDescription() {
+ return description;
+ }
+ public void setDescription(String description) {
+ this.description = description;
+ }
+}
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/DataPoint.hbm.xml
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/DataPoint.hbm.xml 2010-02-23 21:52:59 UTC (rev 18863)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/DataPoint.hbm.xml 2010-02-23 22:18:43 UTC (rev 18864)
@@ -13,10 +13,10 @@
<generator class="increment"/>
</id>
<property name="x">
- <column name="xval" not-null="true" precision="25" scale="19" unique-key="xy"/>
+ <column name="xval" not-null="true" precision="25" scale="20" unique-key="xy"/>
</property>
<property name="y">
- <column name="yval" not-null="true" precision="25" scale="19" unique-key="xy"/>
+ <column name="yval" not-null="true" precision="25" scale="20" unique-key="xy"/>
</property>
<property name="description"/>
</class>
Copied: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Enrolment.hbm.xml (from rev 18852, core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/criteria/Enrolment.hbm.xml)
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Enrolment.hbm.xml (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Enrolment.hbm.xml 2010-02-23 22:18:43 UTC (rev 18864)
@@ -0,0 +1,45 @@
+<?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 package="org.hibernate.test.readonly">
+
+ <class name="Course">
+ <id name="courseCode">
+ <generator class="assigned"/>
+ </id>
+ <property name="description"/>
+ </class>
+
+ <class name="Student">
+ <id name="studentNumber">
+ <column name="studentId"/>
+ <generator class="assigned"/>
+ </id>
+ <property name="name" not-null="true"/>
+ <set name="enrolments" inverse="true" cascade="delete">
+ <key column="studentId"/>
+ <one-to-many class="Enrolment"/>
+ </set>
+ <many-to-one name="preferredCourse" column="preferredCourseCode"/>
+ </class>
+
+ <class name="Enrolment">
+ <composite-id>
+ <key-property name="studentNumber">
+ <column name="studentId"/>
+ </key-property>
+ <key-property name="courseCode"/>
+ </composite-id>
+ <many-to-one name="student" insert="false" update="false">
+ <column name="studentId"/>
+ </many-to-one>
+ <many-to-one name="course" insert="false" update="false">
+ <column name="courseCode"/>
+ </many-to-one>
+ <property name="semester" not-null="true"/>
+ <property name="year" not-null="true"/>
+ </class>
+
+</hibernate-mapping>
Copied: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Enrolment.java (from rev 18852, core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/criteria/Enrolment.java)
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Enrolment.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Enrolment.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -0,0 +1,63 @@
+//$Id: Enrolment.java 6970 2005-05-31 20:24:41Z oneovthafew $
+package org.hibernate.test.readonly;
+
+import java.io.Serializable;
+
+/**
+ * @author Gavin King
+ */
+public class Enrolment implements Serializable {
+ private Student student;
+ private Course course;
+ private long studentNumber;
+ private String courseCode;
+ private short year;
+ private short semester;
+ public String getCourseCode() {
+ return courseCode;
+ }
+ public void setCourseCode(String courseId) {
+ this.courseCode = courseId;
+ }
+ public long getStudentNumber() {
+ return studentNumber;
+ }
+ public void setStudentNumber(long studentId) {
+ this.studentNumber = studentId;
+ }
+ public Course getCourse() {
+ return course;
+ }
+ public void setCourse(Course course) {
+ this.course = course;
+ }
+ public Student getStudent() {
+ return student;
+ }
+ public void setStudent(Student student) {
+ this.student = student;
+ }
+ public short getSemester() {
+ return semester;
+ }
+ public void setSemester(short semester) {
+ this.semester = semester;
+ }
+ public short getYear() {
+ return year;
+ }
+ public void setYear(short year) {
+ this.year = year;
+ }
+
+ public boolean equals(Object other) {
+ if ( !(other instanceof Enrolment) ) return false;
+ Enrolment that = (Enrolment) other;
+ return studentNumber==that.studentNumber &&
+ courseCode.equals(that.courseCode);
+ }
+
+ public int hashCode() {
+ return courseCode.hashCode();
+ }
+}
Copied: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyCriteriaQueryTest.java (from rev 18852, core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/criteria/ReadOnlyCriteriaQueryTest.java)
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyCriteriaQueryTest.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyCriteriaQueryTest.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -0,0 +1,1666 @@
+//$Id: CriteriaQueryTest.java 10976 2006-12-12 23:22:26Z steve.ebersole(a)jboss.com $
+package org.hibernate.test.readonly;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import junit.framework.Test;
+
+import org.hibernate.CacheMode;
+import org.hibernate.Criteria;
+import org.hibernate.FetchMode;
+import org.hibernate.Hibernate;
+import org.hibernate.ScrollableResults;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.criterion.DetachedCriteria;
+import org.hibernate.criterion.Example;
+import org.hibernate.criterion.MatchMode;
+import org.hibernate.criterion.Order;
+import org.hibernate.criterion.Projection;
+import org.hibernate.criterion.Projections;
+import org.hibernate.criterion.Property;
+import org.hibernate.criterion.Restrictions;
+import org.hibernate.criterion.Subqueries;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.proxy.HibernateProxy;
+import org.hibernate.proxy.LazyInitializer;
+import org.hibernate.test.hql.Animal;
+import org.hibernate.test.hql.Reptile;
+import org.hibernate.test.readonly.AbstractReadOnlyTest;
+import org.hibernate.transform.Transformers;
+import org.hibernate.type.Type;
+import org.hibernate.util.SerializationHelper;
+
+/**
+ * @author Gail Badner (adapted from org.hibernate.test.criteria.CriteriaQueryTest by Gavin King)
+ */
+public class ReadOnlyCriteriaQueryTest extends AbstractReadOnlyTest {
+
+ public ReadOnlyCriteriaQueryTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "readonly/Enrolment.hbm.xml" };
+ }
+
+ public void configure(Configuration cfg) {
+ super.configure( cfg );
+ cfg.setProperty( Environment.USE_QUERY_CACHE, "true" );
+ cfg.setProperty( Environment.CACHE_REGION_PREFIX, "criteriaquerytest" );
+ cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, "true" );
+ cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( ReadOnlyCriteriaQueryTest.class );
+ }
+
+ public void testModifiableSessionDefaultCriteria() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.persist(course);
+
+ Course coursePreferred = new Course();
+ coursePreferred.setCourseCode( "JBOSS" );
+ coursePreferred.setDescription( "JBoss" );
+ s.persist( coursePreferred );
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse( coursePreferred );
+ s.persist(gavin);
+
+ Enrolment enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 3);
+ enrolment.setYear((short) 1998);
+ enrolment.setStudent(gavin);
+ enrolment.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add( enrolment );
+ s.persist( enrolment );
+
+ t.commit();
+ s.close();
+
+ assertInsertCount( 4 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Criteria criteria = s.createCriteria( Student.class );
+ assertFalse( s.isDefaultReadOnly() );
+ assertFalse( criteria.isReadOnlyInitialized() );
+ assertFalse( criteria.isReadOnly() );
+ gavin = ( Student ) criteria.uniqueResult();
+ assertFalse( s.isDefaultReadOnly() );
+ assertFalse( criteria.isReadOnlyInitialized() );
+ assertFalse( criteria.isReadOnly() );
+ assertFalse( s.isReadOnly( gavin ) );
+ assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ checkProxyReadOnly( s, gavin.getPreferredCourse(), false );
+ assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ Hibernate.initialize( gavin.getPreferredCourse() );
+ assertTrue( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ checkProxyReadOnly( s, gavin.getPreferredCourse(), false );
+ assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ Hibernate.initialize( gavin.getEnrolments() );
+ assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ assertEquals( 1, gavin.getEnrolments().size() );
+ enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next();
+ assertFalse( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ Hibernate.initialize( enrolment.getCourse() );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ s.delete(gavin.getPreferredCourse());
+ s.delete(gavin);
+ s.delete( enrolment.getCourse() );
+ s.delete(enrolment);
+ t.commit();
+ s.close();
+
+ assertUpdateCount( 1 );
+ assertDeleteCount( 4 );
+ }
+
+ public void testModifiableSessionReadOnlyCriteria() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.persist(course);
+
+ Course coursePreferred = new Course();
+ coursePreferred.setCourseCode( "JBOSS" );
+ coursePreferred.setDescription( "JBoss" );
+ s.persist( coursePreferred );
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse( coursePreferred );
+ s.persist(gavin);
+
+ Enrolment enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 3);
+ enrolment.setYear((short) 1998);
+ enrolment.setStudent(gavin);
+ enrolment.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add( enrolment );
+ s.persist( enrolment );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Criteria criteria = s.createCriteria( Student.class ).setReadOnly( true );
+ assertFalse( s.isDefaultReadOnly() );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertTrue( criteria.isReadOnly() );
+ gavin = ( Student ) criteria.uniqueResult();
+ assertFalse( s.isDefaultReadOnly() );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertTrue( criteria.isReadOnly() );
+ assertTrue( s.isReadOnly( gavin ) );
+ assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ checkProxyReadOnly( s, gavin.getPreferredCourse(), true );
+ assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ Hibernate.initialize( gavin.getPreferredCourse() );
+ assertTrue( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ checkProxyReadOnly( s, gavin.getPreferredCourse(), true );
+ assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ Hibernate.initialize( gavin.getEnrolments() );
+ assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ assertEquals( 1, gavin.getEnrolments().size() );
+ enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next();
+ assertFalse( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ Hibernate.initialize( enrolment.getCourse() );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ s.delete(gavin.getPreferredCourse());
+ s.delete(gavin);
+ s.delete( enrolment.getCourse() );
+ s.delete(enrolment);
+ t.commit();
+ s.close();
+ }
+
+ public void testModifiableSessionModifiableCriteria() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.persist(course);
+
+ Course coursePreferred = new Course();
+ coursePreferred.setCourseCode( "JBOSS" );
+ coursePreferred.setDescription( "JBoss" );
+ s.persist( coursePreferred );
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse( coursePreferred );
+ s.persist(gavin);
+
+ Enrolment enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 3);
+ enrolment.setYear((short) 1998);
+ enrolment.setStudent(gavin);
+ enrolment.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add( enrolment );
+ s.persist( enrolment );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Criteria criteria = s.createCriteria( Student.class );
+ assertFalse( s.isDefaultReadOnly() );
+ assertFalse( criteria.isReadOnlyInitialized() );
+ assertFalse( criteria.isReadOnly() );
+ criteria.setReadOnly( false );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertFalse( criteria.isReadOnly() );
+ gavin = ( Student ) criteria.uniqueResult();
+ assertFalse( s.isDefaultReadOnly() );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertFalse( criteria.isReadOnly() );
+ assertFalse( s.isReadOnly( gavin ) );
+ assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ checkProxyReadOnly( s, gavin.getPreferredCourse(), false );
+ assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ Hibernate.initialize( gavin.getPreferredCourse() );
+ assertTrue( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ checkProxyReadOnly( s, gavin.getPreferredCourse(), false );
+ assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ Hibernate.initialize( gavin.getEnrolments() );
+ assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ assertEquals( 1, gavin.getEnrolments().size() );
+ enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next();
+ assertFalse( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ Hibernate.initialize( enrolment.getCourse() );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ s.delete(gavin.getPreferredCourse());
+ s.delete(gavin);
+ s.delete( enrolment.getCourse() );
+ s.delete(enrolment);
+ t.commit();
+ s.close();
+ }
+
+ public void testReadOnlySessionDefaultCriteria() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.persist(course);
+
+ Course coursePreferred = new Course();
+ coursePreferred.setCourseCode( "JBOSS" );
+ coursePreferred.setDescription( "JBoss" );
+ s.persist( coursePreferred );
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse( coursePreferred );
+ s.persist(gavin);
+
+ Enrolment enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 3);
+ enrolment.setYear((short) 1998);
+ enrolment.setStudent(gavin);
+ enrolment.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add( enrolment );
+ s.persist( enrolment );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ Criteria criteria = s.createCriteria( Student.class );
+ assertTrue( s.isDefaultReadOnly() );
+ assertFalse( criteria.isReadOnlyInitialized() );
+ assertTrue( criteria.isReadOnly() );
+ gavin = ( Student ) criteria.uniqueResult();
+ assertTrue( s.isDefaultReadOnly() );
+ assertFalse( criteria.isReadOnlyInitialized() );
+ assertTrue( criteria.isReadOnly() );
+ assertTrue( s.isReadOnly( gavin ) );
+ assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ checkProxyReadOnly( s, gavin.getPreferredCourse(), true );
+ assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ Hibernate.initialize( gavin.getPreferredCourse() );
+ assertTrue( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ checkProxyReadOnly( s, gavin.getPreferredCourse(), true );
+ assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ Hibernate.initialize( gavin.getEnrolments() );
+ assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ assertEquals( 1, gavin.getEnrolments().size() );
+ enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next();
+ assertTrue( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), true );
+ Hibernate.initialize( enrolment.getCourse() );
+ checkProxyReadOnly( s, enrolment.getCourse(), true );
+ s.delete(gavin.getPreferredCourse());
+ s.delete(gavin);
+ s.delete( enrolment.getCourse() );
+ s.delete(enrolment);
+ t.commit();
+ s.close();
+ }
+
+ public void testReadOnlySessionReadOnlyCriteria() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.persist(course);
+
+ Course coursePreferred = new Course();
+ coursePreferred.setCourseCode( "JBOSS" );
+ coursePreferred.setDescription( "JBoss" );
+ s.persist( coursePreferred );
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse( coursePreferred );
+ s.persist(gavin);
+
+ Enrolment enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 3);
+ enrolment.setYear((short) 1998);
+ enrolment.setStudent(gavin);
+ enrolment.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add( enrolment );
+ s.persist( enrolment );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ Criteria criteria = s.createCriteria( Student.class );
+ assertTrue( s.isDefaultReadOnly() );
+ assertFalse( criteria.isReadOnlyInitialized() );
+ assertTrue( criteria.isReadOnly() );
+ criteria.setReadOnly( true );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertTrue( criteria.isReadOnly() );
+ gavin = ( Student ) criteria.uniqueResult();
+ assertTrue( s.isDefaultReadOnly() );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertTrue( criteria.isReadOnly() );
+ assertTrue( s.isReadOnly( gavin ) );
+ assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ checkProxyReadOnly( s, gavin.getPreferredCourse(), true );
+ assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ Hibernate.initialize( gavin.getPreferredCourse() );
+ assertTrue( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ checkProxyReadOnly( s, gavin.getPreferredCourse(), true );
+ assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ Hibernate.initialize( gavin.getEnrolments() );
+ assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ assertEquals( 1, gavin.getEnrolments().size() );
+ enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next();
+ assertTrue( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), true );
+ Hibernate.initialize( enrolment.getCourse() );
+ checkProxyReadOnly( s, enrolment.getCourse(), true );
+ s.delete(gavin.getPreferredCourse());
+ s.delete(gavin);
+ s.delete( enrolment.getCourse() );
+ s.delete(enrolment);
+ t.commit();
+ s.close();
+ }
+
+ public void testReadOnlySessionModifiableCriteria() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.persist(course);
+
+ Course coursePreferred = new Course();
+ coursePreferred.setCourseCode( "JBOSS" );
+ coursePreferred.setDescription( "JBoss" );
+ s.persist( coursePreferred );
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse( coursePreferred );
+ s.persist(gavin);
+
+ Enrolment enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 3);
+ enrolment.setYear((short) 1998);
+ enrolment.setStudent(gavin);
+ enrolment.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add( enrolment );
+ s.persist( enrolment );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ Criteria criteria = s.createCriteria( Student.class );
+ assertTrue( s.isDefaultReadOnly() );
+ assertFalse( criteria.isReadOnlyInitialized() );
+ assertTrue( criteria.isReadOnly() );
+ criteria.setReadOnly( false );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertFalse( criteria.isReadOnly() );
+ gavin = ( Student ) criteria.uniqueResult();
+ assertTrue( s.isDefaultReadOnly() );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertFalse( criteria.isReadOnly() );
+ assertFalse( s.isReadOnly( gavin ) );
+ assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ checkProxyReadOnly( s, gavin.getPreferredCourse(), false );
+ assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ Hibernate.initialize( gavin.getPreferredCourse() );
+ assertTrue( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ checkProxyReadOnly( s, gavin.getPreferredCourse(), false);
+ assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ Hibernate.initialize( gavin.getEnrolments() );
+ assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ assertEquals( 1, gavin.getEnrolments().size() );
+ enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next();
+ assertTrue( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), true );
+ Hibernate.initialize( enrolment.getCourse() );
+ checkProxyReadOnly( s, enrolment.getCourse(), true );
+ s.delete(gavin.getPreferredCourse());
+ s.delete(gavin);
+ s.delete( enrolment.getCourse() );
+ s.delete(enrolment);
+ t.commit();
+ s.close();
+ }
+
+ public void testReadOnlyCriteriaReturnsModifiableExistingEntity() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.persist(course);
+
+ Course coursePreferred = new Course();
+ coursePreferred.setCourseCode( "JBOSS" );
+ coursePreferred.setDescription( "JBoss" );
+ s.persist( coursePreferred );
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse( coursePreferred );
+ s.persist(gavin);
+
+ Enrolment enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 3);
+ enrolment.setYear((short) 1998);
+ enrolment.setStudent(gavin);
+ enrolment.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add( enrolment );
+ s.persist( enrolment );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ assertFalse( s.isDefaultReadOnly() );
+ coursePreferred = ( Course ) s.get( Course.class, coursePreferred.getCourseCode() );
+ assertFalse( s.isReadOnly( coursePreferred ) );
+ Criteria criteria = s.createCriteria( Student.class ).setReadOnly( true );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertTrue( criteria.isReadOnly() );
+ gavin = ( Student ) criteria.uniqueResult();
+ assertFalse( s.isDefaultReadOnly() );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertTrue( criteria.isReadOnly() );
+ assertTrue( s.isReadOnly( gavin ) );
+ assertFalse( s.isReadOnly( coursePreferred ) );
+ assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ Hibernate.initialize( gavin.getEnrolments() );
+ assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ assertEquals( 1, gavin.getEnrolments().size() );
+ enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next();
+ assertFalse( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ Hibernate.initialize( enrolment.getCourse() );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ s.delete(gavin.getPreferredCourse());
+ s.delete(gavin);
+ s.delete( enrolment.getCourse() );
+ s.delete(enrolment);
+ t.commit();
+ s.close();
+ }
+
+ public void testReadOnlyCriteriaReturnsExistingModifiableProxyNotInit() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.persist(course);
+
+ Course coursePreferred = new Course();
+ coursePreferred.setCourseCode( "JBOSS" );
+ coursePreferred.setDescription( "JBoss" );
+ s.persist( coursePreferred );
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse( coursePreferred );
+ s.persist(gavin);
+
+ Enrolment enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 3);
+ enrolment.setYear((short) 1998);
+ enrolment.setStudent(gavin);
+ enrolment.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add( enrolment );
+ s.persist( enrolment );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ assertFalse( s.isDefaultReadOnly() );
+ coursePreferred = ( Course ) s.load( Course.class, coursePreferred.getCourseCode() );
+ assertFalse( Hibernate.isInitialized( coursePreferred ) );
+ checkProxyReadOnly( s, coursePreferred, false );
+ Criteria criteria = s.createCriteria( Student.class ).setReadOnly( true );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertTrue( criteria.isReadOnly() );
+ gavin = ( Student ) criteria.uniqueResult();
+ assertFalse( s.isDefaultReadOnly() );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertTrue( criteria.isReadOnly() );
+ assertTrue( s.isReadOnly( gavin ) );
+ assertFalse( Hibernate.isInitialized( coursePreferred ) );
+ checkProxyReadOnly( s, coursePreferred, false );
+ Hibernate.initialize( coursePreferred );
+ checkProxyReadOnly( s, coursePreferred, false );
+ assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ Hibernate.initialize( gavin.getEnrolments() );
+ assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ assertEquals( 1, gavin.getEnrolments().size() );
+ enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next();
+ assertFalse( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ Hibernate.initialize( enrolment.getCourse() );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ s.delete(gavin.getPreferredCourse());
+ s.delete(gavin);
+ s.delete( enrolment.getCourse() );
+ s.delete(enrolment);
+ t.commit();
+ s.close();
+ }
+
+ public void testReadOnlyCriteriaReturnsExistingModifiableProxyInit() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.persist(course);
+
+ Course coursePreferred = new Course();
+ coursePreferred.setCourseCode( "JBOSS" );
+ coursePreferred.setDescription( "JBoss" );
+ s.persist( coursePreferred );
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse( coursePreferred );
+ s.persist(gavin);
+
+ Enrolment enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 3);
+ enrolment.setYear((short) 1998);
+ enrolment.setStudent(gavin);
+ enrolment.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add( enrolment );
+ s.persist( enrolment );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ assertFalse( s.isDefaultReadOnly() );
+ coursePreferred = ( Course ) s.load( Course.class, coursePreferred.getCourseCode() );
+ assertFalse( Hibernate.isInitialized( coursePreferred ) );
+ checkProxyReadOnly( s, coursePreferred, false );
+ Hibernate.initialize( coursePreferred );
+ checkProxyReadOnly( s, coursePreferred, false );
+ Criteria criteria = s.createCriteria( Student.class ).setReadOnly( true );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertTrue( criteria.isReadOnly() );
+ gavin = ( Student ) criteria.uniqueResult();
+ assertFalse( s.isDefaultReadOnly() );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertTrue( criteria.isReadOnly() );
+ assertTrue( s.isReadOnly( gavin ) );
+ assertTrue( Hibernate.isInitialized( coursePreferred ) );
+ checkProxyReadOnly( s, coursePreferred, false );
+ assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ Hibernate.initialize( gavin.getEnrolments() );
+ assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ assertEquals( 1, gavin.getEnrolments().size() );
+ enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next();
+ assertFalse( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ Hibernate.initialize( enrolment.getCourse() );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ s.delete(gavin.getPreferredCourse());
+ s.delete(gavin);
+ s.delete( enrolment.getCourse() );
+ s.delete(enrolment);
+ t.commit();
+ s.close();
+ }
+
+ public void testModifiableCriteriaReturnsExistingReadOnlyEntity() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.persist(course);
+
+ Course coursePreferred = new Course();
+ coursePreferred.setCourseCode( "JBOSS" );
+ coursePreferred.setDescription( "JBoss" );
+ s.persist( coursePreferred );
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse( coursePreferred );
+ s.persist(gavin);
+
+ Enrolment enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 3);
+ enrolment.setYear((short) 1998);
+ enrolment.setStudent(gavin);
+ enrolment.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add( enrolment );
+ s.persist( enrolment );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ assertFalse( s.isDefaultReadOnly() );
+ coursePreferred = ( Course ) s.get( Course.class, coursePreferred.getCourseCode() );
+ assertFalse( s.isReadOnly( coursePreferred ) );
+ s.setReadOnly( coursePreferred, true );
+ Criteria criteria = s.createCriteria( Student.class ).setReadOnly( false );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertFalse( criteria.isReadOnly() );
+ gavin = ( Student ) criteria.uniqueResult();
+ assertFalse( s.isDefaultReadOnly() );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertFalse( criteria.isReadOnly() );
+ assertFalse( s.isReadOnly( gavin ) );
+ assertTrue( s.isReadOnly( coursePreferred ) );
+ assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ Hibernate.initialize( gavin.getEnrolments() );
+ assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ assertEquals( 1, gavin.getEnrolments().size() );
+ enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next();
+ assertFalse( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ Hibernate.initialize( enrolment.getCourse() );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ s.delete(gavin.getPreferredCourse());
+ s.delete(gavin);
+ s.delete( enrolment.getCourse() );
+ s.delete(enrolment);
+ t.commit();
+ s.close();
+ }
+
+ public void testModifiableCriteriaReturnsExistingReadOnlyProxyNotInit() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.persist(course);
+
+ Course coursePreferred = new Course();
+ coursePreferred.setCourseCode( "JBOSS" );
+ coursePreferred.setDescription( "JBoss" );
+ s.persist( coursePreferred );
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse( coursePreferred );
+ s.persist(gavin);
+
+ Enrolment enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 3);
+ enrolment.setYear((short) 1998);
+ enrolment.setStudent(gavin);
+ enrolment.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add( enrolment );
+ s.persist( enrolment );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ assertFalse( s.isDefaultReadOnly() );
+ coursePreferred = ( Course ) s.load( Course.class, coursePreferred.getCourseCode() );
+ assertFalse( Hibernate.isInitialized( coursePreferred ) );
+ checkProxyReadOnly( s, coursePreferred, false );
+ s.setReadOnly( coursePreferred, true );
+ checkProxyReadOnly( s, coursePreferred, true );
+ Criteria criteria = s.createCriteria( Student.class ).setReadOnly( false );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertFalse( criteria.isReadOnly() );
+ gavin = ( Student ) criteria.uniqueResult();
+ assertFalse( s.isDefaultReadOnly() );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertFalse( criteria.isReadOnly() );
+ assertFalse( s.isReadOnly( gavin ) );
+ assertFalse( Hibernate.isInitialized( coursePreferred ) );
+ checkProxyReadOnly( s, coursePreferred, true );
+ Hibernate.initialize( coursePreferred );
+ checkProxyReadOnly( s, coursePreferred, true );
+ assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ Hibernate.initialize( gavin.getEnrolments() );
+ assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ assertEquals( 1, gavin.getEnrolments().size() );
+ enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next();
+ assertFalse( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ Hibernate.initialize( enrolment.getCourse() );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ s.delete(gavin.getPreferredCourse());
+ s.delete(gavin);
+ s.delete( enrolment.getCourse() );
+ s.delete(enrolment);
+ t.commit();
+ s.close();
+ }
+
+ public void testModifiableCriteriaReturnsExistingReadOnlyProxyInit() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.persist(course);
+
+ Course coursePreferred = new Course();
+ coursePreferred.setCourseCode( "JBOSS" );
+ coursePreferred.setDescription( "JBoss" );
+ s.persist( coursePreferred );
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse( coursePreferred );
+ s.persist(gavin);
+
+ Enrolment enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 3);
+ enrolment.setYear((short) 1998);
+ enrolment.setStudent(gavin);
+ enrolment.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add( enrolment );
+ s.persist( enrolment );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ assertFalse( s.isDefaultReadOnly() );
+ coursePreferred = ( Course ) s.load( Course.class, coursePreferred.getCourseCode() );
+ assertFalse( Hibernate.isInitialized( coursePreferred ) );
+ checkProxyReadOnly( s, coursePreferred, false );
+ Hibernate.initialize( coursePreferred );
+ checkProxyReadOnly( s, coursePreferred, false );
+ s.setReadOnly( coursePreferred, true );
+ checkProxyReadOnly( s, coursePreferred, true );
+ Criteria criteria = s.createCriteria( Student.class ).setReadOnly( false );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertFalse( criteria.isReadOnly() );
+ gavin = ( Student ) criteria.uniqueResult();
+ assertFalse( s.isDefaultReadOnly() );
+ assertTrue( criteria.isReadOnlyInitialized() );
+ assertFalse( criteria.isReadOnly() );
+ assertFalse( s.isReadOnly( gavin ) );
+ assertTrue( Hibernate.isInitialized( coursePreferred ) );
+ checkProxyReadOnly( s, coursePreferred, true );
+ assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ Hibernate.initialize( gavin.getEnrolments() );
+ assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ assertEquals( 1, gavin.getEnrolments().size() );
+ enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next();
+ assertFalse( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ Hibernate.initialize( enrolment.getCourse() );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ s.delete(gavin.getPreferredCourse());
+ s.delete(gavin);
+ s.delete( enrolment.getCourse() );
+ s.delete(enrolment);
+ t.commit();
+ s.close();
+ }
+
+ public void testScrollCriteria() {
+ Session session = openSession();
+ Transaction t = session.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ session.persist(course);
+ session.flush();
+ session.clear();
+ ScrollableResults sr = session.createCriteria(Course.class).setReadOnly( true ).scroll();
+ assertTrue( sr.next() );
+ course = (Course) sr.get(0);
+ assertNotNull(course);
+ assertTrue( session.isReadOnly( course ) );
+ sr.close();
+ session.delete(course);
+
+ t.commit();
+ session.close();
+
+ }
+
+ public void testSubselect() {
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.persist(course);
+
+ Course coursePreferred = new Course();
+ coursePreferred.setCourseCode( "JBOSS" );
+ coursePreferred.setDescription( "JBoss" );
+ s.persist( coursePreferred );
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse( coursePreferred );
+ s.persist(gavin);
+
+ Enrolment enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 3);
+ enrolment.setYear((short) 1998);
+ enrolment.setStudent(gavin);
+ enrolment.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add(enrolment);
+ s.persist(enrolment);
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ DetachedCriteria dc = DetachedCriteria.forClass(Student.class)
+ .add( Property.forName("studentNumber").eq( new Long(232) ) )
+ .setProjection( Property.forName("name") );
+ gavin = ( Student ) s.createCriteria(Student.class)
+ .add( Subqueries.exists(dc) )
+ .setReadOnly( true )
+ .uniqueResult();
+ assertFalse( s.isDefaultReadOnly() );
+ assertTrue( s.isReadOnly( gavin ) );
+ assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ checkProxyReadOnly( s, gavin.getPreferredCourse(), true );
+ assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ Hibernate.initialize( gavin.getPreferredCourse() );
+ assertTrue( Hibernate.isInitialized( gavin.getPreferredCourse() ) );
+ checkProxyReadOnly( s, gavin.getPreferredCourse(), true );
+ assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ Hibernate.initialize( gavin.getEnrolments() );
+ assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) );
+ assertEquals( 1, gavin.getEnrolments().size() );
+ enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next();
+ assertFalse( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ Hibernate.initialize( enrolment.getCourse() );
+ checkProxyReadOnly( s, enrolment.getCourse(), false );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ DetachedCriteria dc2 = DetachedCriteria.forClass(Student.class, "st")
+ .add( Property.forName("st.studentNumber").eqProperty("e.studentNumber") )
+ .setProjection( Property.forName("name") );
+ enrolment = ( Enrolment ) s.createCriteria(Enrolment.class, "e")
+ .add( Subqueries.eq("Gavin King", dc2) )
+ .setReadOnly( true )
+ .uniqueResult();
+ assertTrue( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), true );
+ Hibernate.initialize( enrolment.getCourse() );
+ assertTrue( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), true );
+ assertFalse( Hibernate.isInitialized( enrolment.getStudent() ) );
+ checkProxyReadOnly( s, enrolment.getStudent(), true );
+ Hibernate.initialize( enrolment.getStudent() );
+ assertTrue( Hibernate.isInitialized( enrolment.getStudent() ) );
+ checkProxyReadOnly( s, enrolment.getStudent(), true );
+ assertFalse( Hibernate.isInitialized( enrolment.getStudent().getPreferredCourse() ) );
+ checkProxyReadOnly( s, enrolment.getStudent().getPreferredCourse(), false );
+ Hibernate.initialize( enrolment.getStudent().getPreferredCourse() );
+ assertTrue( Hibernate.isInitialized( enrolment.getStudent().getPreferredCourse() ) );
+ checkProxyReadOnly( s, enrolment.getStudent().getPreferredCourse(), false );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ DetachedCriteria dc3 = DetachedCriteria.forClass(Student.class, "st")
+ .createCriteria("enrolments")
+ .createCriteria("course")
+ .add( Property.forName("description").eq("Hibernate Training") )
+ .setProjection( Property.forName("st.name") );
+ enrolment = ( Enrolment ) s.createCriteria(Enrolment.class, "e")
+ .add( Subqueries.eq("Gavin King", dc3) )
+ .setReadOnly( true )
+ .uniqueResult();
+ assertTrue( s.isReadOnly( enrolment ) );
+ assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), true );
+ Hibernate.initialize( enrolment.getCourse() );
+ assertTrue( Hibernate.isInitialized( enrolment.getCourse() ) );
+ checkProxyReadOnly( s, enrolment.getCourse(), true );
+ assertFalse( Hibernate.isInitialized( enrolment.getStudent() ) );
+ checkProxyReadOnly( s, enrolment.getStudent(), true );
+ Hibernate.initialize( enrolment.getStudent() );
+ assertTrue( Hibernate.isInitialized( enrolment.getStudent() ) );
+ checkProxyReadOnly( s, enrolment.getStudent(), true );
+ assertFalse( Hibernate.isInitialized( enrolment.getStudent().getPreferredCourse() ) );
+ checkProxyReadOnly( s, enrolment.getStudent().getPreferredCourse(), false );
+ Hibernate.initialize( enrolment.getStudent().getPreferredCourse() );
+ assertTrue( Hibernate.isInitialized( enrolment.getStudent().getPreferredCourse() ) );
+ checkProxyReadOnly( s, enrolment.getStudent().getPreferredCourse(), false );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete(gavin.getPreferredCourse());
+ s.delete(gavin);
+ enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next();
+ s.delete( enrolment.getCourse() );
+ s.delete(enrolment);
+ t.commit();
+ s.close();
+ }
+
+ public void testDetachedCriteria() {
+
+ DetachedCriteria dc = DetachedCriteria.forClass(Student.class)
+ .add( Property.forName("name").eq("Gavin King") )
+ .addOrder( Order.asc("studentNumber") );
+
+ byte[] bytes = SerializationHelper.serialize(dc);
+
+ dc = (DetachedCriteria) SerializationHelper.deserialize(bytes);
+
+ Session session = openSession();
+ Transaction t = session.beginTransaction();
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ Student bizarroGavin = new Student();
+ bizarroGavin.setName("Gavin King");
+ bizarroGavin.setStudentNumber(666);
+ session.persist(bizarroGavin);
+ session.persist(gavin);
+
+ t.commit();
+ session.close();
+
+ session = openSession();
+ t = session.beginTransaction();
+
+ List result = dc.getExecutableCriteria(session)
+ .setMaxResults(3)
+ .setReadOnly( true )
+ .list();
+
+ assertEquals( result.size(), 2 );
+ gavin = ( Student ) result.get( 0 );
+ bizarroGavin = ( Student ) result.get( 1 );
+ assertEquals( 232, gavin.getStudentNumber() );
+ assertEquals( 666, bizarroGavin.getStudentNumber() );
+ assertTrue( session.isReadOnly( gavin ) );
+ assertTrue( session.isReadOnly( bizarroGavin ) );
+
+ session.delete(gavin);
+ session.delete(bizarroGavin);
+ t.commit();
+ session.close();
+ }
+
+ public void testTwoAliasesCache() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.save(course);
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(666);
+ s.save(gavin);
+
+ Student xam = new Student();
+ xam.setName("Max Rydahl Andersen");
+ xam.setStudentNumber(101);
+ s.save(xam);
+
+ Enrolment enrolment1 = new Enrolment();
+ enrolment1.setCourse(course);
+ enrolment1.setCourseCode(course.getCourseCode());
+ enrolment1.setSemester((short) 1);
+ enrolment1.setYear((short) 1999);
+ enrolment1.setStudent(xam);
+ enrolment1.setStudentNumber(xam.getStudentNumber());
+ xam.getEnrolments().add(enrolment1);
+ s.save(enrolment1);
+
+ Enrolment enrolment2 = new Enrolment();
+ enrolment2.setCourse(course);
+ enrolment2.setCourseCode(course.getCourseCode());
+ enrolment2.setSemester((short) 3);
+ enrolment2.setYear((short) 1998);
+ enrolment2.setStudent(gavin);
+ enrolment2.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add(enrolment2);
+ s.save(enrolment2);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ List list = s.createCriteria(Enrolment.class)
+ .createAlias("student", "s")
+ .createAlias("course", "c")
+ .add( Restrictions.isNotEmpty("s.enrolments") )
+ .setCacheable(true)
+ .setReadOnly( true )
+ .list();
+
+ assertEquals( list.size(), 2 );
+
+ Enrolment e = ( Enrolment ) list.get( 0 );
+ if ( e.getStudent().getStudentNumber() == xam.getStudentNumber() ) {
+ enrolment1 = e;
+ enrolment2 = ( Enrolment ) list.get( 1 );
+ }
+ else if ( e.getStudent().getStudentNumber() == xam.getStudentNumber() ) {
+ enrolment2 = e;
+ enrolment1 = ( Enrolment ) list.get( 1 );
+ }
+ else {
+ fail( "Enrolment has unknown student number: " + e.getStudent().getStudentNumber() );
+ }
+
+ assertTrue( s.isReadOnly( enrolment1 ) );
+ assertTrue( s.isReadOnly( enrolment2 ) );
+ assertTrue( s.isReadOnly( enrolment1.getCourse() ) );
+ assertTrue( s.isReadOnly( enrolment2.getCourse() ) );
+ assertSame( enrolment1.getCourse(), enrolment2.getCourse() );
+ assertTrue( s.isReadOnly( enrolment1.getStudent() ) );
+ assertTrue( s.isReadOnly( enrolment2.getStudent() ) );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ list = s.createCriteria(Enrolment.class)
+ .createAlias("student", "s")
+ .createAlias("course", "c")
+ .setReadOnly( true )
+ .add( Restrictions.isNotEmpty("s.enrolments") )
+ .setCacheable(true)
+ .setReadOnly( true )
+ .list();
+
+ assertEquals( list.size(), 2 );
+
+ e = ( Enrolment ) list.get( 0 );
+ if ( e.getStudent().getStudentNumber() == xam.getStudentNumber() ) {
+ enrolment1 = e;
+ enrolment2 = ( Enrolment ) list.get( 1 );
+ }
+ else if ( e.getStudent().getStudentNumber() == xam.getStudentNumber() ) {
+ enrolment2 = e;
+ enrolment1 = ( Enrolment ) list.get( 1 );
+ }
+ else {
+ fail( "Enrolment has unknown student number: " + e.getStudent().getStudentNumber() );
+ }
+
+ assertTrue( s.isReadOnly( enrolment1 ) );
+ assertTrue( s.isReadOnly( enrolment2 ) );
+ assertTrue( s.isReadOnly( enrolment1.getCourse() ) );
+ assertTrue( s.isReadOnly( enrolment2.getCourse() ) );
+ assertSame( enrolment1.getCourse(), enrolment2.getCourse() );
+ assertTrue( s.isReadOnly( enrolment1.getStudent() ) );
+ assertTrue( s.isReadOnly( enrolment2.getStudent() ) );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ list = s.createCriteria(Enrolment.class)
+ .setReadOnly( true )
+ .createAlias("student", "s")
+ .createAlias("course", "c")
+ .add( Restrictions.isNotEmpty("s.enrolments") )
+ .setCacheable(true)
+ .list();
+
+ assertEquals( list.size(), 2 );
+
+ e = ( Enrolment ) list.get( 0 );
+ if ( e.getStudent().getStudentNumber() == xam.getStudentNumber() ) {
+ enrolment1 = e;
+ enrolment2 = ( Enrolment ) list.get( 1 );
+ }
+ else if ( e.getStudent().getStudentNumber() == xam.getStudentNumber() ) {
+ enrolment2 = e;
+ enrolment1 = ( Enrolment ) list.get( 1 );
+ }
+ else {
+ fail( "Enrolment has unknown student number: " + e.getStudent().getStudentNumber() );
+ }
+
+ assertTrue( s.isReadOnly( enrolment1 ) );
+ assertTrue( s.isReadOnly( enrolment2 ) );
+ assertTrue( s.isReadOnly( enrolment1.getCourse() ) );
+ assertTrue( s.isReadOnly( enrolment2.getCourse() ) );
+ assertSame( enrolment1.getCourse(), enrolment2.getCourse() );
+ assertTrue( s.isReadOnly( enrolment1.getStudent() ) );
+ assertTrue( s.isReadOnly( enrolment2.getStudent() ) );
+
+ s.delete( enrolment1 );
+ s.delete( enrolment2 );
+ s.delete( enrolment1.getCourse() );
+ s.delete( enrolment1.getStudent() );
+ s.delete( enrolment2.getStudent() );
+
+ t.commit();
+ s.close();
+ }
+
+ /*
+ public void testProjectionsUsingProperty() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Course course = new Course();
+ course.setCourseCode("HIB");
+ course.setDescription("Hibernate Training");
+ s.save(course);
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(667);
+ s.save(gavin);
+
+ Student xam = new Student();
+ xam.setName("Max Rydahl Andersen");
+ xam.setStudentNumber(101);
+ s.save(xam);
+
+ Enrolment enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 1);
+ enrolment.setYear((short) 1999);
+ enrolment.setStudent(xam);
+ enrolment.setStudentNumber(xam.getStudentNumber());
+ xam.getEnrolments().add(enrolment);
+ s.save(enrolment);
+
+ enrolment = new Enrolment();
+ enrolment.setCourse(course);
+ enrolment.setCourseCode(course.getCourseCode());
+ enrolment.setSemester((short) 3);
+ enrolment.setYear((short) 1998);
+ enrolment.setStudent(gavin);
+ enrolment.setStudentNumber(gavin.getStudentNumber());
+ gavin.getEnrolments().add(enrolment);
+ s.save(enrolment);
+
+ s.flush();
+
+ Long count = (Long) s.createCriteria(Enrolment.class)
+ .setProjection( Property.forName("studentNumber").count().setDistinct() )
+ .uniqueResult();
+ assertEquals(count, new Long(2));
+
+ Object object = s.createCriteria(Enrolment.class)
+ .setProjection( Projections.projectionList()
+ .add( Property.forName("studentNumber").count() )
+ .add( Property.forName("studentNumber").max() )
+ .add( Property.forName("studentNumber").min() )
+ .add( Property.forName("studentNumber").avg() )
+ )
+ .uniqueResult();
+ Object[] result = (Object[])object;
+
+ assertEquals(new Long(2),result[0]);
+ assertEquals(new Long(667),result[1]);
+ assertEquals(new Long(101),result[2]);
+ assertEquals(384.0, ( (Double) result[3] ).doubleValue(), 0.01);
+
+
+ s.createCriteria(Enrolment.class)
+ .add( Property.forName("studentNumber").gt( new Long(665) ) )
+ .add( Property.forName("studentNumber").lt( new Long(668) ) )
+ .add( Property.forName("courseCode").like("HIB", MatchMode.START) )
+ .add( Property.forName("year").eq( new Short( (short) 1999 ) ) )
+ .addOrder( Property.forName("studentNumber").asc() )
+ .uniqueResult();
+
+ List resultWithMaps = s.createCriteria(Enrolment.class)
+ .setProjection( Projections.projectionList()
+ .add( Property.forName("studentNumber").as("stNumber") )
+ .add( Property.forName("courseCode").as("cCode") )
+ )
+ .add( Property.forName("studentNumber").gt( new Long(665) ) )
+ .add( Property.forName("studentNumber").lt( new Long(668) ) )
+ .addOrder( Property.forName("studentNumber").asc() )
+ .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP)
+ .list();
+
+ assertEquals(1, resultWithMaps.size());
+ Map m1 = (Map) resultWithMaps.get(0);
+
+ assertEquals(new Long(667), m1.get("stNumber"));
+ assertEquals(course.getCourseCode(), m1.get("cCode"));
+
+ resultWithMaps = s.createCriteria(Enrolment.class)
+ .setProjection( Property.forName("studentNumber").as("stNumber") )
+ .addOrder( Order.desc("stNumber") )
+ .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP)
+ .list();
+
+ assertEquals(2, resultWithMaps.size());
+ Map m0 = (Map) resultWithMaps.get(0);
+ m1 = (Map) resultWithMaps.get(1);
+
+ assertEquals(new Long(101), m1.get("stNumber"));
+ assertEquals(new Long(667), m0.get("stNumber"));
+
+
+ List resultWithAliasedBean = s.createCriteria(Enrolment.class)
+ .createAlias("student", "st")
+ .createAlias("course", "co")
+ .setProjection( Projections.projectionList()
+ .add( Property.forName("st.name").as("studentName") )
+ .add( Property.forName("co.description").as("courseDescription") )
+ )
+ .addOrder( Order.desc("studentName") )
+ .setResultTransformer( Transformers.aliasToBean(StudentDTO.class) )
+ .list();
+
+ assertEquals(2, resultWithAliasedBean.size());
+
+ StudentDTO dto = (StudentDTO) resultWithAliasedBean.get(0);
+ assertNotNull(dto.getDescription());
+ assertNotNull(dto.getName());
+
+ s.createCriteria(Student.class)
+ .add( Restrictions.like("name", "Gavin", MatchMode.START) )
+ .addOrder( Order.asc("name") )
+ .createCriteria("enrolments", "e")
+ .addOrder( Order.desc("year") )
+ .addOrder( Order.desc("semester") )
+ .createCriteria("course","c")
+ .addOrder( Order.asc("description") )
+ .setProjection( Projections.projectionList()
+ .add( Property.forName("this.name") )
+ .add( Property.forName("e.year") )
+ .add( Property.forName("e.semester") )
+ .add( Property.forName("c.courseCode") )
+ .add( Property.forName("c.description") )
+ )
+ .uniqueResult();
+
+ Projection p1 = Projections.projectionList()
+ .add( Property.forName("studentNumber").count() )
+ .add( Property.forName("studentNumber").max() )
+ .add( Projections.rowCount() );
+
+ Projection p2 = Projections.projectionList()
+ .add( Property.forName("studentNumber").min() )
+ .add( Property.forName("studentNumber").avg() )
+ .add( Projections.sqlProjection(
+ "1 as constOne, count(*) as countStar",
+ new String[] { "constOne", "countStar" },
+ new Type[] { Hibernate.INTEGER, Hibernate.INTEGER }
+ ) );
+
+ Object[] array = (Object[]) s.createCriteria(Enrolment.class)
+ .setProjection( Projections.projectionList().add(p1).add(p2) )
+ .uniqueResult();
+
+ assertEquals( array.length, 7 );
+
+ List list = s.createCriteria(Enrolment.class)
+ .createAlias("student", "st")
+ .createAlias("course", "co")
+ .setProjection( Projections.projectionList()
+ .add( Property.forName("co.courseCode").group() )
+ .add( Property.forName("st.studentNumber").count().setDistinct() )
+ .add( Property.forName("year").group() )
+ )
+ .list();
+
+ assertEquals( list.size(), 2 );
+
+ s.delete(gavin);
+ s.delete(xam);
+ s.delete(course);
+
+ t.commit();
+ s.close();
+ }
+
+ public void testRestrictionOnSubclassCollection() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ s.createCriteria( Reptile.class )
+ .add( Restrictions.isEmpty( "offspring" ) )
+ .list();
+
+ s.createCriteria( Reptile.class )
+ .add( Restrictions.isNotEmpty( "offspring" ) )
+ .list();
+
+ t.rollback();
+ s.close();
+ }
+
+ public void testClassProperty() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ // HQL: from Animal a where a.mother.class = Reptile
+ Criteria c = s.createCriteria(Animal.class,"a")
+ .createAlias("mother","m")
+ .add( Property.forName("m.class").eq(Reptile.class) );
+ c.list();
+ t.rollback();
+ s.close();
+ }
+
+ public void testProjectedId() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.createCriteria(Course.class).setProjection( Projections.property("courseCode") ).list();
+ s.createCriteria(Course.class).setProjection( Projections.id() ).list();
+ t.rollback();
+ s.close();
+ }
+
+ public void testSubcriteriaJoinTypes() {
+ Session session = openSession();
+ Transaction t = session.beginTransaction();
+
+ Course courseA = new Course();
+ courseA.setCourseCode("HIB-A");
+ courseA.setDescription("Hibernate Training A");
+ session.persist(courseA);
+
+ Course courseB = new Course();
+ courseB.setCourseCode("HIB-B");
+ courseB.setDescription("Hibernate Training B");
+ session.persist(courseB);
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse(courseA);
+ session.persist(gavin);
+
+ Student leonardo = new Student();
+ leonardo.setName("Leonardo Quijano");
+ leonardo.setStudentNumber(233);
+ leonardo.setPreferredCourse(courseB);
+ session.persist(leonardo);
+
+ Student johnDoe = new Student();
+ johnDoe.setName("John Doe");
+ johnDoe.setStudentNumber(235);
+ johnDoe.setPreferredCourse(null);
+ session.persist(johnDoe);
+
+ List result = session.createCriteria( Student.class )
+ .setProjection( Property.forName("preferredCourse.courseCode") )
+ .createCriteria( "preferredCourse", Criteria.LEFT_JOIN )
+ .addOrder( Order.asc( "courseCode" ) )
+ .list();
+ assertEquals( 3, result.size() );
+ // can't be sure of NULL comparison ordering aside from they should
+ // either come first or last
+ if ( result.get( 0 ) == null ) {
+ assertEquals( "HIB-A", result.get(1) );
+ assertEquals( "HIB-B", result.get(2) );
+ }
+ else {
+ assertNull( result.get(2) );
+ assertEquals( "HIB-A", result.get(0) );
+ assertEquals( "HIB-B", result.get(1) );
+ }
+
+ result = session.createCriteria( Student.class )
+ .setFetchMode( "preferredCourse", FetchMode.JOIN )
+ .createCriteria( "preferredCourse", Criteria.LEFT_JOIN )
+ .addOrder( Order.asc( "courseCode" ) )
+ .list();
+ assertEquals( 3, result.size() );
+ assertNotNull( result.get(0) );
+ assertNotNull( result.get(1) );
+ assertNotNull( result.get(2) );
+
+ result = session.createCriteria( Student.class )
+ .setFetchMode( "preferredCourse", FetchMode.JOIN )
+ .createAlias( "preferredCourse", "pc", Criteria.LEFT_JOIN )
+ .addOrder( Order.asc( "pc.courseCode" ) )
+ .list();
+ assertEquals( 3, result.size() );
+ assertNotNull( result.get(0) );
+ assertNotNull( result.get(1) );
+ assertNotNull( result.get(2) );
+
+ session.delete(gavin);
+ session.delete(leonardo);
+ session.delete(johnDoe);
+ session.delete(courseA);
+ session.delete(courseB);
+ t.commit();
+ session.close();
+ }
+
+ public void testAliasJoinCriterion() {
+ Session session = openSession();
+ Transaction t = session.beginTransaction();
+
+ Course courseA = new Course();
+ courseA.setCourseCode("HIB-A");
+ courseA.setDescription("Hibernate Training A");
+ session.persist(courseA);
+
+ Course courseB = new Course();
+ courseB.setCourseCode("HIB-B");
+ courseB.setDescription("Hibernate Training B");
+ session.persist(courseB);
+
+ Student gavin = new Student();
+ gavin.setName("Gavin King");
+ gavin.setStudentNumber(232);
+ gavin.setPreferredCourse(courseA);
+ session.persist(gavin);
+
+ Student leonardo = new Student();
+ leonardo.setName("Leonardo Quijano");
+ leonardo.setStudentNumber(233);
+ leonardo.setPreferredCourse(courseB);
+ session.persist(leonardo);
+
+ Student johnDoe = new Student();
+ johnDoe.setName("John Doe");
+ johnDoe.setStudentNumber(235);
+ johnDoe.setPreferredCourse(null);
+ session.persist(johnDoe);
+
+ // test == on one value exists
+ List result = session.createCriteria( Student.class )
+ .createAlias( "preferredCourse", "pc", Criteria.LEFT_JOIN, Restrictions.eq("pc.courseCode", "HIB-A") )
+ .setProjection( Property.forName("pc.courseCode") )
+ .addOrder(Order.asc("pc.courseCode"))
+ .list();
+
+ assertEquals( 3, result.size() );
+
+ // can't be sure of NULL comparison ordering aside from they should
+ // either come first or last
+ if ( result.get( 0 ) == null ) {
+ assertNull(result.get(1));
+ assertEquals( "HIB-A", result.get(2) );
+ }
+ else {
+ assertNull( result.get(2) );
+ assertNull( result.get(1) );
+ assertEquals( "HIB-A", result.get(0) );
+ }
+
+ // test == on non existent value
+ result = session.createCriteria( Student.class )
+ .createAlias( "preferredCourse", "pc", Criteria.LEFT_JOIN, Restrictions.eq("pc.courseCode", "HIB-R") )
+ .setProjection( Property.forName("pc.courseCode") )
+ .addOrder(Order.asc("pc.courseCode"))
+ .list();
+
+ assertEquals( 3, result.size() );
+ assertNull( result.get(2) );
+ assertNull( result.get(1) );
+ assertNull(result.get(0) );
+
+ // test != on one existing value
+ result = session.createCriteria( Student.class )
+ .createAlias( "preferredCourse", "pc", Criteria.LEFT_JOIN, Restrictions.ne("pc.courseCode", "HIB-A") )
+ .setProjection( Property.forName("pc.courseCode") )
+ .addOrder(Order.asc("pc.courseCode"))
+ .list();
+
+ assertEquals( 3, result.size() );
+ // can't be sure of NULL comparison ordering aside from they should
+ // either come first or last
+ if ( result.get( 0 ) == null ) {
+ assertNull( result.get(1) );
+ assertEquals( "HIB-B", result.get(2) );
+ }
+ else {
+ assertEquals( "HIB-B", result.get(0) );
+ assertNull( result.get(1) );
+ assertNull( result.get(2) );
+ }
+
+ session.delete(gavin);
+ session.delete(leonardo);
+ session.delete(johnDoe);
+ session.delete(courseA);
+ session.delete(courseB);
+ t.commit();
+ session.close();
+ }
+ */
+
+ private void checkProxyReadOnly(Session s, Object proxy, boolean expectedReadOnly) {
+ assertTrue( proxy instanceof HibernateProxy );
+ LazyInitializer li = ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer();
+ assertSame( s, li.getSession() );
+ assertEquals( expectedReadOnly, s.isReadOnly( proxy ) );
+ assertEquals( expectedReadOnly, li.isReadOnly() );
+ assertEquals( Hibernate.isInitialized( proxy ), ! li.isUninitialized() );
+ if ( Hibernate.isInitialized( proxy ) ) {
+ assertEquals( expectedReadOnly, s.isReadOnly( li.getImplementation() ) );
+ }
+ }
+
+}
+
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyProxyTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyProxyTest.java 2010-02-23 21:52:59 UTC (rev 18863)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyProxyTest.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -52,7 +52,7 @@
*
* @author Gail Badner
*/
-public class ReadOnlyProxyTest extends FunctionalTestCase {
+public class ReadOnlyProxyTest extends AbstractReadOnlyTest {
public ReadOnlyProxyTest(String str) {
super(str);
@@ -62,14 +62,6 @@
return new String[] { "readonly/DataPoint.hbm.xml", "readonly/TextHolder.hbm.xml" };
}
- public void configure(Configuration cfg) {
- cfg.setProperty(Environment.STATEMENT_BATCH_SIZE, "20");
- }
-
- public String getCacheConcurrencyStrategy() {
- return null;
- }
-
public static Test suite() {
return new FunctionalTestClassTestSuite( ReadOnlyProxyTest.class );
}
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionLazyNonLazyTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionLazyNonLazyTest.java 2010-02-23 21:52:59 UTC (rev 18863)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionLazyNonLazyTest.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -66,7 +66,7 @@
*
* @author Gail Badner
*/
-public class ReadOnlySessionLazyNonLazyTest extends FunctionalTestCase {
+public class ReadOnlySessionLazyNonLazyTest extends AbstractReadOnlyTest {
public ReadOnlySessionLazyNonLazyTest(String str) {
super(str);
@@ -76,14 +76,6 @@
return new String[] { "readonly/DataPoint.hbm.xml" };
}
- public void configure(Configuration cfg) {
- cfg.setProperty(Environment.STATEMENT_BATCH_SIZE, "20");
- }
-
- public String getCacheConcurrencyStrategy() {
- return null;
- }
-
public static Test suite() {
return new FunctionalTestClassTestSuite( ReadOnlySessionLazyNonLazyTest.class );
}
@@ -106,7 +98,6 @@
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -195,7 +186,6 @@
Set expectedReadOnlyObjects = new HashSet();
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -278,7 +268,6 @@
DataPoint lazyDataPointOrig = ( DataPoint ) cOrig.getLazyDataPoints().iterator().next();
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -362,7 +351,6 @@
DataPoint lazyDataPointOrig = ( DataPoint ) cOrig.getLazyDataPoints().iterator().next();
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -449,7 +437,6 @@
DataPoint lazyDataPointOrig = ( DataPoint ) cOrig.getLazyDataPoints().iterator().next();
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -533,7 +520,6 @@
DataPoint lazyDataPointOrig = ( DataPoint ) cOrig.getLazyDataPoints().iterator().next();
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -618,7 +604,6 @@
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -697,7 +682,6 @@
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -767,7 +751,6 @@
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -847,7 +830,6 @@
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -916,7 +898,6 @@
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -961,7 +942,6 @@
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -1045,7 +1025,6 @@
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -1118,7 +1097,6 @@
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -1199,7 +1177,6 @@
Session s = openSession();
assertFalse( s.isDefaultReadOnly() );
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
@@ -1257,14 +1234,12 @@
Container cOrig = createContainer();
Session s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
t.commit();
s.close();
s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
t = s.beginTransaction();
List list = s.createQuery( "from Container c left outer join c.nonLazyInfo where c.id = :id" )
.setLong( "id", cOrig.getId() )
@@ -1301,14 +1276,12 @@
Container cOrig = createContainer();
Session s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
t.commit();
s.close();
s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
t = s.beginTransaction();
List list = s.createQuery( "from Container c left join fetch c.nonLazyInfo where c.id = :id" )
.setLong( "id", cOrig.getId() )
@@ -1348,14 +1321,12 @@
Container cOrig = createContainer();
Session s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
s.save( cOrig );
t.commit();
s.close();
s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
t = s.beginTransaction();
Container c = ( Container ) s.get( Container.class, cOrig.getId() );
assertNotNull( c );
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java 2010-02-23 21:52:59 UTC (rev 18863)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -48,7 +48,7 @@
*
* @author Gail Badner
*/
-public class ReadOnlySessionTest extends FunctionalTestCase {
+public class ReadOnlySessionTest extends AbstractReadOnlyTest {
public ReadOnlySessionTest(String str) {
super(str);
@@ -58,14 +58,6 @@
return new String[] { "readonly/DataPoint.hbm.xml", "readonly/TextHolder.hbm.xml" };
}
- public void configure(Configuration cfg) {
- cfg.setProperty(Environment.STATEMENT_BATCH_SIZE, "20");
- }
-
- public String getCacheConcurrencyStrategy() {
- return null;
- }
-
public static Test suite() {
return new FunctionalTestClassTestSuite( ReadOnlySessionTest.class );
}
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyTest.java 2010-02-23 21:52:59 UTC (rev 18863)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyTest.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -47,7 +47,7 @@
* @author Gavin King
* @author Gail Badner
*/
-public class ReadOnlyTest extends FunctionalTestCase {
+public class ReadOnlyTest extends AbstractReadOnlyTest {
public ReadOnlyTest(String str) {
super(str);
@@ -57,21 +57,14 @@
return new String[] { "readonly/DataPoint.hbm.xml", "readonly/TextHolder.hbm.xml" };
}
- public void configure(Configuration cfg) {
- cfg.setProperty(Environment.STATEMENT_BATCH_SIZE, "20");
- }
-
- public String getCacheConcurrencyStrategy() {
- return null;
- }
-
public static Test suite() {
return new FunctionalTestClassTestSuite( ReadOnlyTest.class );
}
public void testReadOnlyOnProxies() {
+ clearCounts();
+
Session s = openSession();
- s.setCacheMode( CacheMode.IGNORE );
s.beginTransaction();
DataPoint dp = new DataPoint();
dp.setX( new BigDecimal( 0.1d ).setScale(19, BigDecimal.ROUND_DOWN) );
@@ -82,8 +75,11 @@
s.getTransaction().commit();
s.close();
+ assertInsertCount( 1 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
s.beginTransaction();
dp = ( DataPoint ) s.load( DataPoint.class, new Long( dpId ) );
assertFalse( "was initialized", Hibernate.isInitialized( dp ) );
@@ -96,20 +92,27 @@
s.getTransaction().commit();
s.close();
+ assertUpdateCount( 0 );
+
s = openSession();
s.beginTransaction();
List list = s.createQuery( "from DataPoint where description = 'changed'" ).list();
assertEquals( "change written to database", 0, list.size() );
- s.createQuery("delete from DataPoint").executeUpdate();
+ assertEquals( 1, s.createQuery("delete from DataPoint").executeUpdate() );
s.getTransaction().commit();
s.close();
+
+ assertUpdateCount( 0 );
+ //deletes from Query.executeUpdate() are not tracked
+ //assertDeleteCount( 1 );
}
public void testReadOnlyMode() {
-
+
+ clearCounts();
+
Session s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
- Transaction t = s.beginTransaction();
+ Transaction t = s.beginTransaction();
for ( int i=0; i<100; i++ ) {
DataPoint dp = new DataPoint();
dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
@@ -118,9 +121,12 @@
}
t.commit();
s.close();
-
+
+ assertInsertCount( 100 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
t = s.beginTransaction();
int i = 0;
ScrollableResults sr = s.createQuery("from DataPoint dp order by dp.x asc")
@@ -134,20 +140,27 @@
dp.setDescription("done!");
}
t.commit();
+
+ assertUpdateCount( 1 );
+ clearCounts();
+
s.clear();
t = s.beginTransaction();
List single = s.createQuery("from DataPoint where description='done!'").list();
assertEquals( single.size(), 1 );
- s.createQuery("delete from DataPoint").executeUpdate();
+ assertEquals( 100, s.createQuery("delete from DataPoint").executeUpdate() );
t.commit();
s.close();
-
+
+ assertUpdateCount( 0 );
+ //deletes from Query.executeUpdate() are not tracked
+ //assertDeleteCount( 100 );
}
public void testReadOnlyModeAutoFlushOnQuery() {
+ clearCounts();
Session s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
DataPoint dpFirst = null;
for ( int i=0; i<100; i++ ) {
@@ -156,9 +169,18 @@
dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
s.save(dp);
}
+
+ assertInsertCount( 0 );
+ assertUpdateCount( 0 );
+
ScrollableResults sr = s.createQuery("from DataPoint dp order by dp.x asc")
.setReadOnly(true)
.scroll(ScrollMode.FORWARD_ONLY);
+
+ assertInsertCount( 100 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
while ( sr.next() ) {
DataPoint dp = (DataPoint) sr.get(0);
assertFalse( s.isReadOnly( dp ) );
@@ -167,12 +189,62 @@
t.commit();
s.close();
+ assertUpdateCount( 0 );
+ assertDeleteCount( 100 );
}
+ public void testSaveReadOnlyModifyInSaveTransaction() {
+ clearCounts();
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setDescription( "original" );
+ dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ s.setReadOnly( dp, true );
+ dp.setDescription( "different" );
+ t.commit();
+ s.close();
+
+ assertInsertCount( 1 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
+ s = openSession();
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ s.setReadOnly( dp, true );
+ assertEquals( "original", dp.getDescription() );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ s.refresh( dp );
+ assertEquals( "original", dp.getDescription() );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ t.commit();
+
+ assertInsertCount( 0 );
+ assertUpdateCount( 0 );
+
+ s.clear();
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertEquals( "original", dp.getDescription() );
+ s.delete( dp );
+ t.commit();
+ s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 1 );
+ clearCounts();
+ }
+
public void testReadOnlyRefresh() {
+ clearCounts();
Session s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
DataPoint dp = new DataPoint();
dp.setDescription( "original" );
@@ -182,8 +254,11 @@
t.commit();
s.close();
+ assertInsertCount( 1 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
t = s.beginTransaction();
dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
s.setReadOnly( dp, true );
@@ -196,6 +271,9 @@
assertEquals( "changed", dp.getDescription() );
t.commit();
+ assertInsertCount( 0 );
+ assertUpdateCount( 0 );
+
s.clear();
t = s.beginTransaction();
dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
@@ -204,12 +282,15 @@
t.commit();
s.close();
+ assertUpdateCount( 0 );
+ assertDeleteCount( 1 );
+ clearCounts();
}
public void testReadOnlyRefreshDetached() {
+ clearCounts();
Session s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
DataPoint dp = new DataPoint();
dp.setDescription( "original" );
@@ -219,8 +300,11 @@
t.commit();
s.close();
+ assertInsertCount( 1 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
t = s.beginTransaction();
dp.setDescription( "changed" );
assertEquals( "changed", dp.getDescription() );
@@ -236,6 +320,9 @@
assertFalse( s.isReadOnly( dp ) );
t.commit();
+ assertInsertCount( 0 );
+ assertUpdateCount( 0 );
+
s.clear();
t = s.beginTransaction();
dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
@@ -243,12 +330,16 @@
s.delete( dp );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 1 );
}
public void testReadOnlyDelete() {
+ clearCounts();
+
Session s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
DataPoint dp = new DataPoint();
dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
@@ -257,8 +348,11 @@
t.commit();
s.close();
+ assertInsertCount( 1 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
t = s.beginTransaction();
dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
s.setReadOnly( dp, true );
@@ -266,6 +360,9 @@
t.commit();
s.close();
+ assertUpdateCount( 0 );
+ assertDeleteCount( 1 );
+
s = openSession();
t = s.beginTransaction();
List list = s.createQuery("from DataPoint where description='done!'").list();
@@ -276,9 +373,9 @@
}
public void testReadOnlyGetModifyAndDelete() {
+ clearCounts();
Session s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
DataPoint dp = new DataPoint();
dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
@@ -287,8 +384,11 @@
t.commit();
s.close();
+ assertInsertCount( 1 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
t = s.beginTransaction();
dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
s.setReadOnly( dp, true );
@@ -297,6 +397,10 @@
t.commit();
s.close();
+ assertUpdateCount( 0 );
+ assertDeleteCount( 1 );
+ clearCounts();
+
s = openSession();
t = s.beginTransaction();
List list = s.createQuery("from DataPoint where description='done!'").list();
@@ -307,9 +411,9 @@
}
public void testReadOnlyModeWithExistingModifiableEntity() {
+ clearCounts();
Session s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
DataPoint dp = null;
for ( int i=0; i<100; i++ ) {
@@ -321,8 +425,11 @@
t.commit();
s.close();
+ assertInsertCount( 100 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
t = s.beginTransaction();
DataPoint dpLast = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
assertFalse( s.isReadOnly( dpLast ) );
@@ -348,18 +455,25 @@
}
t.commit();
s.clear();
+
+ assertInsertCount( 0 );
+ assertUpdateCount( nExpectedChanges );
+ clearCounts();
+
t = s.beginTransaction();
List list = s.createQuery("from DataPoint where description='done!'").list();
assertEquals( list.size(), nExpectedChanges );
- s.createQuery("delete from DataPoint").executeUpdate();
+ assertEquals( 100, s.createQuery("delete from DataPoint").executeUpdate() );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
}
public void testModifiableModeWithExistingReadOnlyEntity() {
+ clearCounts();
Session s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
DataPoint dp = null;
for ( int i=0; i<100; i++ ) {
@@ -371,14 +485,21 @@
t.commit();
s.close();
+ assertInsertCount( 100 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
t = s.beginTransaction();
DataPoint dpLast = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
assertFalse( s.isReadOnly( dpLast ) );
s.setReadOnly( dpLast, true );
assertTrue( s.isReadOnly( dpLast ) );
+ dpLast.setDescription( "oy" );
int i = 0;
+
+ assertUpdateCount( 0 );
+
ScrollableResults sr = s.createQuery("from DataPoint dp order by dp.x asc")
.setReadOnly(false)
.scroll(ScrollMode.FORWARD_ONLY);
@@ -400,30 +521,40 @@
}
t.commit();
s.clear();
+
+ assertUpdateCount( nExpectedChanges );
+ clearCounts();
+
t = s.beginTransaction();
List list = s.createQuery("from DataPoint where description='done!'").list();
assertEquals( list.size(), nExpectedChanges );
- s.createQuery("delete from DataPoint").executeUpdate();
+ assertEquals( 100, s.createQuery("delete from DataPoint").executeUpdate() );
t.commit();
s.close();
+
+ assertUpdateCount( 0 );
}
public void testReadOnlyOnTextType() {
final String origText = "some huge text string";
final String newText = "some even bigger text string";
+ clearCounts();
+
Session s = openSession();
s.beginTransaction();
- s.setCacheMode( CacheMode.IGNORE );
TextHolder holder = new TextHolder( origText );
s.save( holder );
Long id = holder.getId();
s.getTransaction().commit();
s.close();
+ assertInsertCount( 1 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
s = openSession();
s.beginTransaction();
- s.setCacheMode( CacheMode.IGNORE );
holder = ( TextHolder ) s.get( TextHolder.class, id );
s.setReadOnly( holder, true );
holder.setTheText( newText );
@@ -431,6 +562,8 @@
s.getTransaction().commit();
s.close();
+ assertUpdateCount( 0 );
+
s = openSession();
s.beginTransaction();
holder = ( TextHolder ) s.get( TextHolder.class, id );
@@ -438,12 +571,15 @@
s.delete( holder );
s.getTransaction().commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 1 );
}
public void testMergeWithReadOnlyEntity() {
+ clearCounts();
Session s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
Transaction t = s.beginTransaction();
DataPoint dp = new DataPoint();
dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
@@ -452,10 +588,13 @@
t.commit();
s.close();
+ assertInsertCount( 1 );
+ assertUpdateCount( 0 );
+ clearCounts();
+
dp.setDescription( "description" );
s = openSession();
- s.setCacheMode(CacheMode.IGNORE);
t = s.beginTransaction();
DataPoint dpManaged = ( DataPoint ) s.get( DataPoint.class, new Long( dp.getId() ) );
s.setReadOnly( dpManaged, true );
@@ -464,6 +603,8 @@
t.commit();
s.close();
+ assertUpdateCount( 0 );
+
s = openSession();
t = s.beginTransaction();
dpManaged = ( DataPoint ) s.get( DataPoint.class, new Long( dp.getId() ) );
@@ -472,6 +613,9 @@
t.commit();
s.close();
+ assertUpdateCount( 0 );
+ assertDeleteCount( 1 );
+
}
}
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyVersionedNodesTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyVersionedNodesTest.java 2010-02-23 21:52:59 UTC (rev 18863)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyVersionedNodesTest.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -36,7 +36,7 @@
/**
* @author Gail Badner
*/
-public class ReadOnlyVersionedNodesTest extends FunctionalTestCase {
+public class ReadOnlyVersionedNodesTest extends AbstractReadOnlyTest {
public ReadOnlyVersionedNodesTest(String str) {
super( str );
@@ -46,15 +46,6 @@
return new String[] { "readonly/VersionedNode.hbm.xml" };
}
- public String getCacheConcurrencyStrategy() {
- return null;
- }
-
- public void configure(Configuration cfg) {
- cfg.setProperty( Environment.GENERATE_STATISTICS, "true");
- cfg.setProperty( Environment.STATEMENT_BATCH_SIZE, "0" );
- }
-
public static Test suite() {
return new FunctionalTestClassTestSuite( ReadOnlyVersionedNodesTest.class );
}
@@ -116,15 +107,20 @@
assertUpdateCount( 1 );
assertInsertCount( 0 );
+ clearCounts();
s = openSession();
s.beginTransaction();
node = ( VersionedNode ) s.get( VersionedNode.class, node.getId() );
assertEquals( "diff-node-name", node.getName() );
assertEquals( 1, node.getVersion() );
+ s.setReadOnly( node, true );
s.delete( node );
s.getTransaction().commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 1 );
}
public void testUpdateSetReadOnlyTwice() throws Exception {
@@ -155,9 +151,13 @@
node = ( VersionedNode ) s.get( VersionedNode.class, node.getId() );
assertEquals( "node", node.getName() );
assertEquals( 0, node.getVersion() );
+ s.setReadOnly( node, true );
s.delete( node );
s.getTransaction().commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 1 );
}
public void testUpdateSetModifiable() throws Exception {
@@ -181,15 +181,20 @@
assertUpdateCount( 1 );
assertInsertCount( 0 );
+ clearCounts();
s = openSession();
s.beginTransaction();
node = ( VersionedNode ) s.get( VersionedNode.class, node.getId() );
assertEquals( "node-name", node.getName() );
assertEquals( 1, node.getVersion() );
+ s.setReadOnly( node, true );
s.delete( node );
s.getTransaction().commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 1 );
}
public void testUpdateSetReadOnlySetModifiableFailureExpected() throws Exception {
@@ -317,6 +322,7 @@
assertUpdateCount( 0 );
assertInsertCount( 1 );
+ clearCounts();
s = openSession();
s.beginTransaction();
@@ -328,10 +334,15 @@
assertSame( parent, child.getParent() );
assertSame( child, parent.getChildren().iterator().next() );
assertEquals( 0, child.getVersion() );
+ s.setReadOnly( parent, true );
+ s.setReadOnly( child, true );
s.delete( parent );
s.delete( child );
s.getTransaction().commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 2 );
}
public void testMergeDetachedParentWithNewChildCommitWithReadOnlyParent() throws Exception {
@@ -357,6 +368,7 @@
assertUpdateCount( 0 );
assertInsertCount( 1 );
+ clearCounts();
s = openSession();
s.beginTransaction();
@@ -368,10 +380,15 @@
assertSame( parent, child.getParent() );
assertSame( child, parent.getChildren().iterator().next() );
assertEquals( 0, child.getVersion() );
+ s.setReadOnly( parent, true );
+ s.setReadOnly( child, true );
s.delete( parent );
s.delete( child );
s.getTransaction().commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 2 );
}
public void testGetParentMakeReadOnlyThenMergeDetachedParentWithNewChildC() throws Exception {
@@ -399,6 +416,7 @@
assertUpdateCount( 0 );
assertInsertCount( 1 );
+ clearCounts();
s = openSession();
s.beginTransaction();
@@ -414,9 +432,74 @@
s.delete( child );
s.getTransaction().commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 2 );
}
+ public void testMergeUnchangedDetachedParentChildren() throws Exception {
+ Session s = openSession();
+ s.beginTransaction();
+ VersionedNode parent = new VersionedNode( "parent", "parent" );
+ VersionedNode child = new VersionedNode( "child", "child");
+ parent.addChild( child );
+ s.persist( parent );
+ s.getTransaction().commit();
+ s.close();
+ clearCounts();
+
+ s = openSession();
+ s.beginTransaction();
+ parent = ( VersionedNode ) s.merge( parent );
+ s.getTransaction().commit();
+ s.close();
+
+ assertUpdateCount( 0 );
+ assertInsertCount( 0 );
+ clearCounts();
+
+ s = openSession();
+ s.beginTransaction();
+ VersionedNode parentGet = ( VersionedNode ) s.get( parent.getClass(), parent.getId() );
+ s.merge( parent );
+ s.getTransaction().commit();
+ s.close();
+
+ assertUpdateCount( 0 );
+ assertInsertCount( 0 );
+ clearCounts();
+
+ s = openSession();
+ s.beginTransaction();
+ VersionedNode parentLoad = ( VersionedNode ) s.load( parent.getClass(), parent.getId() );
+ s.merge( parent );
+ s.getTransaction().commit();
+ s.close();
+
+ assertUpdateCount( 0 );
+ assertInsertCount( 0 );
+ clearCounts();
+
+ s = openSession();
+ s.beginTransaction();
+ parent = ( VersionedNode ) s.get( VersionedNode.class, parent.getId() );
+ child = ( VersionedNode ) s.get( VersionedNode.class, child.getId() );
+ assertEquals( parent.getName(), "parent" );
+ assertEquals( 1, parent.getChildren().size() );
+ assertEquals( 0, parent.getVersion() );
+ assertSame( parent, child.getParent() );
+ assertSame( child, parent.getChildren().iterator().next() );
+ assertEquals( 0, child.getVersion() );
+ s.delete( parent );
+ s.delete( child );
+ s.getTransaction().commit();
+ s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 2 );
+ }
+
public void testAddNewParentToReadOnlyChild() throws Exception {
Session s = openSession();
s.beginTransaction();
@@ -448,9 +531,13 @@
assertEquals( 0, child.getVersion() );
parent = ( VersionedNode ) s.get( VersionedNode.class, parent.getId() );
assertNull( parent );
+ s.setReadOnly( child, true );
s.delete( child );
s.getTransaction().commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 1 );
}
public void testUpdateChildWithNewParentCommitWithReadOnlyChild() throws Exception {
@@ -476,6 +563,7 @@
assertUpdateCount( 0 );
assertInsertCount( 1 );
+ clearCounts();
s = openSession();
s.beginTransaction();
@@ -487,10 +575,15 @@
assertNotNull( parent );
assertEquals( 0, parent.getChildren().size() );
assertEquals( 0, parent.getVersion() );
+ s.setReadOnly( parent, true );
+ s.setReadOnly( child, true );
s.delete( parent );
s.delete( child );
s.getTransaction().commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 2 );
}
public void testMergeDetachedChildWithNewParentCommitWithReadOnlyChild() throws Exception {
@@ -516,6 +609,7 @@
assertUpdateCount( 1 );
assertInsertCount( 1 );
+ clearCounts();
s = openSession();
s.beginTransaction();
@@ -527,10 +621,15 @@
assertNotNull( parent );
assertEquals( 0, parent.getChildren().size() );
assertEquals( 1, parent.getVersion() ); // hmmm, why is was version updated?
+ s.setReadOnly( parent, true );
+ s.setReadOnly( child, true );
s.delete( parent );
s.delete( child );
s.getTransaction().commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 2 );
}
public void testGetChildMakeReadOnlyThenMergeDetachedChildWithNewParent() throws Exception {
@@ -558,6 +657,7 @@
assertUpdateCount( 1 );
assertInsertCount( 1 );
+ clearCounts();
s = openSession();
s.beginTransaction();
@@ -569,10 +669,15 @@
assertNotNull( parent );
assertEquals( 0, parent.getChildren().size() );
assertEquals( 1, parent.getVersion() ); // / hmmm, why is was version updated?
+ s.setReadOnly( parent, true );
+ s.setReadOnly( child, true );
s.delete( parent );
s.delete( child );
s.getTransaction().commit();
s.close();
+
+ assertUpdateCount( 0 );
+ assertDeleteCount( 2 );
}
protected void cleanupTest() throws Exception {
@@ -590,23 +695,4 @@
s.getTransaction().commit();
s.close();
}
-
- protected void clearCounts() {
- getSessions().getStatistics().clear();
- }
-
- protected void assertInsertCount(int expected) {
- int inserts = ( int ) getSessions().getStatistics().getEntityInsertCount();
- assertEquals( "unexpected insert count", expected, inserts );
- }
-
- protected void assertUpdateCount(int expected) {
- int updates = ( int ) getSessions().getStatistics().getEntityUpdateCount();
- assertEquals( "unexpected update counts", expected, updates );
- }
-
- protected void assertDeleteCount(int expected) {
- int deletes = ( int ) getSessions().getStatistics().getEntityDeleteCount();
- assertEquals( "unexpected delete counts", expected, deletes );
- }
}
Copied: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Student.java (from rev 18852, core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/criteria/Student.java)
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Student.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Student.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -0,0 +1,47 @@
+//$Id: Student.java 9116 2006-01-23 21:21:01Z steveebersole $
+package org.hibernate.test.readonly;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * @author Gavin King
+ */
+public class Student {
+ private long studentNumber;
+ private String name;
+ private Course preferredCourse;
+ private Set enrolments = new HashSet();
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public long getStudentNumber() {
+ return studentNumber;
+ }
+
+ public void setStudentNumber(long studentNumber) {
+ this.studentNumber = studentNumber;
+ }
+
+ public Course getPreferredCourse() {
+ return preferredCourse;
+ }
+
+ public void setPreferredCourse(Course preferredCourse) {
+ this.preferredCourse = preferredCourse;
+ }
+
+ public Set getEnrolments() {
+ return enrolments;
+ }
+
+ public void setEnrolments(Set employments) {
+ this.enrolments = employments;
+ }
+}
Copied: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/StudentDTO.java (from rev 18852, core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/criteria/StudentDTO.java)
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/StudentDTO.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/StudentDTO.java 2010-02-23 22:18:43 UTC (rev 18864)
@@ -0,0 +1,26 @@
+/*
+ * Created on 28-Jan-2005
+ *
+ */
+package org.hibernate.test.readonly;
+
+/**
+ * @author max
+ *
+ */
+public class StudentDTO {
+
+ private String studentName;
+ private String courseDescription;
+
+ public StudentDTO() { }
+
+ public String getName() {
+ return studentName;
+ }
+
+ public String getDescription() {
+ return courseDescription;
+ }
+
+}
14 years, 12 months
Hibernate SVN: r18863 - core/branches/Branch_3_3/core/src/main/java/org/hibernate/persister/collection.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2010-02-23 16:52:59 -0500 (Tue, 23 Feb 2010)
New Revision: 18863
Modified:
core/branches/Branch_3_3/core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java
Log:
mapping order impacting behavior leading to bug
Modified: core/branches/Branch_3_3/core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java
===================================================================
--- core/branches/Branch_3_3/core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java 2010-02-23 21:52:32 UTC (rev 18862)
+++ core/branches/Branch_3_3/core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java 2010-02-23 21:52:59 UTC (rev 18863)
@@ -299,7 +299,7 @@
// NativeSQL: collect key column and auto-aliases
Column col = ( (Column) iter.next() );
keyColumnNames[k] = col.getQuotedName(dialect);
- keyColumnAliases[k] = col.getAlias(dialect);
+ keyColumnAliases[k] = col.getAlias(dialect,collection.getOwner().getRootTable());
k++;
}
14 years, 12 months
Hibernate SVN: r18862 - in core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass: alias and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2010-02-23 16:52:32 -0500 (Tue, 23 Feb 2010)
New Revision: 18862
Added:
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/CarBuyer.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Customer.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/PersonID.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/SellCarTest.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Seller.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/mapping.hbm.xml
Log:
mapping order impacting behavior leading to bug
Added: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/CarBuyer.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/CarBuyer.java (rev 0)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/CarBuyer.java 2010-02-23 21:52:32 UTC (rev 18862)
@@ -0,0 +1,59 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.unionsubclass.alias;
+
+/**
+ *
+ * @author Strong Liu <stliu(a)redhat.com>
+ */
+public class CarBuyer extends Customer {
+ private String sellerName;
+ private String pid;
+ private Seller seller;
+
+ public String getSellerName() {
+ return sellerName;
+ }
+
+ public void setSellerName( String sellerName ) {
+ this.sellerName = sellerName;
+ }
+
+ public String getPid() {
+ return pid;
+ }
+
+ public void setPid( String pid ) {
+ this.pid = pid;
+ }
+
+ public Seller getSeller() {
+ return seller;
+ }
+
+ public void setSeller( Seller seller ) {
+ this.seller = seller;
+ }
+
+}
Added: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Customer.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Customer.java (rev 0)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Customer.java 2010-02-23 21:52:32 UTC (rev 18862)
@@ -0,0 +1,57 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.unionsubclass.alias;
+
+import java.io.Serializable;
+
+/**
+ *
+ * @author Strong Liu <stliu(a)redhat.com>
+ */
+public abstract class Customer implements Serializable {
+ private PersonID id;
+
+ public PersonID getId() {
+ return id;
+ }
+
+ public void setId( PersonID id ) {
+ this.id = id;
+ }
+
+ public boolean equals( Object obj ) {
+ if ( obj == null )
+ return false;
+ if ( obj == this )
+ return true;
+ if ( !( obj instanceof Customer ) )
+ return false;
+ return ( (Customer) obj ).getId().equals( getId() );
+ }
+
+ public int hashCode() {
+ return id.hashCode();
+ }
+
+}
Added: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/PersonID.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/PersonID.java (rev 0)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/PersonID.java 2010-02-23 21:52:32 UTC (rev 18862)
@@ -0,0 +1,94 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.unionsubclass.alias;
+
+import java.io.Serializable;
+
+/**
+ *
+ * @author Strong Liu <stliu(a)redhat.com>
+ */
+public class PersonID implements Serializable {
+ private Long num;
+ private String name;
+
+ public Long getNum() {
+ return num;
+ }
+
+ public void setNum( Long num ) {
+ this.num = num;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName( String name ) {
+ this.name = name;
+ }
+
+ public boolean equals( Object obj ) {
+ if ( this == obj )
+ return true;
+ if ( obj == null )
+ return false;
+ if ( getClass() != obj.getClass() )
+ return false;
+ final PersonID other = (PersonID) obj;
+ if ( name == null ) {
+ if ( other.name != null )
+ return false;
+
+ } else if ( !name.equals( other.name ) ) {
+ return false;
+ }
+ if ( num == null ) {
+ if ( other.num != null )
+ return false;
+
+ } else if ( !num.equals( other.num ) ) {
+ return false;
+ }
+ return true;
+ }
+
+ public int hashCode() {
+ final int PRIME = 31;
+ int result = 1;
+ if ( name != null ) {
+ result += name.hashCode();
+ }
+ result *= PRIME;
+ if ( num != null ) {
+ result += num.hashCode();
+ }
+ return result;
+ }
+
+ public String toString() {
+ return name + " | " + num;
+ }
+
+}
Added: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/SellCarTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/SellCarTest.java (rev 0)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/SellCarTest.java 2010-02-23 21:52:32 UTC (rev 18862)
@@ -0,0 +1,82 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.unionsubclass.alias;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.junit.functional.FunctionalTestCase;
+
+/**
+ * http://opensource.atlassian.com/projects/hibernate/browse/HHH-4825
+ * @author Strong Liu <stliu(a)redhat.com>
+ */
+public class SellCarTest extends FunctionalTestCase {
+
+ public SellCarTest( String string ) {
+ super( string );
+ }
+
+ public String[] getMappings() {
+ return new String[] { "unionsubclass/alias/mapping.hbm.xml" };
+ }
+
+ public void testSellCar() throws Exception {
+ prepareData();
+ Session session = openSession();
+ Transaction tx = session.beginTransaction();
+ Query query = session.createQuery( "from Seller" );
+ Seller seller = (Seller) query.uniqueResult();
+ assertNotNull( seller );
+ assertEquals( 1, seller.getBuyers().size() );
+ tx.commit();
+ session.close();
+ }
+
+ private void prepareData() {
+ Session session = openSession();
+ Transaction tx = session.beginTransaction();
+ session.save( createData() );
+ tx.commit();
+ session.close();
+ }
+
+ private Object createData() {
+ Seller stliu = new Seller();
+ stliu.setId( createID( "stliu" ) );
+ CarBuyer zd = new CarBuyer();
+ zd.setId( createID( "zd" ) );
+ zd.setSeller( stliu );
+ zd.setSellerName( stliu.getId().getName() );
+ stliu.getBuyers().add( zd );
+ return stliu;
+ }
+
+ private PersonID createID( String name ) {
+ PersonID id = new PersonID();
+ id.setName( name );
+ id.setNum( new Long( 100 ) );
+ return id;
+ }
+}
Added: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Seller.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Seller.java (rev 0)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Seller.java 2010-02-23 21:52:32 UTC (rev 18862)
@@ -0,0 +1,69 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.unionsubclass.alias;
+
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ *
+ * @author Strong Liu <stliu(a)redhat.com>
+ */
+public class Seller implements Serializable {
+ private PersonID id;
+ private Set buyers = new HashSet();
+
+ public PersonID getId() {
+ return id;
+ }
+
+ public void setId( PersonID id ) {
+ this.id = id;
+ }
+
+ public Set getBuyers() {
+ return buyers;
+ }
+
+ public void setBuyers( Set buyers ) {
+ this.buyers = buyers;
+ }
+
+ public boolean equals( Object obj ) {
+ if ( obj == null )
+ return false;
+ if ( obj == this )
+ return true;
+ if ( !( obj instanceof Seller ) )
+ return false;
+
+ return ( (Seller) obj ).getId().equals( getId() );
+ }
+
+ public int hashCode() {
+ return id.hashCode();
+ }
+
+}
Added: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/mapping.hbm.xml
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/mapping.hbm.xml (rev 0)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/mapping.hbm.xml 2010-02-23 21:52:32 UTC (rev 18862)
@@ -0,0 +1,36 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping SYSTEM
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+<hibernate-mapping package="org.hibernate.test.unionsubclass.alias">
+
+ <class name="Seller">
+ <composite-id class="PersonID" name="id">
+ <key-property column="NR_RZBK" name="num" />
+ <key-property column="TXT_OID" name="name" />
+ </composite-id>
+ <set cascade="persist, merge, save-update" inverse="true" lazy="false"
+ name="buyers">
+ <key>
+ <column name="NR_RZBK" />
+ <column name="TXT_OID_TESTB" />
+ </key>
+ <one-to-many class="CarBuyer" />
+ </set>
+ </class>
+
+ <class abstract="true" name="Customer">
+ <composite-id class="PersonID" name="id">
+ <key-property column="NR_RZBK" name="num" />
+ <key-property column="TXT_OID" name="name" />
+ </composite-id>
+ <union-subclass name="CarBuyer">
+ <property column="PID" name="pid" update="false" />
+ <property column="TXT_OID_TESTB" name="sellerName" />
+ <many-to-one cascade="persist, merge, save-update" class="Seller"
+ insert="false" name="seller" update="false">
+ <column name="NR_RZBK" />
+ <column name="TXT_OID_TESTB" />
+ </many-to-one>
+ </union-subclass>
+ </class>
+</hibernate-mapping>
\ No newline at end of file
14 years, 12 months
Hibernate SVN: r18861 - in core/trunk: testsuite/src/test/java/org/hibernate/test/unionsubclass and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2010-02-23 16:45:34 -0500 (Tue, 23 Feb 2010)
New Revision: 18861
Added:
core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/
core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/CarBuyer.java
core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Customer.java
core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/PersonID.java
core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/SellCarTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Seller.java
core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/mapping.hbm.xml
Modified:
core/trunk/core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java
Log:
HHH-4825 mapping order impacting behavior leading to bug
Modified: core/trunk/core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java 2010-02-23 19:12:49 UTC (rev 18860)
+++ core/trunk/core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java 2010-02-23 21:45:34 UTC (rev 18861)
@@ -297,7 +297,7 @@
// NativeSQL: collect key column and auto-aliases
Column col = ( (Column) iter.next() );
keyColumnNames[k] = col.getQuotedName(dialect);
- keyColumnAliases[k] = col.getAlias(dialect);
+ keyColumnAliases[k] = col.getAlias(dialect,collection.getOwner().getRootTable());
k++;
}
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/CarBuyer.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/CarBuyer.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/CarBuyer.java 2010-02-23 21:45:34 UTC (rev 18861)
@@ -0,0 +1,59 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.unionsubclass.alias;
+
+/**
+ *
+ * @author Strong Liu <stliu(a)redhat.com>
+ */
+public class CarBuyer extends Customer {
+ private String sellerName;
+ private String pid;
+ private Seller seller;
+
+ public String getSellerName() {
+ return sellerName;
+ }
+
+ public void setSellerName( String sellerName ) {
+ this.sellerName = sellerName;
+ }
+
+ public String getPid() {
+ return pid;
+ }
+
+ public void setPid( String pid ) {
+ this.pid = pid;
+ }
+
+ public Seller getSeller() {
+ return seller;
+ }
+
+ public void setSeller( Seller seller ) {
+ this.seller = seller;
+ }
+
+}
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Customer.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Customer.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Customer.java 2010-02-23 21:45:34 UTC (rev 18861)
@@ -0,0 +1,57 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.unionsubclass.alias;
+
+import java.io.Serializable;
+
+/**
+ *
+ * @author Strong Liu <stliu(a)redhat.com>
+ */
+public abstract class Customer implements Serializable {
+ private PersonID id;
+
+ public PersonID getId() {
+ return id;
+ }
+
+ public void setId( PersonID id ) {
+ this.id = id;
+ }
+
+ public boolean equals( Object obj ) {
+ if ( obj == null )
+ return false;
+ if ( obj == this )
+ return true;
+ if ( !( obj instanceof Customer ) )
+ return false;
+ return ( (Customer) obj ).getId().equals( getId() );
+ }
+
+ public int hashCode() {
+ return id.hashCode();
+ }
+
+}
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/PersonID.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/PersonID.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/PersonID.java 2010-02-23 21:45:34 UTC (rev 18861)
@@ -0,0 +1,94 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.unionsubclass.alias;
+
+import java.io.Serializable;
+
+/**
+ *
+ * @author Strong Liu <stliu(a)redhat.com>
+ */
+public class PersonID implements Serializable {
+ private Long num;
+ private String name;
+
+ public Long getNum() {
+ return num;
+ }
+
+ public void setNum( Long num ) {
+ this.num = num;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName( String name ) {
+ this.name = name;
+ }
+
+ public boolean equals( Object obj ) {
+ if ( this == obj )
+ return true;
+ if ( obj == null )
+ return false;
+ if ( getClass() != obj.getClass() )
+ return false;
+ final PersonID other = (PersonID) obj;
+ if ( name == null ) {
+ if ( other.name != null )
+ return false;
+
+ } else if ( !name.equals( other.name ) ) {
+ return false;
+ }
+ if ( num == null ) {
+ if ( other.num != null )
+ return false;
+
+ } else if ( !num.equals( other.num ) ) {
+ return false;
+ }
+ return true;
+ }
+
+ public int hashCode() {
+ final int PRIME = 31;
+ int result = 1;
+ if ( name != null ) {
+ result += name.hashCode();
+ }
+ result *= PRIME;
+ if ( num != null ) {
+ result += num.hashCode();
+ }
+ return result;
+ }
+
+ public String toString() {
+ return name + " | " + num;
+ }
+
+}
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/SellCarTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/SellCarTest.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/SellCarTest.java 2010-02-23 21:45:34 UTC (rev 18861)
@@ -0,0 +1,82 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.unionsubclass.alias;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.junit.functional.FunctionalTestCase;
+
+/**
+ * http://opensource.atlassian.com/projects/hibernate/browse/HHH-4825
+ * @author Strong Liu <stliu(a)redhat.com>
+ */
+public class SellCarTest extends FunctionalTestCase {
+
+ public SellCarTest( String string ) {
+ super( string );
+ }
+
+ public String[] getMappings() {
+ return new String[] { "unionsubclass/alias/mapping.hbm.xml" };
+ }
+
+ public void testSellCar() throws Exception {
+ prepareData();
+ Session session = openSession();
+ Transaction tx = session.beginTransaction();
+ Query query = session.createQuery( "from Seller" );
+ Seller seller = (Seller) query.uniqueResult();
+ assertNotNull( seller );
+ assertEquals( 1, seller.getBuyers().size() );
+ tx.commit();
+ session.close();
+ }
+
+ private void prepareData() {
+ Session session = openSession();
+ Transaction tx = session.beginTransaction();
+ session.save( createData() );
+ tx.commit();
+ session.close();
+ }
+
+ private Object createData() {
+ Seller stliu = new Seller();
+ stliu.setId( createID( "stliu" ) );
+ CarBuyer zd = new CarBuyer();
+ zd.setId( createID( "zd" ) );
+ zd.setSeller( stliu );
+ zd.setSellerName( stliu.getId().getName() );
+ stliu.getBuyers().add( zd );
+ return stliu;
+ }
+
+ private PersonID createID( String name ) {
+ PersonID id = new PersonID();
+ id.setName( name );
+ id.setNum( new Long( 100 ) );
+ return id;
+ }
+}
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Seller.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Seller.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/Seller.java 2010-02-23 21:45:34 UTC (rev 18861)
@@ -0,0 +1,69 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.unionsubclass.alias;
+
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ *
+ * @author Strong Liu <stliu(a)redhat.com>
+ */
+public class Seller implements Serializable {
+ private PersonID id;
+ private Set buyers = new HashSet();
+
+ public PersonID getId() {
+ return id;
+ }
+
+ public void setId( PersonID id ) {
+ this.id = id;
+ }
+
+ public Set getBuyers() {
+ return buyers;
+ }
+
+ public void setBuyers( Set buyers ) {
+ this.buyers = buyers;
+ }
+
+ public boolean equals( Object obj ) {
+ if ( obj == null )
+ return false;
+ if ( obj == this )
+ return true;
+ if ( !( obj instanceof Seller ) )
+ return false;
+
+ return ( (Seller) obj ).getId().equals( getId() );
+ }
+
+ public int hashCode() {
+ return id.hashCode();
+ }
+
+}
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/mapping.hbm.xml
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/mapping.hbm.xml (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/unionsubclass/alias/mapping.hbm.xml 2010-02-23 21:45:34 UTC (rev 18861)
@@ -0,0 +1,36 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping SYSTEM
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+<hibernate-mapping package="org.hibernate.test.unionsubclass.alias">
+
+ <class name="Seller">
+ <composite-id class="PersonID" name="id">
+ <key-property column="NR_RZBK" name="num" />
+ <key-property column="TXT_OID" name="name" />
+ </composite-id>
+ <set cascade="persist, merge, save-update" inverse="true" lazy="false"
+ name="buyers">
+ <key>
+ <column name="NR_RZBK" />
+ <column name="TXT_OID_TESTB" />
+ </key>
+ <one-to-many class="CarBuyer" />
+ </set>
+ </class>
+
+ <class abstract="true" name="Customer">
+ <composite-id class="PersonID" name="id">
+ <key-property column="NR_RZBK" name="num" />
+ <key-property column="TXT_OID" name="name" />
+ </composite-id>
+ <union-subclass name="CarBuyer">
+ <property column="PID" name="pid" update="false" />
+ <property column="TXT_OID_TESTB" name="sellerName" />
+ <many-to-one cascade="persist, merge, save-update" class="Seller"
+ insert="false" name="seller" update="false">
+ <column name="NR_RZBK" />
+ <column name="TXT_OID_TESTB" />
+ </many-to-one>
+ </union-subclass>
+ </class>
+</hibernate-mapping>
\ No newline at end of file
14 years, 12 months
Hibernate SVN: r18860 - in core/trunk/annotations/src: test/java/org/hibernate/test/annotations/derivedidentities/e5 and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2010-02-23 14:12:49 -0500 (Tue, 23 Feb 2010)
New Revision: 18860
Added:
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/c/
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/c/ForeignGeneratorViaMapsIdTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/c/MedicalHistory.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/c/Person.java
Modified:
core/trunk/annotations/src/main/docbook/en/modules/entity.xml
core/trunk/annotations/src/main/docbook/en/modules/setup.xml
Log:
HHH-4933 Write documentation on composite identity, partial generated value and derived identity
Modified: core/trunk/annotations/src/main/docbook/en/modules/entity.xml
===================================================================
--- core/trunk/annotations/src/main/docbook/en/modules/entity.xml 2010-02-23 14:55:16 UTC (rev 18859)
+++ core/trunk/annotations/src/main/docbook/en/modules/entity.xml 2010-02-23 19:12:49 UTC (rev 18860)
@@ -273,9 +273,109 @@
</section>
<section>
- <title></title>
+ <title>Access type</title>
- <para></para>
+ <para>By default the access type of a class hierarchy is defined by
+ the position of the <classname>@Id</classname> or
+ <classname>@EmbeddedId</classname> annotations. If these annotations
+ are on a field, then only fields are considered for persistence and
+ the state is accessed via the field. If there annotations are on a
+ getter, then only the getters are considered for persistence and the
+ state is accessed via the getter/setter. That works well in practice
+ and is the recommended approach.<note>
+ <para>The placement of annotations within a class hierarchy has to
+ be consistent (either field or on property) to be able to
+ determine the default access type. It is recommended to stick to
+ one single annotation placement strategy throughout your whole
+ application.</para>
+ </note></para>
+
+ <para>However in some situations, you need to:</para>
+
+ <itemizedlist>
+ <listitem>
+ <para>force the access type of the entity hierarchy</para>
+ </listitem>
+
+ <listitem>
+ <para>override the access type of a specific entity in the class
+ hierarchy</para>
+ </listitem>
+
+ <listitem>
+ <para>override the access type of an embeddable type</para>
+ </listitem>
+ </itemizedlist>
+
+ <para>The best use case is an embeddable class used by several
+ entities that might not use the same access type. In this case it is
+ better to force the access type at the embeddable class level.</para>
+
+ <para>To force the access type on a given class, use the
+ <classname>@Access</classname> annotation as showed below:</para>
+
+ <programlisting>@Entity
+public class Order {
+ @Id private Long id;
+ public Long getId() { return id; }
+ public void setId(Long id) { this.id = id; }
+
+ @Embedded private Address address;
+ public Address getAddress() { return address; }
+ public void setAddress() { this.address = address; }
+}
+
+@Entity
+public class User {
+ private Long id;
+ @Id public Long getId() { return id; }
+ public void setId(Long id) { this.id = id; }
+
+ private Address address;
+ @Embedded public Address getAddress() { return address; }
+ public void setAddress() { this.address = address; }
+}
+
+@Embeddable
+(a)Access(AcessType.PROPERTY)
+public class Address {
+ private String street1;
+ public String getStreet1() { return street1; }
+ public void setStreet1() { this.street1 = street1; }
+
+ private hashCode; //not persistent
+}</programlisting>
+
+ <para>You can also override the access type of a single property while
+ keeping the other properties standard.</para>
+
+ <programlisting>@Entity
+public class Order {
+ @Id private Long id;
+ public Long getId() { return id; }
+ public void setId(Long id) { this.id = id; }
+ @Transient private String userId;
+ @Transient private String orderId;
+
+ @Access(AccessType.PROPERTY)
+ public String getOrderNumber() { return userId + ":" + orderId; }
+ public void setOrderNumber() { this.userId = ...; this.orderId = ...; }
+}</programlisting>
+
+ <para>In this example, the default access type is
+ <classname>FIELD</classname> except for the
+ <literal>orderNumber</literal> property. Note that the corresponding
+ field, if any must be marked as <classname>@Transient</classname> or
+ <code>transient</code>.</para>
+
+ <note>
+ <title>@org.hibernate.annotations.AccessType</title>
+
+ <para>The annotation
+ <classname>@org.hibernate.annotations.AccessType</classname> should
+ be considered deprecated for FIELD and PROPERTY access. It is still
+ useful however if you need to use a custom access type.</para>
+ </note>
</section>
<section id="entity-mapping-property-column" revision="1">
@@ -307,12 +407,6 @@
<listitem>
<para>annotated with <literal>@Temporal</literal></para>
</listitem>
-
- <listitem>
- <para>annotated with
- <literal>@org.hibernate.annotations.CollectionOfElements</literal>
- (for Hibernate only)</para>
- </listitem>
</itemizedlist>
<programlisting>
@@ -435,8 +529,7 @@
<literal>@Embedded</literal> and <literal>@AttributeOverride</literal>
annotation in the associated property:</para>
- <programlisting>
-@Entity
+ <programlisting>@Entity
public class Person implements Serializable {
// Persistent component using defaults
@@ -449,19 +542,15 @@
} )
Country bornIn;
...
-}
- </programlisting>
+} </programlisting>
- <programlisting>
-@Embeddable
+ <programlisting>@Embeddable
public class Address implements Serializable {
String city;
Country nationality; //no overriding here
-}
- </programlisting>
+} </programlisting>
- <programlisting>
-@Embeddable
+ <programlisting>@Embeddable
public class Country implements Serializable {
private String iso2;
@Column(name="countryName") private String name;
@@ -473,13 +562,11 @@
public String getName() { return name; }
public void setName(String name) { this.name = name; }
...
-}
- </programlisting>
+} </programlisting>
<para>An embeddable object inherits the access type of its owning
- entity (note that you can override that using
- <literal>@Access</literal> or the Hibernate specific
- <literal>@AccessType</literal> annotation.</para>
+ entity (note that you can override that using the
+ <literal>@Access</literal> annotation).</para>
<para>The <literal>Person</literal> entity bean has two component
properties, <literal>homeAddress</literal> and
@@ -492,10 +579,9 @@
</literal>annotations for each mapped attribute of
<literal>Country</literal>. As you can see, <literal>Country
</literal>is also a nested component of <literal>Address</literal>,
- again using auto-detection by Hibernate and EJB3 defaults. Overriding
- columns of embedded objects of embedded objects is currently not
- supported in the EJB3 spec, however, Hibernate Annotations supports it
- through dotted expressions.</para>
+ again using auto-detection by Hibernate and JPA defaults. Overriding
+ columns of embedded objects of embedded objects is through dotted
+ expressions.</para>
<para><programlisting> @Embedded
@AttributeOverrides( {
@@ -504,27 +590,28 @@
@AttributeOverride(name="<emphasis role="bold">nationality.name</emphasis>", column = @Column(name="nat_CountryName") )
//nationality columns in homeAddress are overridden
} )
- Address homeAddress;</programlisting>Hibernate Annotations supports one
- more feature that is not explicitly supported by the EJB3
- specification. You can annotate a embedded object with the
+ Address homeAddress;</programlisting>Hibernate Annotations supports
+ something that is not explicitly supported by the JPA specification.
+ You can annotate a embedded object with the
<literal>@MappedSuperclass</literal> annotation to make the superclass
properties persistent (see <literal>@MappedSuperclass</literal> for
more informations).</para>
- <para>While not supported by the EJB3 specification, Hibernate
- Annotations allows you to use association annotations in an embeddable
- object (ie <literal>@*ToOne</literal> nor
- <literal>@*ToMany</literal>). To override the association columns you
- can use <literal>@AssociationOverride</literal>.</para>
+ <para>You can also use association annotations in an embeddable object
+ (ie <literal>@OneToOne</literal>, <classname>@ManyToOne</classname>,
+ <classname>@OneToMany</classname> or <literal>@ManyToMany</literal>).
+ To override the association columns you can use
+ <literal>@AssociationOverride</literal>.</para>
<para>If you want to have the same embeddable object type twice in the
- same entity, the column name defaulting will not work: at least one of
- the columns will have to be explicit. Hibernate goes beyond the EJB3
- spec and allows you to enhance the defaulting mechanism through the
- <classname>NamingStrategy</classname>.
- <classname>DefaultComponentSafeNamingStrategy</classname> is a small
- improvement over the default EJB3NamingStrategy that allows embedded
- objects to be defaulted even if used twice in the same entity.</para>
+ same entity, the column name defaulting will not work as several
+ embedded objects would share the same set of columns. In plain JPA,
+ you need to override at least one set of columns. Hibernate, however,
+ allows you to enhance the default naming mechanism through the
+ <classname>NamingStrategy</classname> interface. You can write a
+ strategy that prevent name clashing in such a situation.
+ <classname>DefaultComponentSafeNamingStrategy</classname> is an
+ example of this.</para>
</section>
<section>
@@ -545,15 +632,18 @@
</listitem>
<listitem>
- <para>Otherwise, if the type of the property is Serializable, it
- is mapped as @Basic in a column holding the object in its
- serialized version</para>
+ <para>Otherwise, if the type of the property is
+ <classname>Serializable</classname>, it is mapped as
+ <classname>@Basic</classname> in a column holding the object in
+ its serialized version</para>
</listitem>
<listitem>
- <para>Otherwise, if the type of the property is java.sql.Clob or
- java.sql.Blob, it is mapped as @Lob with the appropriate
- LobType</para>
+ <para>Otherwise, if the type of the property is
+ <classname>java.sql.Clob</classname> or
+ <classname>java.sql.Blob</classname>, it is mapped as
+ <classname>@Lob</classname> with the appropriate
+ <classname>LobType</classname></para>
</listitem>
</itemizedlist>
</section>
@@ -567,58 +657,65 @@
property is the identifier of your entity bean. This property can be set
by the application itself or be generated by Hibernate (preferred). You
can define the identifier generation strategy thanks to the
- <literal>@GeneratedValue</literal> annotation:</para>
+ <literal>@GeneratedValue</literal> annotation.</para>
- <itemizedlist>
- <listitem>
- <para>AUTO - either identity column, sequence or table depending on
- the underlying DB</para>
- </listitem>
+ <section>
+ <title>Generating the identifier property</title>
- <listitem>
- <para>TABLE - table holding the id</para>
- </listitem>
+ <para>JPA defines five types of identifier generation
+ strategies:</para>
- <listitem>
- <para>IDENTITY - identity column</para>
- </listitem>
+ <itemizedlist>
+ <listitem>
+ <para>AUTO - either identity column, sequence or table depending
+ on the underlying DB</para>
+ </listitem>
- <listitem>
- <para>SEQUENCE - sequence</para>
- </listitem>
- </itemizedlist>
+ <listitem>
+ <para>TABLE - table holding the id</para>
+ </listitem>
- <para>Hibernate provides more id generators than the basic EJB3 ones.
- Check <xref linkend="entity-hibspec" /> for more informations.</para>
+ <listitem>
+ <para>IDENTITY - identity column</para>
+ </listitem>
- <para>The following example shows a sequence generator using the
- SEQ_STORE configuration (see below)</para>
+ <listitem>
+ <para>SEQUENCE - sequence</para>
+ </listitem>
- <programlisting>
-@Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_STORE")
-public Integer getId() { ... }
- </programlisting>
+ <listitem>
+ <para>identity copy - the identity is copied from another
+ entity</para>
+ </listitem>
+ </itemizedlist>
- <para>The next example uses the identity generator:</para>
+ <para>Hibernate provides more id generators than the basic JPA ones.
+ Check <xref linkend="entity-hibspec" /> for more informations.</para>
- <programlisting>
-@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
-public Long getId() { ... }
- </programlisting>
+ <para>The following example shows a sequence generator using the
+ SEQ_STORE configuration (see below)</para>
- <para>The <literal>AUTO</literal> generator is the preferred type for
- portable applications (across several DB vendors). The identifier
- generation configuration can be shared for several
- <literal>@Id</literal> mappings with the generator attribute. There are
- several configurations available through
- <literal>@SequenceGenerator</literal> and
- <literal>@TableGenerator</literal>. The scope of a generator can be the
- application or the class. Class-defined generators are not visible
- outside the class and can override application level generators.
- Application level generators are defined at XML level (see <xref
- linkend="xml-overriding" />):</para>
+ <programlisting>@Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_STORE")
+public Integer getId() { ... } </programlisting>
- <programlisting><table-generator name="EMP_GEN"
+ <para>The next example uses the identity generator:</para>
+
+ <programlisting>@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
+public Long getId() { ... } </programlisting>
+
+ <para>The <literal>AUTO</literal> generator is the preferred type for
+ portable applications (across several DB vendors). The identifier
+ generation configuration can be shared for several
+ <literal>@Id</literal> mappings with the generator attribute. There
+ are several configurations available through
+ <literal>@SequenceGenerator</literal> and
+ <literal>@TableGenerator</literal>. The scope of a generator can be
+ the application or the class. Class-defined generators are not visible
+ outside the class and can override application level generators.
+ Application level generators are defined at XML level (see <xref
+ linkend="xml-overriding" />):</para>
+
+ <programlisting><table-generator name="EMP_GEN"
table="GENERATOR_TABLE"
pk-column-name="key"
value-column-name="hi"
@@ -649,37 +746,47 @@
)
</programlisting>
- <para>If JPA XML (like <filename>META-INF/orm.xml</filename>) is used to
- define thegenerators, <literal>EMP_GEN</literal> and
- <literal>SEQ_GEN</literal> are application level generators.
- <literal>EMP_GEN</literal> defines a table based id generator using the
- hilo algorithm with a <literal>max_lo</literal> of 20. The hi value is
- kept in a <literal>table</literal> "<literal>GENERATOR_TABLE</literal>".
- The information is kept in a row where <literal>pkColumnName</literal>
- "key" is equals to <literal>pkColumnValue</literal>
- "<literal>EMP</literal>" and column <literal>valueColumnName</literal>
- "<literal>hi</literal>" contains the the next high value used.</para>
+ <para>If JPA XML (like <filename>META-INF/orm.xml</filename>) is used
+ to define thegenerators, <literal>EMP_GEN</literal> and
+ <literal>SEQ_GEN</literal> are application level generators.
+ <literal>EMP_GEN</literal> defines a table based id generator using
+ the hilo algorithm with a <literal>max_lo</literal> of 20. The hi
+ value is kept in a <literal>table</literal>
+ "<literal>GENERATOR_TABLE</literal>". The information is kept in a row
+ where <literal>pkColumnName</literal> "key" is equals to
+ <literal>pkColumnValue</literal> "<literal>EMP</literal>" and column
+ <literal>valueColumnName</literal> "<literal>hi</literal>" contains
+ the the next high value used.</para>
- <para><literal>SEQ_GEN</literal> defines a sequence generator using a
- sequence named <literal>my_sequence</literal>. The allocation size used
- for this sequence based hilo algorithm is 20. Note that this version of
- Hibernate Annotations does not handle <literal>initialValue</literal> in
- the sequence generator. The default allocation size is 50, so if you
- want to use a sequence and pickup the value each time, you must set the
- allocation size to 1.</para>
+ <para><literal>SEQ_GEN</literal> defines a sequence generator using a
+ sequence named <literal>my_sequence</literal>. The allocation size
+ used for this sequence based hilo algorithm is 20. Note that this
+ version of Hibernate Annotations does not handle
+ <literal>initialValue</literal> in the sequence generator. The default
+ allocation size is 50, so if you want to use a sequence and pickup the
+ value each time, you must set the allocation size to 1.</para>
- <note>
- <para>Package level definition is no longer supported by the EJB 3.0
- specification. However, you can use the
- <literal>@GenericGenerator</literal> at the package level (see <xref
- linkend="entity-hibspec-identifier" />).</para>
- </note>
+ <important>
+ <para>We recommend all new projects to use
+ <code>hibernate.id.new_generator_mappings=true</code> as the new
+ generators are more efficient and closer to the JPA 2 specification
+ semantic. However they are not backward compatible with existing
+ databases (if a sequence or a table is used for id generation). See
+ <xref linkend="ann-setup-properties" /> for more information on how
+ to activate them.</para>
+ </important>
- <para>The next example shows the definition of a sequence generator in a
- class scope:</para>
+ <note>
+ <para>Package level definition is not supported by the JPA
+ specification. However, you can use the
+ <literal>@GenericGenerator</literal> at the package level (see <xref
+ linkend="entity-hibspec-identifier" />).</para>
+ </note>
- <programlisting>
-@Entity
+ <para>The next example shows the definition of a sequence generator in
+ a class scope:</para>
+
+ <programlisting>@Entity
@javax.persistence.SequenceGenerator(
name="SEQ_STORE",
sequenceName="my_sequence"
@@ -689,120 +796,378 @@
@Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_STORE")
public Long getId() { return id; }
+} </programlisting>
+
+ <para>This class will use a sequence named my_sequence and the
+ SEQ_STORE generator is not visible in other classes. Note that you can
+ check the Hibernate Annotations tests in the
+ <package>org.hibernate.test.annotations.id</package> package for more
+ examples.</para>
+
+ <para>Finally, you can ask Hibernate to copy the identifier from
+ another associated entity. In the Hibernate jargon, it is known as a
+ foreign generator but the JPA mapping reads better and is
+ encouraged.</para>
+
+ <programlisting>@Entity
+class MedicalHistory implements Serializable {
+ <emphasis role="bold">@Id @OneToOne</emphasis>
+ @JoinColumn(name = "person_id")
+ Person patient;
}
- </programlisting>
- <para>This class will use a sequence named my_sequence and the SEQ_STORE
- generator is not visible in other classes. Note that you can check the
- Hibernate Annotations tests in the
- <package>org.hibernate.test.annotations.id</package> package for more
- examples.</para>
+@Entity
+public class Person implements Serializable {
+ @Id @GeneratedValue Integer id;
+}</programlisting>
- <para>You can define a composite primary key through several
- syntaxes:</para>
+ <para>Or alternatively</para>
- <itemizedlist>
- <listitem>
- <para>annotate the component property as @Id and make the component
- class @Embeddable</para>
- </listitem>
+ <programlisting>@Entity
+class MedicalHistory implements Serializable {
+ @Id Integer id;
- <listitem>
- <para>annotate the component property as @EmbeddedId</para>
- </listitem>
+ <emphasis role="bold">@MapsId @OneToOne</emphasis>
+ @JoinColumn(name = "patient_id")
+ Person patient;
+}
- <listitem>
- <para>annotate the class as @IdClass and annotate each property of
- the entity involved in the primary key with @Id</para>
- </listitem>
- </itemizedlist>
+@Entity
+class Person {
+ @Id @GeneratedValue Integer id;
+}</programlisting>
- <para>While quite common to the EJB2 developer,
- <literal>@IdClass</literal> is likely new for Hibernate users. The
- composite primary key class corresponds to multiple fields or properties
- of the entity class, and the names of primary key fields or properties
- in the primary key class and those of the entity class must match and
- their types must be the same. Let's look at an example:</para>
+ <para>But an identifier does not have to be a single property, it ca
+ be composed of several properties.</para>
+ </section>
- <programlisting>@Entity
-<emphasis role="bold">@IdClass(FootballerPk.class)</emphasis>
-public class Footballer {
- //part of the id key
- <emphasis role="bold">@Id</emphasis> public String getFirstname() {
- return firstname;
- }
+ <section>
+ <title>Composite identifier</title>
- public void setFirstname(String firstname) {
- this.firstname = firstname;
- }
+ <para>You can define a composite primary key through several
+ syntaxes:</para>
- //part of the id key
- <emphasis role="bold">@Id</emphasis> public String getLastname() {
- return lastname;
- }
+ <itemizedlist>
+ <listitem>
+ <para>use a component type to represent the identifier and map it
+ as a property in the entity: you then annotated the property as
+ <classname>@EmbeddedId</classname>. The component type has to be
+ <classname>Serializable</classname>.</para>
+ </listitem>
- public void setLastname(String lastname) {
- this.lastname = lastname;
- }
+ <listitem>
+ <para>map multiple properties as <classname>@Id</classname>
+ properties: the identifier type is then the entity class itself
+ and needs to be <classname>Serializable</classname>. This approach
+ is unfortunately not standard and only supported by
+ Hibernate.</para>
+ </listitem>
- public String getClub() {
- return club;
- }
+ <listitem>
+ <para>map multiple properties as <classname>@Id</classname>
+ properties and declare an external class to be the identifier
+ type. This class, which needs to be
+ <classname>Serializable</classname>, is declared on the entity via
+ the <classname>@IdClass</classname> annotation. The identifier
+ type must contain the same properties as the identifier properties
+ of the entity: each property name must be the same, its type must
+ be the same as well if the entity property is of a basic type, its
+ type must be the type of the primary key of the associated entity
+ if the entity property is an association (either a
+ <classname>@OneToOne</classname> or a
+ <classname>@ManyToOne</classname>).</para>
+ </listitem>
+ </itemizedlist>
- public void setClub(String club) {
- this.club = club;
- }
+ <para>As you can see the last case is far from obvious. It has been
+ inherited from the dark ages of EJB 2 for backward compatibilities and
+ we recommend you not to use it (for simplicity sake).</para>
- //appropriate equals() and hashCode() implementation
+ <para>Let's explore all three cases using examples.</para>
+
+ <section>
+ <title>@EmbeddedId property</title>
+
+ <para>Here is a simple example of
+ <classname>@EmbeddedId</classname>.</para>
+
+ <programlisting>@Entity
+class User {
+ <emphasis role="bold" security="">@EmbeddedId
+ @AttributeOverride(name="firstName", column=@Column(name="fld_firstname")
+ UserId id;</emphasis>
+
+ Integer age;
}
@Embeddable
-public class FootballerPk implements Serializable {
- //same name and type as in Footballer
- public String getFirstname() {
- return firstname;
- }
+class UserId implements Serializable {
+ String firstName;
+ String lastName;
+}</programlisting>
- public void setFirstname(String firstname) {
- this.firstname = firstname;
- }
+ <para>You can notice that the <classname>UserId</classname> class is
+ serializable. To override the column mapping, use
+ <classname>@AttributeOverride</classname>.</para>
- //same name and type as in Footballer
- public String getLastname() {
- return lastname;
- }
+ <para>An embedded id can itself contains the primary key of an
+ associated entity.</para>
- public void setLastname(String lastname) {
- this.lastname = lastname;
- }
+ <programlisting>@Entity
+class Customer {
+ @EmbeddedId CustomerId id;
+ boolean preferredCustomer;
- //appropriate equals() and hashCode() implementation
+ <emphasis role="bold">@MapsId("userId")
+ @JoinColumns({
+ @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
+ @JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
+ })
+ @OneToOne User user;</emphasis>
}
-</programlisting>
- <para>As you may have seen, <literal>@IdClass</literal> points to the
- corresponding primary key class.</para>
+@Embeddable
+class CustomerId implements Serializable {
+ <emphasis role="bold">UserId userId;</emphasis>
+ String customerNumber;
+}
- <para>While not supported by the EJB3 specification, Hibernate allows
- you to define associations inside a composite identifier. Simply use the
- regular annotations for that</para>
+@Entity
+class User {
+ @EmbeddedId UserId id;
+ Integer age;
+}
- <programlisting>@Entity
-@AssociationOverride( name="id.channel", joinColumns = @JoinColumn(name="chan_id") )
-public class TvMagazin {
- @EmbeddedId public TvMagazinPk id;
- @Temporal(TemporalType.TIME) Date time;
+@Embeddable
+class UserId implements Serializable {
+ String firstName;
+ String lastName;
+}</programlisting>
+
+ <para>In the embedded id object, the association is represented as
+ the identifier of the associated entity. But you can link its value
+ to a regular association in the entity via the
+ <classname>@MapsId</classname> annotation. The
+ <classname>@MapsId</classname> value correspond to the property name
+ of the embedded id object containing the associated entity's
+ identifier. In the database, it means that the
+ <literal>Customer.user</literal> and the
+ <literal>CustomerId.userId</literal> properties share the same
+ underlying column (<literal>user_fk</literal> in this case). </para>
+
+ <para>In practice, your code only sets the
+ <literal>Customer.user</literal> property and the user id value is
+ copied by Hibernate into the <literal>CustomerId.userId</literal>
+ property.</para>
+
+ <warning>
+ <para>The id value can be copied as late as flush time, don't rely
+ on it until after flush time. </para>
+ </warning>
+
+ <para>While not supported in JPA, Hibernate lets you place your
+ association directly in the embedded id component (instead of having
+ to use the <classname>@MapsId</classname> annotation).</para>
+
+ <programlisting>@Entity
+class Customer {
+ @EmbeddedId CustomerId id;
+ boolean preferredCustomer;
}
@Embeddable
-public class TvMagazinPk implements Serializable {
- @ManyToOne
- public Channel channel;
- public String name;
- @ManyToOne
- public Presenter presenter;
+class CustomerId implements Serializable {
+ <emphasis role="bold">@OneToOne
+ @JoinColumns({
+ @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
+ @JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
+ })
+ User user;</emphasis>
+ String customerNumber;
}
-</programlisting>
+
+@Entity
+class User {
+ @EmbeddedId UserId id;
+ Integer age;
+}
+
+@Embeddable
+class UserId implements Serializable {
+ String firstName;
+ String lastName;
+}</programlisting>
+ </section>
+
+ <section>
+ <title>Multiple @Id properties</title>
+
+ <para>Another arguably more natural) approach is to place
+ <classname>@Id</classname> on multiple properties of my entity. This
+ approach is only supported by Hibernate but does not require an
+ extra embeddable component.</para>
+
+ <programlisting>@Entity
+class Customer <emphasis role="bold">implements Serializable </emphasis>{
+ <emphasis role="bold">@Id @OneToOne
+ @JoinColumns({
+ @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
+ @JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
+ })
+ User user;</emphasis>
+
+ <emphasis role="bold">@Id</emphasis> String customerNumber;
+
+ boolean preferredCustomer;
+}
+
+@Entity
+class User {
+ @EmbeddedId UserId id;
+ Integer age;
+}
+
+@Embeddable
+class UserId implements Serializable {
+ String firstName;
+ String lastName;
+}</programlisting>
+
+ <para>In this case <classname>Customer</classname> being it's own
+ identifier representation, it must implement
+ <classname>Serializable</classname>.</para>
+ </section>
+
+ <section>
+ <title>@IdClass</title>
+
+ <para><classname>@IdClass</classname> on an entity points to the
+ class (component) representing the identifier of the class. The
+ properties marked <classname>@Id</classname> on the entity must have
+ their corresponding property on the <classname>@IdClass</classname>.
+ The return type of search twin property must be either identical for
+ basic properties or must correspond to the identifier class of the
+ associated entity for an association.</para>
+
+ <warning>
+ <para>This approach is inherited from the EJB 2 days and we
+ recommend against its use. But, after all it's your application
+ and Hibernate supports it.</para>
+ </warning>
+
+ <programlisting>@Entity
+class Customer {
+ <emphasis role="bold">@Id @OneToOne
+ @JoinColumns({
+ @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
+ @JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
+ })
+ User user;</emphasis>
+
+ <emphasis role="bold">@Id</emphasis> String customerNumber;
+
+ boolean preferredCustomer;
+}
+
+class CustomerId implements Serializable {
+ <emphasis role="bold">UserId user;</emphasis>
+ String customerNumber;
+}
+
+@Entity
+class User {
+ @EmbeddedId UserId id;
+ Integer age;
+}
+
+@Embeddable
+class UserId implements Serializable {
+ String firstName;
+ String lastName;
+}</programlisting>
+
+ <para><classname>Customer</classname> and
+ <classname>CustomerId</classname> do have the same properties
+ <literal>customerNumber</literal> as well as
+ <literal>user</literal>.</para>
+
+ <para>While not JPA standard, Hibernate let's you declare the
+ vanilla associated property in the
+ <classname>@IdClass</classname>.</para>
+
+ <programlisting>@Entity
+class Customer {
+ <emphasis role="bold">@Id @OneToOne
+ @JoinColumns({
+ @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
+ @JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
+ })
+ User user;</emphasis>
+
+ <emphasis role="bold">@Id</emphasis> String customerNumber;
+
+ boolean preferredCustomer;
+}
+
+class CustomerId implements Serializable {
+ <emphasis role="bold">@OneToOne User user;</emphasis>
+ String customerNumber;
+}
+
+@Entity
+class User {
+ @EmbeddedId UserId id;
+ Integer age;
+}
+
+@Embeddable
+class UserId implements Serializable {
+ String firstName;
+ String lastName;
+}</programlisting>
+ </section>
+
+ <section>
+ <title>Partial identifier generation</title>
+
+ <para>Hibernate supports the automatic generation of some of the
+ identifier properties. Simply use the
+ <classname>@GeneratedValue</classname> annotation on one or several
+ id properties.</para>
+
+ <warning>
+ <para>The Hibernate team has always felt such a construct as
+ fundamentally wrong. Try hard to fix your data model before using
+ this feature.</para>
+ </warning>
+
+ <programlisting>@Entity
+public class CustomerInventory implements Serializable {
+ @Id
+ @TableGenerator(name = "inventory",
+ table = "U_SEQUENCES",
+ pkColumnName = "S_ID",
+ valueColumnName = "S_NEXTNUM",
+ pkColumnValue = "inventory",
+ allocationSize = 1000)
+ <emphasis role="bold">@GeneratedValue(strategy = GenerationType.TABLE, generator = "inventory")</emphasis>
+ Integer id;
+
+
+ @Id @ManyToOne(cascade = CascadeType.MERGE)
+ Customer customer;
+}
+
+@Entity
+public class Customer implements Serializable {
+ @Id
+ private int id;
+}</programlisting>
+
+ <para>You can also generate properties inside an
+ <classname>@EmbeddedId</classname> class.</para>
+ </section>
+ </section>
</section>
<section>
@@ -965,8 +1330,7 @@
<note>
<para>The default access type (field or methods) is used, unless you
- use the <literal>@Access</literal> or
- <literal>@AccessType</literal></para>
+ use the <literal>@Access</literal> annotation.</para>
</note>
<note>
@@ -1830,8 +2194,7 @@
</programlisting>
<para><literal>@Embeddable</literal> inherit the access type of its
- owning entity unless <literal>@Access</literal> or the Hibernate
- specific annotation <literal>@AccessType</literal> is used. Composite
+ owning entity unless <literal>@Access</literal> is used. Composite
foreign keys (if not using the default sensitive values) are defined on
associations using the <literal>@JoinColumns</literal> element, which is
basically an array of <literal>@JoinColumn</literal>. It is considered a
@@ -2563,172 +2926,6 @@
<title>Property</title>
<section>
- <title>Access type</title>
-
- <para>The default access type is determined from the position of the
- <literal>@Id</literal> or <literal>@EmbeddedId</literal> annotation in
- the entity hierarchy.</para>
-
- <note>
- <para>The placement of annotations within a class hierarchy has to
- be consistent (either field or on property) to be able to determine
- the default access type. It is recommended to stick to one single
- annotation placement strategy throughout your whole
- application.</para>
- </note>
-
- <para>To finetune the access strategy JPA 2 introduces the @Access
- annotation. With its help you can define the access type on:</para>
-
- <itemizedlist>
- <listitem>
- <para>an entity</para>
- </listitem>
-
- <listitem>
- <para>a superclass</para>
- </listitem>
-
- <listitem>
- <para>an embeddable object</para>
- </listitem>
-
- <listitem>
- <para>a property</para>
- </listitem>
- </itemizedlist>
-
- <para>Prior to JPA 2 Hibernate used the Hibernate specific annotation
- <literal>@org.hibernate.annotations.AccessType</literal> to change
- specific access types. @AccessType still exists to support legacy
- systems, but the usage of @Access is recommended for new applications.
- The behaviour of @Access and @AccessType are similar, but there are
- differences. For both annotations applies:</para>
-
- <itemizedlist>
- <listitem>
- <para>The access type is overridden for the annotated element, if
- overridden on a class, all the properties of the given class
- inherit the access type.</para>
- </listitem>
-
- <listitem>
- <para>If an entity is marked as
- <literal>@Access(AccessType.PROPERTY)</literal> or
- <literal>@AccessType("property")</literal> respectively, the
- getters are scanned for annotations, if the enitiy is marked as
- <literal>@Access(AccessType.FIELD)</literal> or
- <literal>@AccessType("field")</literal> respectively, the fields
- are scanned for annotations.</para>
- </listitem>
- </itemizedlist>
-
- <para>In the case where you want to override the access type for a
- property of an entity which already defines an explicit access type
- the annotation placement between @Access and @AccessType
- differs:</para>
-
- <programlisting><emphasis role="bold">@AccessType("property")</emphasis> // set access type for all properties in Country
-public class Country implements Serializable {
- private String iso2;
- private String name;
-
- public String getIso2() {
- return iso2;
- }
-
- public void setIso2(String iso2) {
- this.iso2 = iso2;
- }
-
- @Column(name = "countryName")
- <emphasis role="bold">@AccessType("field")</emphasis> // set the access type for name to field
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-}
-</programlisting>
-
- <programlisting><emphasis role="bold">@Access(AccessType.PROPERTY)</emphasis> // set access type for all properties in Country
-public class Country implements Serializable {
- private String iso2;
-
- <emphasis role="bold">@Access(AccessType.FIELD)</emphasis> // set the access type for name to field
- private String name;
-
- public String getIso2() {
- return iso2;
- }
-
- public void setIso2(String iso2) {
- this.iso2 = iso2;
- }
-
- @Column(name = "countryName")
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-}
-</programlisting>
-
- <note>
- <para>Watch out for the different annotation placement strategy. In
- the case of <literal>@Access</literal> the field has to be annotated
- with the overriding access strategy whereas with
- <literal>@AccessType</literal> the property gets annotated.</para>
- </note>
-
- <para>If a superclass or an embeddable object is not annotated, the
- default entity access type is used.</para>
-
- <programlisting>@Entity
-public class Person implements Serializable {
- @Id @GeneratedValue //access type field
- Integer id;
-
- @Embedded
- @AttributeOverrides({
- @AttributeOverride(name = "iso2", column = @Column(name = "bornIso2")),
- @AttributeOverride(name = "name", column = @Column(name = "bornCountryName"))
- })
- Country bornIn;
-}
-
-@Embeddable
-<emphasis role="bold">@AccessType("property")</emphasis> //override access type for all properties in Country
-public class Country implements Serializable {
- private String iso2;
- private String name;
-
- public String getIso2() {
- return iso2;
- }
-
- public void setIso2(String iso2) {
- this.iso2 = iso2;
- }
-
- @Column(name = "countryName")
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-}
-</programlisting>
- </section>
-
- <section>
<title>Formula</title>
<para>Sometimes, you want the Database to do some computation for you
Modified: core/trunk/annotations/src/main/docbook/en/modules/setup.xml
===================================================================
--- core/trunk/annotations/src/main/docbook/en/modules/setup.xml 2010-02-23 14:55:16 UTC (rev 18859)
+++ core/trunk/annotations/src/main/docbook/en/modules/setup.xml 2010-02-23 19:12:49 UTC (rev 18860)
@@ -204,7 +204,7 @@
annotations, except for this startup routine change or in the
configuration file. You can use your favorite configuration method for
other properties ( <filename>hibernate.properties</filename>,
- <filename>hibernate.cfg.xml</filename>, programmatic APIs, etc). </para>
+ <filename>hibernate.cfg.xml</filename>, programmatic APIs, etc).</para>
<note>
<para>You can mix annotated persistent classes and classic
@@ -225,7 +225,7 @@
conflict occurs.</para>
</section>
- <section>
+ <section id="ann-setup-properties">
<title id="setup-properties">Properties</title>
<para>On top of the Hibernate Core properties, Hibernate Annotations
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/c/ForeignGeneratorViaMapsIdTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/c/ForeignGeneratorViaMapsIdTest.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/c/ForeignGeneratorViaMapsIdTest.java 2010-02-23 19:12:49 UTC (rev 18860)
@@ -0,0 +1,38 @@
+package org.hibernate.test.annotations.derivedidentities.e5.c;
+
+import org.hibernate.Session;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.util.SchemaUtil;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ForeignGeneratorViaMapsIdTest extends TestCase {
+
+ public void testForeignGenerator() throws Exception {
+ assertTrue( SchemaUtil.isColumnPresent( "MedicalHistory", "patient_id", getCfg() ) );
+ Person e = new Person();
+ Session s = openSession( );
+ s.getTransaction().begin();
+ s.persist( e );
+ MedicalHistory d = new MedicalHistory();
+ d.patient = e;
+ s.persist( d );
+ s.flush();
+ s.clear();
+ d = (MedicalHistory) s.get( MedicalHistory.class, e.id);
+ assertEquals( e.id, d.id );
+ s.delete( d );
+ s.delete( d.patient );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ @Override
+ protected Class<?>[] getAnnotatedClasses() {
+ return new Class<?>[] {
+ MedicalHistory.class,
+ Person.class
+ };
+ }
+}
Copied: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/c/MedicalHistory.java (from rev 18789, core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/a/MedicalHistory.java)
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/c/MedicalHistory.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/c/MedicalHistory.java 2010-02-23 19:12:49 UTC (rev 18860)
@@ -0,0 +1,25 @@
+package org.hibernate.test.annotations.derivedidentities.e5.c;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.MapsId;
+import javax.persistence.OneToOne;
+
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class MedicalHistory implements Serializable {
+ @Id
+ Integer id;
+
+ @MapsId
+ @JoinColumn(name = "patient_id")
+ @OneToOne
+ Person patient;
+}
\ No newline at end of file
Copied: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/c/Person.java (from rev 18789, core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/a/Person.java)
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/c/Person.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e5/c/Person.java 2010-02-23 19:12:49 UTC (rev 18860)
@@ -0,0 +1,14 @@
+package org.hibernate.test.annotations.derivedidentities.e5.c;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Person {
+ @Id @GeneratedValue
+ Integer id;
+}
\ No newline at end of file
14 years, 12 months
Hibernate SVN: r18859 - core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-02-23 09:55:16 -0500 (Tue, 23 Feb 2010)
New Revision: 18859
Added:
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Prcontra.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/PrcontraPK.java
Modified:
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/StaticMetadataTest.java
Log:
HHH-4942 Refactored JarVistitorTest and PackagedEntityManagerTest to use Shrinkwrap to build the packages needed for the tests. This removed the need for some custom antrun plugin stuff. Also created a baseclass for the packaged tests.
HHH-4845 Refactored PersistTest to extend from the main em base test case. This allows the em test to run in forkMode 'once'
Added: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Prcontra.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Prcontra.java (rev 0)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Prcontra.java 2010-02-23 14:55:16 UTC (rev 18859)
@@ -0,0 +1,1487 @@
+// $Id:$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.ejb.test.metadata;
+
+import java.io.Serializable;
+import java.math.BigInteger;
+import java.util.Date;
+import javax.persistence.Column;
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+import javax.persistence.Table;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+
+import org.hibernate.annotations.Formula;
+
+@Entity
+@Table(name = "PRCONTRA", schema = "MUVALE")
+public class Prcontra implements Serializable {
+ private static final long serialVersionUID = -4996315772144793755L;
+ @EmbeddedId
+ protected PrcontraPK prcontraPK;
+ @Column(name = "DOC", nullable = false, insertable = false, updatable = false)
+ private BigInteger doc;
+ @Column(name = "NIF", nullable = false, insertable = false, updatable = false)
+ private String nif;
+ @Column(name = "ANNO")
+ private BigInteger anno;
+// @Column(name = "NIF",insertable=false, updatable=false,nullable=false)
+ // private String nif;
+ @Column(name = "PRSSEM")
+ private BigInteger prssem;
+ @Column(name = "NISSEM")
+ private BigInteger nissem;
+ @Column(name = "COSSEM")
+ private BigInteger cossem;
+ @Column(name = "REGIMEN")
+ private BigInteger regimen;
+ @Column(name = "CONTACTO")
+ private String contacto;
+ @Column(name = "TELEFONO")
+ private String telefono;
+ @Column(name = "FAX")
+ private String fax;
+ @Column(name = "NUTRA")
+ private BigInteger nutra;
+ @Column(name = "NUTRAT")
+ private BigInteger nutrat;
+ @Column(name = "CNAE")
+ private BigInteger cnae;
+ @Column(name = "GREMP")
+ private BigInteger gremp;
+ @Column(name = "A1")
+ private Character a1;
+ @Column(name = "F_ALTA")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date fAlta;
+ @Column(name = "F_BAJA")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date fBaja;
+ @Column(name = "PRECIO")
+ private Float precio;
+ @Column(name = "MPAGO")
+ private BigInteger mpago;
+ @Column(name = "PERIO")
+ private BigInteger perio;
+ @Column(name = "CTABANCO")
+ private String ctabanco;
+ @Column(name = "QUIENFIRMA")
+ private String quienfirma;
+ @Column(name = "DNIFIRMA")
+ private String dnifirma;
+ @Column(name = "CARGOFIRMA")
+ private String cargofirma;
+ @Column(name = "F_ESCRITURA")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date fEscritura;
+ @Column(name = "NOTARIO")
+ private String notario;
+ @Column(name = "POBLANOT")
+ private String poblanot;
+ @Column(name = "PROTOCOLO")
+ private String protocolo;
+ @Column(name = "LUGARFIRMA")
+ private String lugarfirma;
+ @Column(name = "CONTF")
+ private BigInteger contf;
+ @Column(name = "BLOQUEO")
+ private Character bloqueo;
+ @Column(name = "FACTURA")
+ private Character factura;
+ @Column(name = "ENPODER")
+ private String enpoder;
+ @Column(name = "CPAR1")
+ private Character cpar1;
+ @Column(name = "CPAR2")
+ private Character cpar2;
+ @Column(name = "CPAR3")
+ private Character cpar3;
+ @Column(name = "CPAR4")
+ private Character cpar4;
+ @Column(name = "CPAR5")
+ private Character cpar5;
+ @Column(name = "CPAR6")
+ private Character cpar6;
+ @Column(name = "CPAR7")
+ private Character cpar7;
+ @Column(name = "CPAR8")
+ private Character cpar8;
+ @Column(name = "CPAR9")
+ private Character cpar9;
+ @Column(name = "SPP1")
+ private Character spp1;
+ @Column(name = "SPP2")
+ private Character spp2;
+ @Column(name = "SPP3")
+ private Character spp3;
+ @Column(name = "RR")
+ private Character rr;
+ @Column(name = "TIPOC")
+ private String tipoc;
+ @Column(name = "PTRAB")
+ private String ptrab;
+ @Column(name = "PCURSO")
+ private String pcurso;
+ @Column(name = "USUALT")
+ private BigInteger usualt;
+ @Column(name = "F_USU")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date fUsu;
+ @Column(name = "FIRMADO")
+ private Character firmado;
+ @Column(name = "VS")
+ private Character vs;
+ @Column(name = "CENTRA")
+ private BigInteger centra;
+ @Column(name = "RT")
+ private BigInteger rt;
+ @Column(name = "F1")
+ private Character f1;
+ @Column(name = "IPC")
+ private Character ipc;
+ @Column(name = "NR")
+ private BigInteger nr;
+ @Column(name = "COORD")
+ private BigInteger coord;
+ @Column(name = "OBSERV")
+ private String observ;
+ @Column(name = "TM")
+ private BigInteger tm;
+ @Column(name = "RE")
+ private BigInteger re;
+ @Column(name = "UMOVIL")
+ private Character umovil;
+ @Column(name = "ADS")
+ private BigInteger ads;
+ @Column(name = "F_DESCARGA")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date fDescarga;
+ @Column(name = "GRUPO_EMP")
+ private BigInteger grupoEmp;
+ @Column(name = "OBSERV1")
+ private String observ1;
+ @Column(name = "OBSERV2")
+ private String observ2;
+ @Column(name = "F_LLAMADA1")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date fLlamada1;
+ @Column(name = "NA1")
+ private Character na1;
+ @Column(name = "CONST")
+ private Character const1;
+ @Column(name = "F_EVR")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date fEvr;
+ @Column(name = "F_PLAN")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date fPlan;
+ @Column(name = "F_MEMORIA")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date fMemoria;
+ @Column(name = "F_RENOVE")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date fRenove;
+ @Column(name = "INCI")
+ private Character inci;
+ @Column(name = "F_ENV_PLAN")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date fEnvPlan;
+ @Column(name = "A1_DOC_IMP")
+ private Float a1DocImp;
+ @Column(name = "A1_DOC_NTRA")
+ private Float a1DocNtra;
+ @Column(name = "A1_RM_IMP")
+ private Float a1RmImp;
+ @Column(name = "A1_RM_NTRA")
+ private Float a1RmNtra;
+ @Column(name = "NA1_DOC_IMP")
+ private Float na1DocImp;
+ @Column(name = "NA1_DOC_NTRA")
+ private Float na1DocNtra;
+ @Column(name = "NA1_RM_IMP")
+ private Float na1RmImp;
+ @Column(name = "NA1_RM_NTRA")
+ private Float na1RmNtra;
+ @Column(name = "CONST_DOC_IMP")
+ private Float constDocImp;
+ @Column(name = "CONST_DOC_NTRA")
+ private Float constDocNtra;
+ @Column(name = "CONST_RM_IMP")
+ private Float constRmImp;
+ @Column(name = "CONST_RM_NTRA")
+ private String constRmNtra;
+ @Column(name = "TIENE_PRE")
+ private Character tienePre;
+ @Column(name = "ACEPTA_PRE")
+ private Character aceptaPre;
+ @Column(name = "F_PRE")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date fPre;
+ @Column(name = "NHORAS")
+ private BigInteger nhoras;
+ @Column(name = "CHORA")
+ private Float chora;
+ @Column(name = "IND_UNICO")
+ private BigInteger indUnico;
+ @Column(name = "NUMEROI")
+ private BigInteger numeroi;
+ @Column(name = "RENOVI")
+ private BigInteger renovi;
+ @Column(name = "TIPOI")
+ private BigInteger tipoi;
+ @Column(name = "TARIFA")
+ private Float tarifa;
+ @Column(name = "IPC_PORC")
+ private Float ipcPorc;
+ @Column(name = "F_REC_MEM")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date fRecMem;
+ @Column(name = "F_REC_PLAN")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date fRecPlan;
+ @Column(name = "IPC_IMP")
+ private Float ipcImp;
+ @Column(name = "UMOVIL_IMP")
+ private Float umovilImp;
+ @Column(name = "QUIENFIRMA2")
+ private String quienfirma2;
+ @Column(name = "DNIFIRMA2")
+ private String dnifirma2;
+ @Column(name = "CARGOFIRMA2")
+ private String cargofirma2;
+ @Column(name = "DOMIC_ENV")
+ private String domicEnv;
+ @Column(name = "PROVI_ENV")
+ private BigInteger proviEnv;
+ @Column(name = "POBLA_ENV")
+ private BigInteger poblaEnv;
+ @Column(name = "DISPO_ENV")
+ private BigInteger dispoEnv;
+ @Column(name = "MUT_ORIGEN")
+ private BigInteger mutOrigen;
+ @Column(name = "COD_CONCIERTO")
+ private String codConcierto;
+ @Column(name = "N_PEDIDO")
+ private String nPedido;
+ @Column(name = "D_FACTURA")
+ private BigInteger dFactura;
+ @Column(name = "D_VENCIMIENTO")
+ private String dVencimiento;
+ @Column(name = "CON_NRM_RH")
+ private BigInteger conNrmRh;
+ @Column(name = "CON_NRM_RT")
+ private BigInteger conNrmRt;
+
+ @Column(name = "CON_PRECIO_RM_EXCESO")
+ private Float conPrecioRmExceso;
+ @Column(name = "CON_NTRA_DOC_RH")
+ private BigInteger conNtraDocRh;
+ @Column(name = "CON_IMPDOC_RHIGIENICO")
+ private Float conImpDocRhigienico;
+ @Column(name = "CON_IMPRM_RHIGIENICO")
+ private Float conImprmRhigienico;
+ @Column(name = "CON_NTRA_DOC_RT")
+ private BigInteger conNtraDocRt;
+ @Column(name = "CON_IMPDOC_RTIPOLOGIAS")
+ private Float conImpdocRTipologias;
+ @Column(name = "CON_IMPRM_RTIPOLOGIAS")
+ private Float conImprmRtipologias;
+ @Column(name = "CON_IMP_UMOVIL")
+ private Float conImpUmovil;
+ @Column(name = "CON_PRECIO_SME")
+ private Float conPrecioSme;
+
+
+ @Formula(value = "(select pago.texto from muvale.mpago pago where pago.mpago=mpago)")
+ private String textoMpago;
+
+ @Formula(value = "(" +
+ "muvale.nutra_nif(" +
+ " to_char(F_ALTA,'RRRR')," +
+ " to_char(F_ALTA,'MM')," +
+ " nif) " +
+ ")")
+ private Integer totalAfiliados;
+
+ // Modo de pago
+ @Formula(value = "(select p.DOM_DESCRIPCION from prevencion.prv_dominios_prevencion p where p.dom_campo='TPRECIO' and p.dom_valor=tarifa)")
+ private String modo;
+
+ // Impagado
+ @Formula(value = "( SELECT distinct 1 " +
+ " FROM MUVALE.PRFAC A " +
+ " inner join MUVALE.PRECIB R on A.ANNO = R.ANNO and A.NUMFAC = R.NUMFAC and A.SERIE = R.SERIE" +
+ " WHERE A.SERIE = 10" +
+ " AND R.NUM = (SELECT MAX(R1.NUM) " +
+ " FROM MUVALE.PRECIB R1 " +
+ " WHERE R.ANNO = R1.ANNO " +
+ " AND R.NUMFAC = R1.NUMFAC " +
+ " AND R.SERIE = R1.SERIE " +
+ " AND R.LIN = R1.LIN) " +
+ " AND R.COBRADO IN ('I','J') " +
+ " and a.numero = numero and a.renov = renov and a.tipo = tipo)")
+ private Integer impagado;
+
+ @Formula(value = "( " +
+ " select count( r.rec_codigo ) " +
+ " from prevencion.vds_reconocimiento r " +
+ " where r.rec_numero= NUMERO " +
+ " and r.rec_tipo = 2 " +
+ " and r.rec_fecha between F_ALTA and nvl(F_BAJA,sysdate) " +
+ " and r.rec_estado>0 " +
+ " and r.rec_tiprec in(0,1,3,10,15,16,17) )")
+ //Los mismos que en VdsReconocimientoDAO.FILTRO_TIPO_DE_RECONOCIMENTO
+ private Long numReconRealizados;
+
+ @Formula(value = "( " +
+ " nvl(CON_NRM_RH,0) + nvl(CON_NRM_RT,0) " +
+ " )")
+ private Long numReconPrevistos;
+
+ //END-ENTITY-MOD
+
+
+ public Prcontra() {
+ }
+
+ public Prcontra(PrcontraPK prcontraPK) {
+ this.prcontraPK = prcontraPK;
+
+ }
+
+ public Prcontra(BigInteger numero, BigInteger renov, BigInteger tipo) {
+ this.prcontraPK = new PrcontraPK( numero, renov, tipo );
+ }
+
+ public Prcontra(BigInteger numero, BigInteger renov, BigInteger tipo, Date fAlta, Character bloqueo) {
+ this.prcontraPK = new PrcontraPK( numero, renov, tipo );
+ this.fAlta = fAlta;
+ this.bloqueo = bloqueo;
+ }
+
+ public PrcontraPK getPrcontraPK() {
+ return prcontraPK;
+ }
+
+ public void setPrcontraPK(PrcontraPK prcontraPK) {
+ this.prcontraPK = prcontraPK;
+ }
+
+ public BigInteger getAnno() {
+ return anno;
+ }
+
+ public void setAnno(BigInteger anno) {
+ this.anno = anno;
+ }
+
+// public String getNif() {
+// return nif;
+// }
+//
+// public void setNif(String nif) {
+// this.nif = nif;
+// }
+
+ public BigInteger getPrssem() {
+ return prssem;
+ }
+
+ public void setPrssem(BigInteger prssem) {
+ this.prssem = prssem;
+ }
+
+ public BigInteger getNissem() {
+ return nissem;
+ }
+
+ public void setNissem(BigInteger nissem) {
+ this.nissem = nissem;
+ }
+
+ public BigInteger getCossem() {
+ return cossem;
+ }
+
+ public void setCossem(BigInteger cossem) {
+ this.cossem = cossem;
+ }
+
+ public BigInteger getRegimen() {
+ return regimen;
+ }
+
+ public void setRegimen(BigInteger regimen) {
+ this.regimen = regimen;
+ }
+
+ public String getContacto() {
+ return contacto;
+ }
+
+ public void setContacto(String contacto) {
+ this.contacto = contacto;
+ }
+
+ public String getTelefono() {
+ return telefono;
+ }
+
+ public void setTelefono(String telefono) {
+ this.telefono = telefono;
+ }
+
+ public String getFax() {
+ return fax;
+ }
+
+ public void setFax(String fax) {
+ this.fax = fax;
+ }
+
+ public BigInteger getNutra() {
+ return nutra;
+ }
+
+ public void setNutra(BigInteger nutra) {
+ this.nutra = nutra;
+ }
+
+ public BigInteger getNutrat() {
+ return nutrat;
+ }
+
+ public void setNutrat(BigInteger nutrat) {
+ this.nutrat = nutrat;
+ }
+
+ public BigInteger getCnae() {
+ return cnae;
+ }
+
+ public void setCnae(BigInteger cnae) {
+ this.cnae = cnae;
+ }
+
+ public BigInteger getGremp() {
+ return gremp;
+ }
+
+ public void setGremp(BigInteger gremp) {
+ this.gremp = gremp;
+ }
+
+ public Character getA1() {
+ return a1;
+ }
+
+ public void setA1(Character a1) {
+ this.a1 = a1;
+ }
+
+ public Date getFAlta() {
+ return fAlta;
+ }
+
+ public void setFAlta(Date fAlta) {
+ this.fAlta = fAlta;
+ }
+
+ public Date getFBaja() {
+ return fBaja;
+ }
+
+ public void setFBaja(Date fBaja) {
+ this.fBaja = fBaja;
+ }
+
+ public Float getPrecio() {
+ return precio;
+ }
+
+ public void setPrecio(Float precio) {
+ this.precio = precio;
+ }
+
+ public BigInteger getMpago() {
+ return mpago;
+ }
+
+ public void setMpago(BigInteger mpago) {
+ this.mpago = mpago;
+ }
+
+ public BigInteger getPerio() {
+ return perio;
+ }
+
+ public void setPerio(BigInteger perio) {
+ this.perio = perio;
+ }
+
+ public String getCtabanco() {
+ return ctabanco;
+ }
+
+ public void setCtabanco(String ctabanco) {
+ this.ctabanco = ctabanco;
+ }
+
+ public String getQuienfirma() {
+ return quienfirma;
+ }
+
+ public void setQuienfirma(String quienfirma) {
+ this.quienfirma = quienfirma;
+ }
+
+ public String getDnifirma() {
+ return dnifirma;
+ }
+
+ public void setDnifirma(String dnifirma) {
+ this.dnifirma = dnifirma;
+ }
+
+ public String getCargofirma() {
+ return cargofirma;
+ }
+
+ public void setCargofirma(String cargofirma) {
+ this.cargofirma = cargofirma;
+ }
+
+ public Date getFEscritura() {
+ return fEscritura;
+ }
+
+ public void setFEscritura(Date fEscritura) {
+ this.fEscritura = fEscritura;
+ }
+
+ public String getNotario() {
+ return notario;
+ }
+
+ public void setNotario(String notario) {
+ this.notario = notario;
+ }
+
+ public String getPoblanot() {
+ return poblanot;
+ }
+
+ public void setPoblanot(String poblanot) {
+ this.poblanot = poblanot;
+ }
+
+ public String getProtocolo() {
+ return protocolo;
+ }
+
+ public void setProtocolo(String protocolo) {
+ this.protocolo = protocolo;
+ }
+
+ public String getLugarfirma() {
+ return lugarfirma;
+ }
+
+ public void setLugarfirma(String lugarfirma) {
+ this.lugarfirma = lugarfirma;
+ }
+
+ public BigInteger getContf() {
+ return contf;
+ }
+
+ public void setContf(BigInteger contf) {
+ this.contf = contf;
+ }
+
+ public Character getBloqueo() {
+ return bloqueo;
+ }
+
+ public void setBloqueo(Character bloqueo) {
+ this.bloqueo = bloqueo;
+ }
+
+ public Character getFactura() {
+ return factura;
+ }
+
+ public void setFactura(Character factura) {
+ this.factura = factura;
+ }
+
+ public String getEnpoder() {
+ return enpoder;
+ }
+
+ public void setEnpoder(String enpoder) {
+ this.enpoder = enpoder;
+ }
+
+ public Character getCpar1() {
+ return cpar1;
+ }
+
+ public void setCpar1(Character cpar1) {
+ this.cpar1 = cpar1;
+ }
+
+ public Character getCpar2() {
+ return cpar2;
+ }
+
+ public void setCpar2(Character cpar2) {
+ this.cpar2 = cpar2;
+ }
+
+ public Character getCpar3() {
+ return cpar3;
+ }
+
+ public void setCpar3(Character cpar3) {
+ this.cpar3 = cpar3;
+ }
+
+ public Character getCpar4() {
+ return cpar4;
+ }
+
+ public void setCpar4(Character cpar4) {
+ this.cpar4 = cpar4;
+ }
+
+ public Character getCpar5() {
+ return cpar5;
+ }
+
+ public void setCpar5(Character cpar5) {
+ this.cpar5 = cpar5;
+ }
+
+ public Character getCpar6() {
+ return cpar6;
+ }
+
+ public void setCpar6(Character cpar6) {
+ this.cpar6 = cpar6;
+ }
+
+ public Character getCpar7() {
+ return cpar7;
+ }
+
+ public void setCpar7(Character cpar7) {
+ this.cpar7 = cpar7;
+ }
+
+ public Character getCpar8() {
+ return cpar8;
+ }
+
+ public void setCpar8(Character cpar8) {
+ this.cpar8 = cpar8;
+ }
+
+ public Character getCpar9() {
+ return cpar9;
+ }
+
+ public void setCpar9(Character cpar9) {
+ this.cpar9 = cpar9;
+ }
+
+ public Character getSpp1() {
+ return spp1;
+ }
+
+ public void setSpp1(Character spp1) {
+ this.spp1 = spp1;
+ }
+
+ public Character getSpp2() {
+ return spp2;
+ }
+
+ public void setSpp2(Character spp2) {
+ this.spp2 = spp2;
+ }
+
+ public Character getSpp3() {
+ return spp3;
+ }
+
+ public void setSpp3(Character spp3) {
+ this.spp3 = spp3;
+ }
+
+ public Character getRr() {
+ return rr;
+ }
+
+ public void setRr(Character rr) {
+ this.rr = rr;
+ }
+
+ public String getTipoc() {
+ return tipoc;
+ }
+
+ public void setTipoc(String tipoc) {
+ this.tipoc = tipoc;
+ }
+
+ public String getPtrab() {
+ return ptrab;
+ }
+
+ public void setPtrab(String ptrab) {
+ this.ptrab = ptrab;
+ }
+
+ public String getPcurso() {
+ return pcurso;
+ }
+
+ public void setPcurso(String pcurso) {
+ this.pcurso = pcurso;
+ }
+
+ public BigInteger getUsualt() {
+ return usualt;
+ }
+
+ public void setUsualt(BigInteger usualt) {
+ this.usualt = usualt;
+ }
+
+ public Date getFUsu() {
+ return fUsu;
+ }
+
+ public void setFUsu(Date fUsu) {
+ this.fUsu = fUsu;
+ }
+
+ public Character getFirmado() {
+ return firmado;
+ }
+
+ public void setFirmado(Character firmado) {
+ this.firmado = firmado;
+ }
+
+ public Character getVs() {
+ return vs;
+ }
+
+ public void setVs(Character vs) {
+ this.vs = vs;
+ }
+
+ public BigInteger getCentra() {
+ return centra;
+ }
+
+ public void setCentra(BigInteger centra) {
+ this.centra = centra;
+ }
+
+ public BigInteger getRt() {
+ return rt;
+ }
+
+ public void setRt(BigInteger rt) {
+ this.rt = rt;
+ }
+
+ public Character getF1() {
+ return f1;
+ }
+
+ public void setF1(Character f1) {
+ this.f1 = f1;
+ }
+
+ public Character getIpc() {
+ return ipc;
+ }
+
+ public void setIpc(Character ipc) {
+ this.ipc = ipc;
+ }
+
+ public BigInteger getNr() {
+ return nr;
+ }
+
+ public void setNr(BigInteger nr) {
+ this.nr = nr;
+ }
+
+ public BigInteger getCoord() {
+ return coord;
+ }
+
+ public void setCoord(BigInteger coord) {
+ this.coord = coord;
+ }
+
+ public String getObserv() {
+ return observ;
+ }
+
+ public void setObserv(String observ) {
+ this.observ = observ;
+ }
+
+ public BigInteger getTm() {
+ return tm;
+ }
+
+ public void setTm(BigInteger tm) {
+ this.tm = tm;
+ }
+
+ public BigInteger getRe() {
+ return re;
+ }
+
+ public void setRe(BigInteger re) {
+ this.re = re;
+ }
+
+ public Character getUmovil() {
+ return umovil;
+ }
+
+ public void setUmovil(Character umovil) {
+ this.umovil = umovil;
+ }
+
+ public BigInteger getAds() {
+ return ads;
+ }
+
+ public void setAds(BigInteger ads) {
+ this.ads = ads;
+ }
+
+ public Date getFDescarga() {
+ return fDescarga;
+ }
+
+ public void setFDescarga(Date fDescarga) {
+ this.fDescarga = fDescarga;
+ }
+
+ public BigInteger getGrupoEmp() {
+ return grupoEmp;
+ }
+
+ public void setGrupoEmp(BigInteger grupoEmp) {
+ this.grupoEmp = grupoEmp;
+ }
+
+ public String getObserv1() {
+ return observ1;
+ }
+
+ public void setObserv1(String observ1) {
+ this.observ1 = observ1;
+ }
+
+ public String getObserv2() {
+ return observ2;
+ }
+
+ public void setObserv2(String observ2) {
+ this.observ2 = observ2;
+ }
+
+ public Date getFLlamada1() {
+ return fLlamada1;
+ }
+
+ public void setFLlamada1(Date fLlamada1) {
+ this.fLlamada1 = fLlamada1;
+ }
+
+ public Character getNa1() {
+ return na1;
+ }
+
+ public void setNa1(Character na1) {
+ this.na1 = na1;
+ }
+
+ public Character getConst1() {
+ return const1;
+ }
+
+ public void setConst1(Character const1) {
+ this.const1 = const1;
+ }
+
+ public Date getFEvr() {
+ return fEvr;
+ }
+
+ public void setFEvr(Date fEvr) {
+ this.fEvr = fEvr;
+ }
+
+ public Date getFPlan() {
+ return fPlan;
+ }
+
+ public void setFPlan(Date fPlan) {
+ this.fPlan = fPlan;
+ }
+
+ public Date getFMemoria() {
+ return fMemoria;
+ }
+
+ public void setFMemoria(Date fMemoria) {
+ this.fMemoria = fMemoria;
+ }
+
+ public Date getFRenove() {
+ return fRenove;
+ }
+
+ public void setFRenove(Date fRenove) {
+ this.fRenove = fRenove;
+ }
+
+ public Character getInci() {
+ return inci;
+ }
+
+ public void setInci(Character inci) {
+ this.inci = inci;
+ }
+
+ public Date getFEnvPlan() {
+ return fEnvPlan;
+ }
+
+ public void setFEnvPlan(Date fEnvPlan) {
+ this.fEnvPlan = fEnvPlan;
+ }
+
+ public Float getA1DocImp() {
+ return a1DocImp;
+ }
+
+ public void setA1DocImp(Float a1DocImp) {
+ this.a1DocImp = a1DocImp;
+ }
+
+ public Float getA1DocNtra() {
+ return a1DocNtra;
+ }
+
+ public void setA1DocNtra(Float a1DocNtra) {
+ this.a1DocNtra = a1DocNtra;
+ }
+
+ public Float getA1RmImp() {
+ return a1RmImp;
+ }
+
+ public void setA1RmImp(Float a1RmImp) {
+ this.a1RmImp = a1RmImp;
+ }
+
+ public Float getA1RmNtra() {
+ return a1RmNtra;
+ }
+
+ public void setA1RmNtra(Float a1RmNtra) {
+ this.a1RmNtra = a1RmNtra;
+ }
+
+ public Float getNa1DocImp() {
+ return na1DocImp;
+ }
+
+ public void setNa1DocImp(Float na1DocImp) {
+ this.na1DocImp = na1DocImp;
+ }
+
+ public Float getNa1DocNtra() {
+ return na1DocNtra;
+ }
+
+ public void setNa1DocNtra(Float na1DocNtra) {
+ this.na1DocNtra = na1DocNtra;
+ }
+
+ public Float getNa1RmImp() {
+ return na1RmImp;
+ }
+
+ public void setNa1RmImp(Float na1RmImp) {
+ this.na1RmImp = na1RmImp;
+ }
+
+ public Float getNa1RmNtra() {
+ return na1RmNtra;
+ }
+
+ public void setNa1RmNtra(Float na1RmNtra) {
+ this.na1RmNtra = na1RmNtra;
+ }
+
+ public Float getConstDocImp() {
+ return constDocImp;
+ }
+
+ public void setConstDocImp(Float constDocImp) {
+ this.constDocImp = constDocImp;
+ }
+
+ public Float getConstDocNtra() {
+ return constDocNtra;
+ }
+
+ public void setConstDocNtra(Float constDocNtra) {
+ this.constDocNtra = constDocNtra;
+ }
+
+ public Float getConstRmImp() {
+ return constRmImp;
+ }
+
+ public void setConstRmImp(Float constRmImp) {
+ this.constRmImp = constRmImp;
+ }
+
+ public String getConstRmNtra() {
+ return constRmNtra;
+ }
+
+ public void setConstRmNtra(String constRmNtra) {
+ this.constRmNtra = constRmNtra;
+ }
+
+ public Character getTienePre() {
+ return tienePre;
+ }
+
+ public void setTienePre(Character tienePre) {
+ this.tienePre = tienePre;
+ }
+
+ public Character getAceptaPre() {
+ return aceptaPre;
+ }
+
+ public void setAceptaPre(Character aceptaPre) {
+ this.aceptaPre = aceptaPre;
+ }
+
+ public Date getFPre() {
+ return fPre;
+ }
+
+ public void setFPre(Date fPre) {
+ this.fPre = fPre;
+ }
+
+ public BigInteger getNhoras() {
+ return nhoras;
+ }
+
+ public void setNhoras(BigInteger nhoras) {
+ this.nhoras = nhoras;
+ }
+
+ public Float getChora() {
+ return chora;
+ }
+
+ public void setChora(Float chora) {
+ this.chora = chora;
+ }
+
+ public BigInteger getIndUnico() {
+ return indUnico;
+ }
+
+ public void setIndUnico(BigInteger indUnico) {
+ this.indUnico = indUnico;
+ }
+
+ public BigInteger getNumeroi() {
+ return numeroi;
+ }
+
+ public void setNumeroi(BigInteger numeroi) {
+ this.numeroi = numeroi;
+ }
+
+ public BigInteger getRenovi() {
+ return renovi;
+ }
+
+ public void setRenovi(BigInteger renovi) {
+ this.renovi = renovi;
+ }
+
+ public BigInteger getTipoi() {
+ return tipoi;
+ }
+
+ public void setTipoi(BigInteger tipoi) {
+ this.tipoi = tipoi;
+ }
+
+ public Float getTarifa() {
+ return tarifa;
+ }
+
+ public void setTarifa(Float tarifa) {
+ this.tarifa = tarifa;
+ }
+
+ public Float getIpcPorc() {
+ return ipcPorc;
+ }
+
+ public void setIpcPorc(Float ipcPorc) {
+ this.ipcPorc = ipcPorc;
+ }
+
+ public Date getFRecMem() {
+ return fRecMem;
+ }
+
+ public void setFRecMem(Date fRecMem) {
+ this.fRecMem = fRecMem;
+ }
+
+ public Date getFRecPlan() {
+ return fRecPlan;
+ }
+
+ public void setFRecPlan(Date fRecPlan) {
+ this.fRecPlan = fRecPlan;
+ }
+
+ public Float getIpcImp() {
+ return ipcImp;
+ }
+
+ public void setIpcImp(Float ipcImp) {
+ this.ipcImp = ipcImp;
+ }
+
+ public Float getUmovilImp() {
+ return umovilImp;
+ }
+
+ public void setUmovilImp(Float umovilImp) {
+ this.umovilImp = umovilImp;
+ }
+
+ public String getQuienfirma2() {
+ return quienfirma2;
+ }
+
+ public void setQuienfirma2(String quienfirma2) {
+ this.quienfirma2 = quienfirma2;
+ }
+
+ public String getDnifirma2() {
+ return dnifirma2;
+ }
+
+ public void setDnifirma2(String dnifirma2) {
+ this.dnifirma2 = dnifirma2;
+ }
+
+ public String getCargofirma2() {
+ return cargofirma2;
+ }
+
+ public void setCargofirma2(String cargofirma2) {
+ this.cargofirma2 = cargofirma2;
+ }
+
+ public String getDomicEnv() {
+ return domicEnv;
+ }
+
+ public void setDomicEnv(String domicEnv) {
+ this.domicEnv = domicEnv;
+ }
+
+ public BigInteger getProviEnv() {
+ return proviEnv;
+ }
+
+ public void setProviEnv(BigInteger proviEnv) {
+ this.proviEnv = proviEnv;
+ }
+
+ public BigInteger getPoblaEnv() {
+ return poblaEnv;
+ }
+
+ public void setPoblaEnv(BigInteger poblaEnv) {
+ this.poblaEnv = poblaEnv;
+ }
+
+ public BigInteger getDispoEnv() {
+ return dispoEnv;
+ }
+
+ public void setDispoEnv(BigInteger dispoEnv) {
+ this.dispoEnv = dispoEnv;
+ }
+
+ public BigInteger getMutOrigen() {
+ return mutOrigen;
+ }
+
+ public void setMutOrigen(BigInteger mutOrigen) {
+ this.mutOrigen = mutOrigen;
+ }
+
+ public String getCodConcierto() {
+ return codConcierto;
+ }
+
+ public void setCodConcierto(String codConcierto) {
+ this.codConcierto = codConcierto;
+ }
+
+ public String getNPedido() {
+ return nPedido;
+ }
+
+ public void setNPedido(String nPedido) {
+ this.nPedido = nPedido;
+ }
+
+ public BigInteger getDFactura() {
+ return dFactura;
+ }
+
+ public void setDFactura(BigInteger dFactura) {
+ this.dFactura = dFactura;
+ }
+
+ public String getDVencimiento() {
+ return dVencimiento;
+ }
+
+ public void setDVencimiento(String dVencimiento) {
+ this.dVencimiento = dVencimiento;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 0;
+ hash += ( prcontraPK != null ? prcontraPK.hashCode() : 0 );
+ return hash;
+ }
+
+ @Override
+ public boolean equals(Object object) {
+ if ( !( object instanceof Prcontra ) ) {
+ return false;
+ }
+ Prcontra other = ( Prcontra ) object;
+ if ( this.prcontraPK != other.prcontraPK
+ && ( this.prcontraPK == null || !this.prcontraPK
+ .equals( other.prcontraPK ) ) ) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return "org.kyrian.entity.muvale.Prcontra[prcontraPK=" + prcontraPK
+ + "]";
+ }
+ //START-ENTITY-MOD
+
+ public String getTextoMpago() {
+ return textoMpago;
+ }
+
+ public void setTextoMpago(String textoMpago) {
+ this.textoMpago = textoMpago;
+ }
+
+ public Integer getTotalAfiliados() {
+ return totalAfiliados;
+ }
+
+ public void setTotalAfiliados(Integer totalAfiliados) {
+ this.totalAfiliados = totalAfiliados;
+ }
+
+ public String getModo() {
+ return modo;
+ }
+
+ public void setModo(String modo) {
+ this.modo = modo;
+ }
+
+ public Integer getImpagado() {
+ return impagado;
+ }
+
+ public void setImpagado(Integer impagado) {
+ this.impagado = impagado;
+ }
+
+ public Long getNumReconRealizados() {
+ return numReconRealizados;
+ }
+
+ public void setNumReconRealizados(Long numReconRealizados) {
+ this.numReconRealizados = numReconRealizados;
+ }
+
+ public Long getNumReconPrevistos() {
+ return numReconPrevistos;
+ }
+
+ public void setNumReconPrevistos(Long numReconPrevistos) {
+ this.numReconPrevistos = numReconPrevistos;
+ }
+
+ public BigInteger getConNrmRh() {
+ return conNrmRh;
+ }
+
+ public BigInteger getConNrmRt() {
+ return conNrmRt;
+ }
+
+ public void setConNrmRh(BigInteger conNrmRh) {
+ this.conNrmRh = conNrmRh;
+ }
+
+ public void setConNrmRt(BigInteger conNrmRt) {
+ this.conNrmRt = conNrmRt;
+ }
+
+ public Float getConPrecioRmExceso() {
+ return conPrecioRmExceso;
+ }
+
+ public BigInteger getConNtraDocRh() {
+ return conNtraDocRh;
+ }
+
+ public Float getConImpDocRhigienico() {
+ return conImpDocRhigienico;
+ }
+
+ public Float getConImprmRhigienico() {
+ return conImprmRhigienico;
+ }
+
+ public BigInteger getConNtraDocRt() {
+ return conNtraDocRt;
+ }
+
+ public Float getConImpdocRTipologias() {
+ return conImpdocRTipologias;
+ }
+
+ public Float getConImprmRtipologias() {
+ return conImprmRtipologias;
+ }
+
+ public Float getConImpUmovil() {
+ return conImpUmovil;
+ }
+
+ public Float getConPrecioSme() {
+ return conPrecioSme;
+ }
+
+ public void setConPrecioRmExceso(Float conPrecioRmExceso) {
+ this.conPrecioRmExceso = conPrecioRmExceso;
+ }
+
+ public void setConNtraDocRh(BigInteger conNtraDocRh) {
+ this.conNtraDocRh = conNtraDocRh;
+ }
+
+ public void setConImpDocRhigienico(Float conImpDocRhigienico) {
+ this.conImpDocRhigienico = conImpDocRhigienico;
+ }
+
+ public void setConImprmRhigienico(Float conImprmRhigienico) {
+ this.conImprmRhigienico = conImprmRhigienico;
+ }
+
+ public void setConNtraDocRt(BigInteger conNtraDocRt) {
+ this.conNtraDocRt = conNtraDocRt;
+ }
+
+ public void setConImpdocRTipologias(Float conImpdocRTipologias) {
+ this.conImpdocRTipologias = conImpdocRTipologias;
+ }
+
+ public void setConImprmRtipologias(Float conImprmRtipologias) {
+ this.conImprmRtipologias = conImprmRtipologias;
+ }
+
+ public void setConImpUmovil(Float conImpUmovil) {
+ this.conImpUmovil = conImpUmovil;
+ }
+
+ public void setConPrecioSme(Float conPrecioSme) {
+ this.conPrecioSme = conPrecioSme;
+ }
+
+ public BigInteger getDoc() {
+ return doc;
+ }
+
+ public String getNif() {
+ return nif;
+ }
+
+ public void setDoc(BigInteger doc) {
+ this.doc = doc;
+ }
+
+ public void setNif(String nif) {
+ this.nif = nif;
+ }
+}
+
+
Added: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/PrcontraPK.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/PrcontraPK.java (rev 0)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/PrcontraPK.java 2010-02-23 14:55:16 UTC (rev 18859)
@@ -0,0 +1,104 @@
+// $Id:$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.ejb.test.metadata;
+
+import java.io.Serializable;
+import java.math.BigInteger;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Hardy Ferentschik
+ */
+@Embeddable
+public class PrcontraPK implements Serializable {
+ private static final long serialVersionUID = 7441961985141369232L;
+ @Column(name = "NUMERO", nullable = false)
+ private BigInteger numero;
+ @Column(name = "RENOV", nullable = false)
+ private BigInteger renov;
+ @Column(name = "TIPO", nullable = false)
+ private BigInteger tipo;
+
+ public PrcontraPK() {
+ }
+
+ public PrcontraPK(BigInteger numero, BigInteger renov, BigInteger tipo) {
+ this.numero = numero;
+ this.renov = renov;
+ this.tipo = tipo;
+ }
+
+ public BigInteger getNumero() {
+ return numero;
+ }
+
+ public void setNumero(BigInteger numero) {
+ this.numero = numero;
+ }
+
+ public BigInteger getRenov() {
+ return renov;
+ }
+
+ public void setRenov(BigInteger renov) {
+ this.renov = renov;
+ }
+
+ public BigInteger getTipo() {
+ return tipo;
+ }
+
+ public void setTipo(BigInteger tipo) {
+ this.tipo = tipo;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 0;
+ hash += ( numero != null ? numero.hashCode() : 0 );
+ hash += ( renov != null ? renov.hashCode() : 0 );
+ hash += ( tipo != null ? tipo.hashCode() : 0 );
+ return hash;
+ }
+
+ @Override
+ public boolean equals(Object object) {
+ if ( !( object instanceof PrcontraPK ) ) {
+ return false;
+ }
+ PrcontraPK other = ( PrcontraPK ) object;
+ if ( this.numero != other.numero && ( this.numero == null || !this.numero.equals( other.numero ) ) ) {
+ return false;
+ }
+ if ( this.renov != other.renov && ( this.renov == null || !this.renov.equals( other.renov ) ) ) {
+ return false;
+ }
+ if ( this.tipo != other.tipo && ( this.tipo == null || !this.tipo.equals( other.tipo ) ) ) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return "org.kyrian.entity.muvale.PrcontraPK[numero=" + numero + ", renov=" + renov + ", tipo=" + tipo + "]";
+ }
+}
+
+
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/StaticMetadataTest.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/StaticMetadataTest.java 2010-02-23 12:57:17 UTC (rev 18858)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/StaticMetadataTest.java 2010-02-23 14:55:16 UTC (rev 18859)
@@ -37,12 +37,16 @@
*/
public class StaticMetadataTest extends TestCase {
+ public void testEmbeddedId() throws Exception {
+ assertNotNull( Prcontra_.prcontraPK );
+ }
+
public void testInjections() throws Exception {
// Address (embeddable)
assertNotNull( Address_.address1 );
assertNotNull( Address_.address2 );
assertNotNull( Address_.city );
- final EmbeddableType<Address> addressType = (EmbeddableType<Address>) House_.address.getType();
+ final EmbeddableType<Address> addressType = ( EmbeddableType<Address> ) House_.address.getType();
assertEquals( addressType.getDeclaredSingularAttribute( "address1" ), Address_.address1 );
assertEquals( addressType.getDeclaredSingularAttribute( "address2" ), Address_.address2 );
assertTrue( Address_.address1.isOptional() );
@@ -126,7 +130,7 @@
@Override
public Class[] getAnnotatedClasses() {
- return new Class[]{
+ return new Class[] {
Fridge.class,
FoodItem.class,
Person.class,
@@ -136,8 +140,9 @@
Cattish.class,
Feline.class,
Garden.class,
- Flower.class
+ Flower.class,
+ Prcontra.class,
+ PrcontraPK.class
};
}
-
}
\ No newline at end of file
14 years, 12 months
Hibernate SVN: r18858 - in core/trunk: entitymanager and 10 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-02-23 07:57:17 -0500 (Tue, 23 Feb 2010)
New Revision: 18858
Added:
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/PackagedEntityManagerTest.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/PackagingTestCase.java
Removed:
core/trunk/entitymanager/src/test/bundles/externaljar/META-INF/MANIFEST.MF
core/trunk/entitymanager/src/test/bundles/war/WEB-INF/
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/PackagedEntityManagerTest.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/package-info.java
Modified:
core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/reflection/XMLContext.java
core/trunk/entitymanager/build.xml
core/trunk/entitymanager/pom.xml
core/trunk/entitymanager/src/test/bundles/explicitpar/META-INF/persistence.xml
core/trunk/entitymanager/src/test/bundles/explodedpar/META-INF/persistence.xml
core/trunk/entitymanager/src/test/bundles/explodedpar/org/hibernate/ejb/test/pack/explodedpar/Elephant.hbm.xml
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/TestCase.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/TestCase.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ops/PersistTest.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/JarVisitorTest.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/NativeScannerTest.java
core/trunk/testing/src/main/java/org/hibernate/test/annotations/HibernateTestCase.java
Log:
HHH-4942 Refactored JarVistitorTest and PackagedEntityManagerTest to use Shrinkwrap to build the packages needed for the tests. This removed the need for some custom antrun plugin stuff. Also created a baseclass for the packaged tests.
HHH-4845 Refactored PersistTest to extend from the main em base test case. This allows the em test to run in forkMode 'once'
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/reflection/XMLContext.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/reflection/XMLContext.java 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/reflection/XMLContext.java 2010-02-23 12:57:17 UTC (rev 18858)
@@ -1,10 +1,11 @@
+// $Id:$
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
- * distributed under license by Red Hat Middleware LLC.
+ * distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@@ -183,7 +184,7 @@
classOverriding.put( listenerClassName, listener );
}
}
- log.debug( "Adding XML overriding information for listener: {}", listeners );
+ log.debug( "Adding XML overriding information for listener: {}", localAddedClasses );
addedClasses.addAll( localAddedClasses );
return localAddedClasses;
}
Modified: core/trunk/entitymanager/build.xml
===================================================================
--- core/trunk/entitymanager/build.xml 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/entitymanager/build.xml 2010-02-23 12:57:17 UTC (rev 18858)
@@ -26,97 +26,4 @@
</uptodate>
</target>
- <target name="packjar">
- <property name="extension" value="jar"/>
- <property name="packagename" value="${jarname}"/>
- <property name="headerdirectory" value="."/>
- <mkdir dir="${package.dir}"/>
- <mkdir dir="${package.tmp.dir}/${headerdirectory}"/>
- <copy todir="${package.tmp.dir}/${headerdirectory}">
- <fileset dir="${classes.dir}">
- <include name="**/test/pack/${packagename}/**.*"/>
- </fileset>
- </copy>
- <jar destfile="${package.dir}/${jarname}.${extension}">
- <fileset dir="${package.tmp.dir}">
- <include name="**/*.*"/>
- </fileset>
- <fileset dir="${testresources.dir}/${jarname}">
- <include name="**/*.*"/>
- </fileset>
- </jar>
- <delete dir="${package.tmp.dir}"/>
- </target>
-
- <target name="packexploded">
- <property name="extension" value="jar"/>
- <mkdir dir="${package.dir}/${jarname}.${extension}"/>
- <copy todir="${package.dir}/${jarname}.${extension}">
- <fileset dir="${classes.dir}">
- <include name="**/test/pack/${jarname}/**.*"/>
- </fileset>
- <fileset dir="${testresources.dir}/${jarname}">
- <include name="**/*.*"/>
- </fileset>
- </copy>
- </target>
-
- <target name="package" description="Prepare all needed jars and pars">
- <antcall target="packjar" inheritall="true">
- <param name="extension" value="par"/>
- <param name="jarname" value="defaultpar"/>
- </antcall>
- <antcall target="packjar" inheritall="true">
- <param name="extension" value="par"/>
- <param name="jarname" value="defaultpar_1_0"/>
- </antcall>
- <antcall target="packjar" inheritall="true">
- <param name="extension" value="par"/>
- <param name="jarname" value="space par"/>
- <param name="packagename" value="spacepar"/>
- </antcall>
- <antcall target="packjar" inheritall="true">
- <param name="extension" value="par"/>
- <param name="jarname" value="explicitpar"/>
- </antcall>
- <antcall target="packjar" inheritall="true">
- <param name="extension" value="par"/>
- <param name="jarname" value="excludehbmpar"/>
- </antcall>
- <antcall target="packjar" inheritall="true">
- <param name="extension" value="jar"/>
- <param name="jarname" value="externaljar"/>
- </antcall>
- <antcall target="packjar" inheritall="true">
- <param name="extension" value="par"/>
- <param name="jarname" value="cfgxmlpar"/>
- </antcall>
- <antcall target="packjar" inheritall="true">
- <param name="extension" value="jar"/>
- <param name="jarname" value="overridenpar"/>
- </antcall>
-
- <!-- nested jar -->
- <jar destfile="${package.dir}/nestedjar.ear">
- <fileset dir="${package.dir}">
- <include name="defaultpar.par"/>
- </fileset>
- </jar>
- <copy todir="${package.dir}/nesteddir.ear">
- <fileset dir="${package.dir}">
- <include name="defaultpar.par"/>
- </fileset>
- </copy>
-
- <antcall target="packjar" inheritall="true">
- <param name="extension" value="war"/>
- <param name="jarname" value="war"/>
- <param name="headerdirectory" value="WEB-INF/classes"/>
- </antcall>
-
- <antcall target="packexploded" inheritall="true">
- <param name="extension" value="par"/>
- <param name="jarname" value="explodedpar"/>
- </antcall>
- </target>
</project>
Modified: core/trunk/entitymanager/pom.xml
===================================================================
--- core/trunk/entitymanager/pom.xml 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/entitymanager/pom.xml 2010-02-23 12:57:17 UTC (rev 18858)
@@ -1,5 +1,7 @@
<?xml version="1.0"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
@@ -57,6 +59,18 @@
<scope>test</scope>
</dependency>
<dependency>
+ <groupId>org.jboss.shrinkwrap</groupId>
+ <artifactId>shrinkwrap-api</artifactId>
+ <version>1.0.0-alpha-6</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.shrinkwrap</groupId>
+ <artifactId>shrinkwrap-impl-base</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<!--
Only really needed for the antrun plugin defined below (which in turn is only really needed
to work around a missing feature on the compile plugin; lovely no?). However I have not
@@ -134,24 +148,6 @@
<goal>run</goal>
</goals>
</execution>
- <execution>
- <id>package-tests</id>
- <phase>process-test-classes</phase>
- <configuration>
- <tasks>
- <property name="package.dir" value="${basedir}/target/test-packages"/>
- <property name="package.tmp.dir" value="${basedir}/target/tmp"/>
- <property name="classes.dir" value="${project.build.directory}/test-classes"/>
- <property name="testresources.dir" value="${basedir}/target/bundles"/>
- <ant antfile="${basedir}/build.xml">
- <target name="package"/>
- </ant>
- </tasks>
- </configuration>
- <goals>
- <goal>run</goal>
- </goals>
- </execution>
</executions>
</plugin>
<plugin>
@@ -163,39 +159,12 @@
</configuration>
</plugin>
<plugin>
- <groupId>org.jboss.maven.plugins</groupId>
- <artifactId>maven-test-ext-plugin</artifactId>
- </plugin>
- <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
- <forkMode>pertest</forkMode>
- <additionalClasspathElements>
- <additionalClasspathElement>${basedir}/target/test-packages/cfgxmlpar.par
- </additionalClasspathElement>
- <additionalClasspathElement>${basedir}/target/test-packages/defaultpar.par
- </additionalClasspathElement>
- <additionalClasspathElement>${basedir}/target/test-packages/defaultpar_1_0.par
- </additionalClasspathElement>
- <additionalClasspathElement>${basedir}/target/test-packages/excludehbmpar.par
- </additionalClasspathElement>
- <additionalClasspathElement>${basedir}/target/test-packages/explicitpar.par
- </additionalClasspathElement>
- <additionalClasspathElement>${basedir}/target/test-packages/explodedpar.par
- </additionalClasspathElement>
- <additionalClasspathElement>${basedir}/target/test-packages/externaljar.jar
- </additionalClasspathElement>
- <additionalClasspathElement>${basedir}/target/test-packages/nesteddir.ear
- </additionalClasspathElement>
- <additionalClasspathElement>${basedir}/target/test-packages/nestedjar.ear
- </additionalClasspathElement>
- <additionalClasspathElement>${basedir}/target/test-packages/overridenpar.jar
- </additionalClasspathElement>
- <additionalClasspathElement>${basedir}/target/test-packages/space par.par
- </additionalClasspathElement>
- <additionalClasspathElement>${basedir}/target/test-packages/war.war</additionalClasspathElement>
- </additionalClasspathElements>
+ <excludes>
+ <exclude>**/*TestCase.java</exclude>
+ </excludes>
</configuration>
</plugin>
</plugins>
Modified: core/trunk/entitymanager/src/test/bundles/explicitpar/META-INF/persistence.xml
===================================================================
--- core/trunk/entitymanager/src/test/bundles/explicitpar/META-INF/persistence.xml 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/entitymanager/src/test/bundles/explicitpar/META-INF/persistence.xml 2010-02-23 12:57:17 UTC (rev 18858)
@@ -4,12 +4,11 @@
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">
- <jar-file>./target/test-packages/externaljar.jar</jar-file>
+ <jar-file>${basedir}/target/externaljar.jar</jar-file>
<class>org.hibernate.ejb.test.Cat</class>
<class>org.hibernate.ejb.test.Kitten</class>
<class>org.hibernate.ejb.test.Distributor</class>
<class>org.hibernate.ejb.test.Item</class>
- <class>org.hibernate.ejb.test</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="${db.dialect}"/>
Modified: core/trunk/entitymanager/src/test/bundles/explodedpar/META-INF/persistence.xml
===================================================================
--- core/trunk/entitymanager/src/test/bundles/explodedpar/META-INF/persistence.xml 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/entitymanager/src/test/bundles/explodedpar/META-INF/persistence.xml 2010-02-23 12:57:17 UTC (rev 18858)
@@ -5,7 +5,6 @@
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="explodedpar" transaction-type="RESOURCE_LOCAL">
-
<properties>
<property name="hibernate.dialect" value="${db.dialect}"/>
<property name="hibernate.connection.driver_class" value="${jdbc.driver}"/>
Modified: core/trunk/entitymanager/src/test/bundles/explodedpar/org/hibernate/ejb/test/pack/explodedpar/Elephant.hbm.xml
===================================================================
--- core/trunk/entitymanager/src/test/bundles/explodedpar/org/hibernate/ejb/test/pack/explodedpar/Elephant.hbm.xml 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/entitymanager/src/test/bundles/explodedpar/org/hibernate/ejb/test/pack/explodedpar/Elephant.hbm.xml 2010-02-23 12:57:17 UTC (rev 18858)
@@ -3,18 +3,11 @@
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
-<hibernate-mapping
- package="org.hibernate.ejb.test.pack.explodedpar"
- >
-
-
+<hibernate-mapping package="org.hibernate.ejb.test.pack.explodedpar">
<class name="Elephant">
-
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
-
</class>
-
</hibernate-mapping>
Deleted: core/trunk/entitymanager/src/test/bundles/externaljar/META-INF/MANIFEST.MF
===================================================================
--- core/trunk/entitymanager/src/test/bundles/externaljar/META-INF/MANIFEST.MF 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/entitymanager/src/test/bundles/externaljar/META-INF/MANIFEST.MF 2010-02-23 12:57:17 UTC (rev 18858)
@@ -1,4 +0,0 @@
-Manifest-Version: 1.0
-Ant-Version: Apache Ant 1.6.3
-Created-By: 1.5.0_03-b07 (Sun Microsystems Inc.)
-
Deleted: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/PackagedEntityManagerTest.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/PackagedEntityManagerTest.java 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/PackagedEntityManagerTest.java 2010-02-23 12:57:17 UTC (rev 18858)
@@ -1,455 +0,0 @@
-/*
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
- * indicated by the @author tags or express copyright attribution
- * statements applied by the authors. All third-party contributions are
- * distributed under license by Red Hat Inc.
- *
- * This copyrighted material is made available to anyone wishing to use, modify,
- * copy, or redistribute it subject to the terms and conditions of the GNU
- * Lesser General Public License, as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
- * for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this distribution; if not, write to:
- * Free Software Foundation, Inc.
- * 51 Franklin Street, Fifth Floor
- * Boston, MA 02110-1301 USA
- */
-package org.hibernate.ejb.test;
-
-import java.io.File;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Properties;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.Persistence;
-import javax.persistence.PersistenceException;
-
-import org.hibernate.ejb.AvailableSettings;
-import org.hibernate.ejb.HibernateEntityManagerFactory;
-import org.hibernate.ejb.test.pack.cfgxmlpar.Morito;
-import org.hibernate.ejb.test.pack.defaultpar.ApplicationServer;
-import org.hibernate.ejb.test.pack.defaultpar.IncrementListener;
-import org.hibernate.ejb.test.pack.defaultpar.Lighter;
-import org.hibernate.ejb.test.pack.defaultpar.Money;
-import org.hibernate.ejb.test.pack.defaultpar.Mouse;
-import org.hibernate.ejb.test.pack.defaultpar.OtherIncrementListener;
-import org.hibernate.ejb.test.pack.defaultpar.Version;
-import org.hibernate.ejb.test.pack.defaultpar_1_0.ApplicationServer1;
-import org.hibernate.ejb.test.pack.defaultpar_1_0.Lighter1;
-import org.hibernate.ejb.test.pack.defaultpar_1_0.Mouse1;
-import org.hibernate.ejb.test.pack.defaultpar_1_0.Version1;
-import org.hibernate.ejb.test.pack.excludehbmpar.Caipirinha;
-import org.hibernate.ejb.test.pack.explodedpar.Carpet;
-import org.hibernate.ejb.test.pack.explodedpar.Elephant;
-import org.hibernate.ejb.test.pack.externaljar.Scooter;
-import org.hibernate.ejb.test.pack.spacepar.Bug;
-import org.hibernate.ejb.test.pack.various.Airplane;
-import org.hibernate.ejb.test.pack.various.Seat;
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.event.EventListeners;
-import org.hibernate.stat.Statistics;
-import org.hibernate.util.ConfigHelper;
-
-/**
- * @author Gavin King
- */
-@SuppressWarnings("unchecked")
-public class PackagedEntityManagerTest extends junit.framework.TestCase {
- private static ClassLoader originalClassLoader;
-
- @Override
- protected void setUp() throws Exception {
- originalClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader( buildCustomTCCL( originalClassLoader ) );
- super.setUp();
- }
-
- private ClassLoader buildCustomTCCL(ClassLoader parentClassLoader) throws MalformedURLException {
- // get a URL reference to something we now is part of the classpath (us)
- URL myUrl = parentClassLoader.getResource(
- PackagedEntityManagerTest.class.getName().replace( '.', '/' ) + ".class"
- );
- File myPath = new File( myUrl.getFile() );
- // navigate back to '/target'
- File targetDir = myPath
- .getParentFile() // target/classes/org/hibernate/ejb/test
- .getParentFile() // target/classes/org/hibernate/ejb
- .getParentFile() // target/classes/org/hibernate
- .getParentFile() // target/classes/org
- .getParentFile() // target/classes/
- .getParentFile(); // target
- File testPackagesDir = new File( targetDir, "test-packages" );
- ArrayList<URL> urls = new ArrayList<URL>();
- for ( File testPackage : testPackagesDir.listFiles() ) {
- urls.add( testPackage.toURL() );
- }
- return new URLClassLoader( urls.toArray( new URL[urls.size()] ), parentClassLoader );
- }
-
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
- Thread.currentThread().setContextClassLoader( originalClassLoader );
- }
-
- public void testDefaultPar() throws Exception {
- EntityManagerFactory emf = Persistence.createEntityManagerFactory( "defaultpar", new HashMap() );
- EntityManager em = emf.createEntityManager();
- ApplicationServer as = new ApplicationServer();
- as.setName( "JBoss AS" );
- Version v = new Version();
- v.setMajor( 4 );
- v.setMinor( 0 );
- v.setMicro( 3 );
- as.setVersion( v );
- Mouse mouse = new Mouse();
- mouse.setName( "mickey" );
- em.getTransaction().begin();
- em.persist( as );
- em.persist( mouse );
- assertEquals( 1, em.createNamedQuery( "allMouse" ).getResultList().size() );
- Lighter lighter = new Lighter();
- lighter.name = "main";
- lighter.power = " 250 W";
- em.persist( lighter );
- em.flush();
- em.remove( lighter );
- em.remove( mouse );
- assertNotNull( as.getId() );
- em.remove( as );
- em.getTransaction().commit();
- em.close();
- emf.close();
- }
-
- public void testDefaultParForPersistence_1_0() throws Exception {
- EntityManagerFactory emf = Persistence.createEntityManagerFactory( "defaultpar_1_0", new HashMap() );
- EntityManager em = emf.createEntityManager();
- ApplicationServer1 as = new ApplicationServer1();
- as.setName( "JBoss AS" );
- Version1 v = new Version1();
- v.setMajor( 4 );
- v.setMinor( 0 );
- v.setMicro( 3 );
- as.setVersion( v );
- Mouse1 mouse = new Mouse1();
- mouse.setName( "mickey" );
- em.getTransaction().begin();
- em.persist( as );
- em.persist( mouse );
- assertEquals( 1, em.createNamedQuery( "allMouse_1_0" ).getResultList().size() );
- Lighter1 lighter = new Lighter1();
- lighter.name = "main";
- lighter.power = " 250 W";
- em.persist( lighter );
- em.flush();
- em.remove( lighter );
- em.remove( mouse );
- assertNotNull( as.getId() );
- em.remove( as );
- em.getTransaction().commit();
- em.close();
- emf.close();
- }
-
- public void testListenersDefaultPar() throws Exception {
- IncrementListener.reset();
- OtherIncrementListener.reset();
- EntityManagerFactory emf = Persistence.createEntityManagerFactory( "defaultpar", new HashMap() );
- EntityManager em = emf.createEntityManager();
- em.getTransaction().begin();
- ApplicationServer as = new ApplicationServer();
- as.setName( "JBoss AS" );
- Version v = new Version();
- v.setMajor( 4 );
- v.setMinor( 0 );
- v.setMicro( 3 );
- as.setVersion( v );
- em.persist( as );
- em.flush();
- assertEquals( "Failure in default listeners", 1, IncrementListener.getIncrement() );
- assertEquals( "Failuer in XML overriden listeners", 1, OtherIncrementListener.getIncrement() );
-
- Mouse mouse = new Mouse();
- mouse.setName( "mickey" );
- em.persist( mouse );
- em.flush();
- assertEquals( "Failure in @ExcludeDefaultListeners", 1, IncrementListener.getIncrement() );
- assertEquals( 1, OtherIncrementListener.getIncrement() );
-
- Money money = new Money();
- em.persist( money );
- em.flush();
- assertEquals( "Failure in @ExcludeDefaultListeners", 2, IncrementListener.getIncrement() );
- assertEquals( 1, OtherIncrementListener.getIncrement() );
-
- em.getTransaction().rollback();
- em.close();
- emf.close();
- }
-
- public void testExplodedPar() throws Exception {
- EntityManagerFactory emf = Persistence.createEntityManagerFactory( "explodedpar", new HashMap() );
- EntityManager em = emf.createEntityManager();
- org.hibernate.ejb.test.pack.explodedpar.Carpet carpet = new Carpet();
- Elephant el = new Elephant();
- el.setName( "Dumbo" );
- carpet.setCountry( "Turkey" );
- em.getTransaction().begin();
- em.persist( carpet );
- em.persist( el );
- assertEquals( 1, em.createNamedQuery( "allCarpet" ).getResultList().size() );
- assertNotNull( carpet.getId() );
- em.remove( carpet );
- em.getTransaction().commit();
- em.close();
- emf.close();
- }
-
- public void testExcludeHbmPar() throws Exception {
- EntityManagerFactory emf = null;
- try {
- emf = Persistence.createEntityManagerFactory( "excludehbmpar", new HashMap() );
- }
- catch ( PersistenceException e ) {
- Throwable nested = e.getCause();
- if ( nested == null ) {
- throw e;
- }
- nested = nested.getCause();
- if ( nested == null ) {
- throw e;
- }
- if ( !( nested instanceof ClassNotFoundException ) ) {
- throw e;
- }
- fail( "Try to process hbm file: " + e.getMessage() );
- }
- EntityManager em = emf.createEntityManager();
- Caipirinha s = new Caipirinha( "Strong" );
- em.getTransaction().begin();
- em.persist( s );
- em.getTransaction().commit();
-
- em.getTransaction().begin();
- s = em.find( Caipirinha.class, s.getId() );
- em.remove( s );
- em.getTransaction().commit();
- em.close();
- emf.close();
- }
-
- public void testCfgXmlPar() throws Exception {
- EntityManagerFactory emf = Persistence.createEntityManagerFactory( "cfgxmlpar", new HashMap() );
- EntityManager em = emf.createEntityManager();
- Item i = new Item();
- i.setDescr( "Blah" );
- i.setName( "factory" );
- Morito m = new Morito();
- m.setPower( "SuperStrong" );
- em.getTransaction().begin();
- em.persist( i );
- em.persist( m );
- em.getTransaction().commit();
-
- em.getTransaction().begin();
- i = em.find( Item.class, i.getName() );
- em.remove( i );
- em.remove( em.find( Morito.class, m.getId() ) );
- em.getTransaction().commit();
- em.close();
- emf.close();
- }
-
- public void testSpacePar() throws Exception {
- EntityManagerFactory emf = Persistence.createEntityManagerFactory( "space par", new HashMap() );
- EntityManager em = emf.createEntityManager();
- Bug bug = new Bug();
- bug.setSubject( "Spaces in directory name don't play well on Windows" );
- em.getTransaction().begin();
- em.persist( bug );
- em.flush();
- em.remove( bug );
- assertNotNull( bug.getId() );
- em.getTransaction().rollback();
- em.close();
- emf.close();
- }
-
- public void testOverridenPar() throws Exception {
- HashMap properties = new HashMap();
- properties.put( AvailableSettings.JTA_DATASOURCE, null );
- Properties p = new Properties();
- p.load( ConfigHelper.getResourceAsStream( "/overridenpar.properties" ) );
- properties.putAll( p );
- EntityManagerFactory emf = Persistence.createEntityManagerFactory( "overridenpar", properties );
- EntityManager em = emf.createEntityManager();
- org.hibernate.ejb.test.pack.overridenpar.Bug bug = new org.hibernate.ejb.test.pack.overridenpar.Bug();
- bug.setSubject( "Allow DS overriding" );
- em.getTransaction().begin();
- em.persist( bug );
- em.flush();
- em.remove( bug );
- assertNotNull( bug.getId() );
- em.getTransaction().rollback();
- em.close();
- emf.close();
- }
-
- public void testListeners() throws Exception {
- EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
- EntityManager em = emf.createEntityManager();
- EventListeners eventListeners = em.unwrap( SessionImplementor.class ).getListeners();
- assertEquals(
- "Explicit pre-insert event through hibernate.ejb.event.pre-insert does not work",
- eventListeners.getPreInsertEventListeners().length,
- eventListeners.getPreUpdateEventListeners().length + 1
- );
-
- em.close();
- emf.close();
- }
-
- public void testExtendedEntityManager() {
- EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
- EntityManager em = emf.createEntityManager();
- Item item = new Item( "Mouse", "Micro$oft mouse" );
- em.getTransaction().begin();
- em.persist( item );
- assertTrue( em.contains( item ) );
- em.getTransaction().commit();
-
- assertTrue( em.contains( item ) );
-
- em.getTransaction().begin();
- Item item1 = ( Item ) em.createQuery( "select i from Item i where descr like 'M%'" ).getSingleResult();
- assertNotNull( item1 );
- assertSame( item, item1 );
- item.setDescr( "Micro$oft wireless mouse" );
- assertTrue( em.contains( item ) );
- em.getTransaction().commit();
-
- assertTrue( em.contains( item ) );
-
- em.getTransaction().begin();
- item1 = em.find( Item.class, "Mouse" );
- assertSame( item, item1 );
- em.getTransaction().commit();
- assertTrue( em.contains( item ) );
-
- item1 = em.find( Item.class, "Mouse" );
- assertSame( item, item1 );
- assertTrue( em.contains( item ) );
-
- item1 = ( Item ) em.createQuery( "select i from Item i where descr like 'M%'" ).getSingleResult();
- assertNotNull( item1 );
- assertSame( item, item1 );
- assertTrue( em.contains( item ) );
-
- em.getTransaction().begin();
- assertTrue( em.contains( item ) );
- em.remove( item );
- em.remove( item ); //second remove should be a no-op
- em.getTransaction().commit();
-
- em.close();
- emf.close();
- }
-
- public void testConfiguration() throws Exception {
- EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
- Item item = new Item( "Mouse", "Micro$oft mouse" );
- Distributor res = new Distributor();
- res.setName( "Bruce" );
- item.setDistributors( new HashSet<Distributor>() );
- item.getDistributors().add( res );
- Statistics stats = ( ( HibernateEntityManagerFactory ) emf ).getSessionFactory().getStatistics();
- stats.clear();
- stats.setStatisticsEnabled( true );
-
- EntityManager em = emf.createEntityManager();
- em.getTransaction().begin();
-
- em.persist( res );
- em.persist( item );
- assertTrue( em.contains( item ) );
-
- em.getTransaction().commit();
- em.close();
-
- assertEquals( 1, stats.getSecondLevelCachePutCount() );
- assertEquals( 0, stats.getSecondLevelCacheHitCount() );
-
- em = emf.createEntityManager();
- em.getTransaction().begin();
- Item second = em.find( Item.class, item.getName() );
- assertEquals( 1, second.getDistributors().size() );
- assertEquals( 1, stats.getSecondLevelCacheHitCount() );
- em.getTransaction().commit();
- em.close();
-
- em = emf.createEntityManager();
- em.getTransaction().begin();
- second = em.find( Item.class, item.getName() );
- assertEquals( 1, second.getDistributors().size() );
- assertEquals( 3, stats.getSecondLevelCacheHitCount() );
- for ( Distributor distro : second.getDistributors() ) {
- em.remove( distro );
- }
- em.remove( second );
- em.getTransaction().commit();
- em.close();
-
- stats.clear();
- stats.setStatisticsEnabled( false );
- emf.close();
- }
-
- public void testExternalJar() throws Exception {
- EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
- EntityManager em = emf.createEntityManager();
- Scooter s = new Scooter();
- s.setModel( "Abadah" );
- s.setSpeed( 85l );
- em.getTransaction().begin();
- em.persist( s );
- em.getTransaction().commit();
- em.close();
- em = emf.createEntityManager();
- em.getTransaction().begin();
- s = em.find( Scooter.class, s.getModel() );
- assertEquals( new Long( 85 ), s.getSpeed() );
- em.remove( s );
- em.getTransaction().commit();
- em.close();
- emf.close();
- }
-
- public void testORMFileOnMainAndExplicitJars() throws Exception {
- EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
- EntityManager em = emf.createEntityManager();
- Seat seat = new Seat();
- seat.setNumber( "3B" );
- Airplane plane = new Airplane();
- plane.setSerialNumber( "75924418409052355" );
- em.getTransaction().begin();
- em.persist( seat );
- em.persist( plane );
- em.flush();
- em.getTransaction().rollback();
- em.close();
- emf.close();
- }
-}
\ No newline at end of file
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/TestCase.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/TestCase.java 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/TestCase.java 2010-02-23 12:57:17 UTC (rev 18858)
@@ -1,3 +1,4 @@
+// $Id:$
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
@@ -81,11 +82,16 @@
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
}
cfg.setProperty( AnnotationConfiguration.USE_NEW_ID_GENERATOR_MAPPINGS, "true" );
+
+ for ( String mappingFile : getMappings() ) {
+ cfg.addResource( mappingFile );
+ }
+
factory = ejbconfig.createEntityManagerFactory( getConfig() );
}
- private void cleanUnclosed(EntityManager em){
- if(em == null) {
+ private void cleanUnclosed(EntityManager em) {
+ if ( em == null ) {
return;
}
if ( em.getTransaction().isActive() ) {
@@ -99,10 +105,11 @@
log.warn( "The EntityManager is not closed. Closing it." );
}
}
- protected void handleUnclosedResources(){
+
+ protected void handleUnclosedResources() {
cleanUnclosed( this.em );
- for ( Iterator iter = isolatedEms.iterator(); iter.hasNext();) {
- cleanUnclosed( (EntityManager)iter.next() );
+ for ( Iterator iter = isolatedEms.iterator(); iter.hasNext(); ) {
+ cleanUnclosed( ( EntityManager ) iter.next() );
}
cfg = null;
@@ -122,7 +129,7 @@
}
protected EntityManager createIsolatedEntityManager() {
- EntityManager isolatedEm = factory.createEntityManager( );
+ EntityManager isolatedEm = factory.createEntityManager();
isolatedEms.add( isolatedEm );
return isolatedEm;
}
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/TestCase.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/TestCase.java 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/TestCase.java 2010-02-23 12:57:17 UTC (rev 18858)
@@ -1,3 +1,4 @@
+// $Id:$
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
@@ -61,8 +62,6 @@
return true;
}
- ;
-
private void buildConfiguration() {
configuration = new Ejb3Configuration();
configuration.addProperties( loadProperties() );
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ops/PersistTest.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ops/PersistTest.java 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ops/PersistTest.java 2010-02-23 12:57:17 UTC (rev 18858)
@@ -1,223 +1,235 @@
-//$Id$
+// $Id:$
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
package org.hibernate.ejb.test.ops;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Map;
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceException;
+import javax.persistence.RollbackException;
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import org.hibernate.PersistentObjectException;
-import org.hibernate.Session;
-import org.hibernate.Transaction;
-import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
-import org.hibernate.ejb.test.EJB3TestCase;
-import org.hibernate.exception.ConstraintViolationException;
+import org.hibernate.ejb.EntityManagerFactoryImpl;
+import org.hibernate.ejb.test.TestCase;
/**
* @author Gavin King
+ * @author Hardy Ferentschik
*/
-public class PersistTest extends EJB3TestCase {
+public class PersistTest extends TestCase {
- public PersistTest(String str) {
- super( str );
- }
-
public void testCreateTree() {
clearCounts();
-
- Session s = openSession();
- Transaction tx = s.beginTransaction();
+ EntityManager em = getOrCreateEntityManager();
+ em.getTransaction().begin();
Node root = new Node( "root" );
Node child = new Node( "child" );
root.addChild( child );
- s.persist( root );
- tx.commit();
- s.close();
+ em.persist( root );
+ em.getTransaction().commit();
+ em.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
- s = openSession();
- tx = s.beginTransaction();
- root = (Node) s.get( Node.class, "root" );
+ em = getOrCreateEntityManager();
+ em.getTransaction().begin();
+ root = ( Node ) em.find( Node.class, "root" );
Node child2 = new Node( "child2" );
root.addChild( child2 );
- tx.commit();
- s.close();
+ em.getTransaction().commit();
+ em.close();
assertInsertCount( 3 );
assertUpdateCount( 0 );
}
public void testCreateTreeWithGeneratedId() {
-
clearCounts();
- Session s = openSession();
- Transaction tx = s.beginTransaction();
+ EntityManager em = getOrCreateEntityManager();
+ em.getTransaction().begin();
NumberedNode root = new NumberedNode( "root" );
NumberedNode child = new NumberedNode( "child" );
root.addChild( child );
- s.persist( root );
- tx.commit();
- s.close();
+ em.persist( root );
+ em.getTransaction().commit();
+ em.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
- s = openSession();
- tx = s.beginTransaction();
- root = (NumberedNode) s.get( NumberedNode.class, new Long( root.getId() ) );
+ em = getOrCreateEntityManager();
+ em.getTransaction().begin();
+ root = ( NumberedNode ) em.find( NumberedNode.class, root.getId() );
NumberedNode child2 = new NumberedNode( "child2" );
root.addChild( child2 );
- tx.commit();
- s.close();
+ em.getTransaction().commit();
+ em.close();
assertInsertCount( 3 );
assertUpdateCount( 0 );
}
public void testCreateException() {
- Session s = openSession();
- Transaction tx = s.beginTransaction();
+ EntityManager em = getOrCreateEntityManager();
+ em.getTransaction().begin();
Node dupe = new Node( "dupe" );
- s.persist( dupe );
- s.persist( dupe );
- tx.commit();
- s.close();
+ em.persist( dupe );
+ em.persist( dupe );
+ em.getTransaction().commit();
+ em.close();
- s = openSession();
- tx = s.beginTransaction();
- s.persist( dupe );
+ em = getOrCreateEntityManager();
+ em.getTransaction().begin();
+ em.persist( dupe );
try {
- tx.commit();
+ em.getTransaction().commit();
fail( "Cannot persist() twice the same entity" );
}
- catch (ConstraintViolationException cve) {
+ catch ( Exception cve ) {
//verify that an exception is thrown!
}
- tx.rollback();
- s.close();
+ em.close();
Node nondupe = new Node( "nondupe" );
nondupe.addChild( dupe );
- s = openSession();
- tx = s.beginTransaction();
- s.persist( nondupe );
+ em = getOrCreateEntityManager();
+ em.getTransaction().begin();
+ em.persist( nondupe );
try {
- tx.commit();
+ em.getTransaction().commit();
assertFalse( true );
}
- catch (ConstraintViolationException cve) {
+ catch ( RollbackException e ) {
//verify that an exception is thrown!
}
- tx.rollback();
- s.close();
+ em.close();
}
public void testCreateExceptionWithGeneratedId() {
- Session s = openSession();
- Transaction tx = s.beginTransaction();
+ EntityManager em = getOrCreateEntityManager();
+ em.getTransaction().begin();
NumberedNode dupe = new NumberedNode( "dupe" );
- s.persist( dupe );
- s.persist( dupe );
- tx.commit();
- s.close();
+ em.persist( dupe );
+ em.persist( dupe );
+ em.getTransaction().commit();
+ em.close();
- s = openSession();
- tx = s.beginTransaction();
+ em = getOrCreateEntityManager();
+ em.getTransaction().begin();
try {
- s.persist( dupe );
+ em.persist( dupe );
fail();
}
- catch (PersistentObjectException poe) {
+ catch ( PersistenceException poe ) {
//verify that an exception is thrown!
}
- tx.rollback();
- s.close();
+ em.getTransaction().rollback();
+ em.close();
NumberedNode nondupe = new NumberedNode( "nondupe" );
nondupe.addChild( dupe );
- s = openSession();
- tx = s.beginTransaction();
+ em = getOrCreateEntityManager();
+ em.getTransaction().begin();
try {
- s.persist( nondupe );
+ em.persist( nondupe );
fail();
}
- catch (PersistentObjectException poe) {
+ catch ( PersistenceException poe ) {
//verify that an exception is thrown!
}
- tx.rollback();
- s.close();
+ em.getTransaction().rollback();
+ em.close();
}
public void testBasic() throws Exception {
- Session s;
- Transaction tx;
- s = openSession();
- tx = s.beginTransaction();
+
+ EntityManager em = getOrCreateEntityManager();
+ em.getTransaction().begin();
Employer er = new Employer();
Employee ee = new Employee();
- s.persist( ee );
- Collection erColl = new ArrayList();
- Collection eeColl = new ArrayList();
+ em.persist( ee );
+ Collection<Employee> erColl = new ArrayList<Employee>();
+ Collection<Employer> eeColl = new ArrayList<Employer>();
erColl.add( ee );
eeColl.add( er );
er.setEmployees( erColl );
ee.setEmployers( eeColl );
- tx.commit();
- s.close();
+ em.getTransaction().commit();
+ em.close();
- s = openSession();
- tx = s.beginTransaction();
- er = (Employer) s.load( Employer.class, er.getId() );
+ em = getOrCreateEntityManager();
+ em.getTransaction().begin();
+ er = ( Employer ) em.find( Employer.class, er.getId() );
assertNotNull( er );
assertNotNull( er.getEmployees() );
assertEquals( 1, er.getEmployees().size() );
- Employee eeFromDb = (Employee) er.getEmployees().iterator().next();
+ Employee eeFromDb = ( Employee ) er.getEmployees().iterator().next();
assertEquals( ee.getId(), eeFromDb.getId() );
- tx.commit();
- s.close();
+ em.getTransaction().commit();
+ em.close();
}
private void clearCounts() {
- getSessions().getStatistics().clear();
+ ( ( EntityManagerFactoryImpl ) factory ).getSessionFactory().getStatistics().clear();
}
private void assertInsertCount(int count) {
- int inserts = (int) getSessions().getStatistics().getEntityInsertCount();
+ int inserts = ( int ) ( ( EntityManagerFactoryImpl ) factory ).getSessionFactory()
+ .getStatistics()
+ .getEntityInsertCount();
assertEquals( count, inserts );
}
private void assertUpdateCount(int count) {
- int updates = (int) getSessions().getStatistics().getEntityUpdateCount();
+ int updates = ( int ) ( ( EntityManagerFactoryImpl ) factory ).getSessionFactory()
+ .getStatistics()
+ .getEntityUpdateCount();
assertEquals( count, updates );
}
- protected void configure(Configuration cfg) {
- super.configure( cfg );
- cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
- cfg.setProperty( Environment.STATEMENT_BATCH_SIZE, "0" );
+ protected void addConfigOptions(Map options) {
+ options.put( Environment.GENERATE_STATISTICS, "true" );
+ options.put( Environment.STATEMENT_BATCH_SIZE, "0" );
}
+ @Override
+ protected Class<?>[] getAnnotatedClasses() {
+ return new Class<?>[] { Node.class };
+ }
+
protected String[] getMappings() {
- return new String[]{
- "ops/Node.hbm.xml",
- "ops/Employer.hbm.xml"
+ return new String[] {
+ "org/hibernate/ejb/test/ops/Node.hbm.xml",
+ "org/hibernate/ejb/test/ops/Employer.hbm.xml"
};
}
-
- public static Test suite() {
- return new TestSuite( PersistTest.class );
- }
-
- public String getCacheConcurrencyStrategy() {
- return null;
- }
-
}
Deleted: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/package-info.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/package-info.java 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/package-info.java 2010-02-23 12:57:17 UTC (rev 18858)
@@ -1,4 +0,0 @@
-@NamedQuery(name = "countItems", query = "select count(i) from Item i") package org.hibernate.ejb.test;
-
-import org.hibernate.annotations.NamedQuery;
-
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/JarVisitorTest.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/JarVisitorTest.java 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/JarVisitorTest.java 2010-02-23 12:57:17 UTC (rev 18858)
@@ -1,3 +1,4 @@
+// $Id:$
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
@@ -28,13 +29,10 @@
import java.net.URL;
import java.net.URLConnection;
import java.util.Set;
-
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
-import junit.framework.TestCase;
-
import org.hibernate.ejb.packaging.ClassFilter;
import org.hibernate.ejb.packaging.Entry;
import org.hibernate.ejb.packaging.ExplodedJarVisitor;
@@ -48,39 +46,14 @@
import org.hibernate.ejb.packaging.PackageFilter;
import org.hibernate.ejb.test.pack.defaultpar.ApplicationServer;
import org.hibernate.ejb.test.pack.explodedpar.Carpet;
-import org.hibernate.junit.FailureExpected;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
/**
* @author Emmanuel Bernard
+ * @author Hardy Ferentschik
*/
@SuppressWarnings("unchecked")
-public class JarVisitorTest extends TestCase {
-
- private static final Logger log = LoggerFactory.getLogger(JarVisitorTest.class);
+public class JarVisitorTest extends PackagingTestCase {
- private static String jarFileBase;
-
- @Override
- protected void setUp() throws Exception {
- URL myUrl = JarVisitorTest.class.getClassLoader().getResource( JarVisitorTest.class.getName().replace( '.', '/' ) + ".class" );
- File myPath = new File( myUrl.getFile() );
- // navigate back to '/target'
- File targetDir = myPath
- .getParentFile() // target/classes/org/hibernate/ejb/test/packaging
- .getParentFile() // target/classes/org/hibernate/ejb/test
- .getParentFile() // target/classes/org/hibernate/ejb
- .getParentFile() // target/classes/org/hibernate
- .getParentFile() // target/classes/org
- .getParentFile() // target/classes
- .getParentFile(); // target
- jarFileBase = new File( targetDir, "test-packages" ).toURL().toExternalForm();
- super.setUp();
- }
-
-
public void testHttp() throws Exception {
URL url = JarVisitorFactory.getJarURLFromURLEntry(
new URL(
@@ -92,7 +65,7 @@
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
}
- catch (IOException ie) {
+ catch ( IOException ie ) {
//fail silently
return;
}
@@ -102,11 +75,12 @@
assertEquals( 0, visitor.getMatchingEntries()[2].size() );
}
- @FailureExpected( jiraKey = "")
public void testInputStreamZippedJar() throws Exception {
- String jarFileName = jarFileBase + "defaultpar.par";
+ File defaultPar = buildDefaultPar();
+ addPackageToClasspath( defaultPar );
+
Filter[] filters = getFilters();
- JarVisitor jarVisitor = new InputStreamZippedJarVisitor( new URL( jarFileName ), filters, "" );
+ JarVisitor jarVisitor = new InputStreamZippedJarVisitor( defaultPar.toURL(), filters, "" );
assertEquals( "defaultpar", jarVisitor.getUnqualifiedJarName() );
Set entries = jarVisitor.getMatchingEntries()[1];
assertEquals( 3, entries.size() );
@@ -114,16 +88,21 @@
assertTrue( entries.contains( entry ) );
entry = new Entry( org.hibernate.ejb.test.pack.defaultpar.Version.class.getName(), null );
assertTrue( entries.contains( entry ) );
- assertNull( ( (Entry) entries.iterator().next() ).getInputStream() );
+ assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() );
assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() );
- for (Entry localEntry : (Set<Entry>) jarVisitor.getMatchingEntries()[2] ) {
+ for ( Entry localEntry : ( Set<Entry> ) jarVisitor.getMatchingEntries()[2] ) {
assertNotNull( localEntry.getInputStream() );
localEntry.getInputStream().close();
}
}
public void testNestedJarProtocol() throws Exception {
- String jarFileName = jarFileBase + "/nestedjar.ear!/defaultpar.par";
+ File defaultPar = buildDefaultPar();
+ File nestedEar = buildNestedEar( defaultPar );
+ File nestedEarDir = buildNestedEarDir( defaultPar );
+ addPackageToClasspath( nestedEar );
+
+ String jarFileName = nestedEar.toURL().toExternalForm() + "!/defaultpar.par";
Filter[] filters = getFilters();
JarVisitor jarVisitor = new JarProtocolVisitor( new URL( jarFileName ), filters, "" );
//TODO should we fix the name here to reach defaultpar rather than nestedjar ??
@@ -134,14 +113,14 @@
assertTrue( entries.contains( entry ) );
entry = new Entry( org.hibernate.ejb.test.pack.defaultpar.Version.class.getName(), null );
assertTrue( entries.contains( entry ) );
- assertNull( ( (Entry) entries.iterator().next() ).getInputStream() );
+ assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() );
assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() );
- for (Entry localEntry : (Set<Entry>) jarVisitor.getMatchingEntries()[2] ) {
+ for ( Entry localEntry : ( Set<Entry> ) jarVisitor.getMatchingEntries()[2] ) {
assertNotNull( localEntry.getInputStream() );
localEntry.getInputStream().close();
}
- jarFileName = jarFileBase + "/nesteddir.ear!/defaultpar.par";
+ jarFileName = nestedEarDir.toURL().toExternalForm() + "!/defaultpar.par";
//JarVisitor jarVisitor = new ZippedJarVisitor( jarFileName, true, true );
filters = getFilters();
jarVisitor = new JarProtocolVisitor( new URL( jarFileName ), filters, "" );
@@ -153,16 +132,19 @@
assertTrue( entries.contains( entry ) );
entry = new Entry( org.hibernate.ejb.test.pack.defaultpar.Version.class.getName(), null );
assertTrue( entries.contains( entry ) );
- assertNull( ( (Entry) entries.iterator().next() ).getInputStream() );
+ assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() );
assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() );
- for (Entry localEntry : (Set<Entry>) jarVisitor.getMatchingEntries()[2] ) {
+ for ( Entry localEntry : ( Set<Entry> ) jarVisitor.getMatchingEntries()[2] ) {
assertNotNull( localEntry.getInputStream() );
localEntry.getInputStream().close();
}
}
public void testJarProtocol() throws Exception {
- String jarFileName = jarFileBase + "/war.war!/WEB-INF/classes";
+ File war = buildWar();
+ addPackageToClasspath( war );
+
+ String jarFileName = war.toURL().toExternalForm() + "!/WEB-INF/classes";
Filter[] filters = getFilters();
JarVisitor jarVisitor = new JarProtocolVisitor( new URL( jarFileName ), filters, "" );
assertEquals( "war", jarVisitor.getUnqualifiedJarName() );
@@ -172,18 +154,20 @@
assertTrue( entries.contains( entry ) );
entry = new Entry( org.hibernate.ejb.test.pack.war.Version.class.getName(), null );
assertTrue( entries.contains( entry ) );
- assertNull( ( (Entry) entries.iterator().next() ).getInputStream() );
+ assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() );
assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() );
- for (Entry localEntry : (Set<Entry>) jarVisitor.getMatchingEntries()[2] ) {
+ for ( Entry localEntry : ( Set<Entry> ) jarVisitor.getMatchingEntries()[2] ) {
assertNotNull( localEntry.getInputStream() );
localEntry.getInputStream().close();
}
}
public void testZippedJar() throws Exception {
- String jarFileName = jarFileBase + "/defaultpar.par";
+ File defaultPar = buildDefaultPar();
+ addPackageToClasspath( defaultPar );
+
Filter[] filters = getFilters();
- JarVisitor jarVisitor = new FileZippedJarVisitor( new URL( jarFileName ), filters, "" );
+ JarVisitor jarVisitor = new FileZippedJarVisitor( defaultPar.toURL(), filters, "" );
assertEquals( "defaultpar", jarVisitor.getUnqualifiedJarName() );
Set entries = jarVisitor.getMatchingEntries()[1];
assertEquals( 3, entries.size() );
@@ -191,19 +175,25 @@
assertTrue( entries.contains( entry ) );
entry = new Entry( org.hibernate.ejb.test.pack.defaultpar.Version.class.getName(), null );
assertTrue( entries.contains( entry ) );
- assertNull( ( (Entry) entries.iterator().next() ).getInputStream() );
+ assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() );
assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() );
- for (Entry localEntry : (Set<Entry>) jarVisitor.getMatchingEntries()[2] ) {
+ for ( Entry localEntry : ( Set<Entry> ) jarVisitor.getMatchingEntries()[2] ) {
assertNotNull( localEntry.getInputStream() );
localEntry.getInputStream().close();
}
}
-
public void testExplodedJar() throws Exception {
- String jarFileName = jarFileBase + "/explodedpar.par";
+ File explodedPar = buildExplodedPar();
+ addPackageToClasspath( explodedPar );
+
Filter[] filters = getFilters();
- JarVisitor jarVisitor = new ExplodedJarVisitor( jarFileName, filters );
+ String dirPath = explodedPar.toURL().toExternalForm();
+ // TODO - shouldn't ExplodedJarVisitor take care of a trailing slash?
+ if ( dirPath.endsWith( "/" ) ) {
+ dirPath = dirPath.substring( 0, dirPath.length() - 1 );
+ }
+ JarVisitor jarVisitor = new ExplodedJarVisitor( dirPath, filters );
assertEquals( "explodedpar", jarVisitor.getUnqualifiedJarName() );
Set[] entries = jarVisitor.getMatchingEntries();
assertEquals( 1, entries[1].size() );
@@ -212,7 +202,7 @@
Entry entry = new Entry( Carpet.class.getName(), null );
assertTrue( entries[1].contains( entry ) );
- for (Entry localEntry : (Set<Entry>) jarVisitor.getMatchingEntries()[2] ) {
+ for ( Entry localEntry : ( Set<Entry> ) jarVisitor.getMatchingEntries()[2] ) {
assertNotNull( localEntry.getInputStream() );
localEntry.getInputStream().close();
}
@@ -222,10 +212,9 @@
* EJB-230
*/
public void testDuplicateFilterExplodedJarExpected() throws Exception {
-
- log.warn("Skipping test! See jira issue EJB-230.");
-
-// String jarFileName = "./build/testresources/explodedpar.par";
+// File explodedPar = buildExplodedPar();
+// addPackageToClasspath( explodedPar );
+//
// Filter[] filters = getFilters();
// Filter[] dupeFilters = new Filter[filters.length * 2];
// int index = 0;
@@ -236,20 +225,25 @@
// for ( Filter filter : filters ) {
// dupeFilters[index++] = filter;
// }
-// JarVisitor jarVisitor = new ExplodedJarVisitor( jarFileName, dupeFilters );
+// String dirPath = explodedPar.toURL().toExternalForm();
+// // TODO - shouldn't ExplodedJarVisitor take care of a trailing slash?
+// if ( dirPath.endsWith( "/" ) ) {
+// dirPath = dirPath.substring( 0, dirPath.length() - 1 );
+// }
+// JarVisitor jarVisitor = new ExplodedJarVisitor( dirPath, dupeFilters );
// assertEquals( "explodedpar", jarVisitor.getUnqualifiedJarName() );
// Set[] entries = jarVisitor.getMatchingEntries();
// assertEquals( 1, entries[1].size() );
// assertEquals( 1, entries[0].size() );
// assertEquals( 1, entries[2].size() );
-// for ( Entry entry : (Set<Entry>) entries[2] ) {
+// for ( Entry entry : ( Set<Entry> ) entries[2] ) {
// InputStream is = entry.getInputStream();
// if ( is != null ) {
// assertTrue( 0 < is.available() );
// is.close();
// }
// }
-// for ( Entry entry : (Set<Entry>) entries[5] ) {
+// for ( Entry entry : ( Set<Entry> ) entries[5] ) {
// InputStream is = entry.getInputStream();
// if ( is != null ) {
// assertTrue( 0 < is.available() );
@@ -262,17 +256,18 @@
}
private Filter[] getFilters() {
- return new Filter[]{
+ return new Filter[] {
new PackageFilter( false, null ) {
public boolean accept(String javaElementName) {
return true;
}
},
new ClassFilter(
- false, new Class[]{
- Entity.class,
- MappedSuperclass.class,
- Embeddable.class}
+ false, new Class[] {
+ Entity.class,
+ MappedSuperclass.class,
+ Embeddable.class
+ }
) {
public boolean accept(String javaElementName) {
return true;
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/NativeScannerTest.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/NativeScannerTest.java 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/NativeScannerTest.java 2010-02-23 12:57:17 UTC (rev 18858)
@@ -1,15 +1,37 @@
+// $Id:$
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
package org.hibernate.ejb.test.packaging;
+import java.io.File;
import java.lang.annotation.Annotation;
-import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
-import junit.framework.TestCase;
-
import org.hibernate.ejb.packaging.NamedInputStream;
import org.hibernate.ejb.packaging.NativeScanner;
import org.hibernate.ejb.packaging.Scanner;
@@ -18,34 +40,33 @@
/**
* @author Emmanuel Bernard
+ * @author Hardy Ferentschik
*/
-public class NativeScannerTest extends TestCase {
- private static final String jarFileBase = "file:./target/test-packages";
+public class NativeScannerTest extends PackagingTestCase {
+ public void testNativeScanner() throws Exception {
+ File defaultPar = buildDefaultPar();
+ addPackageToClasspath( defaultPar );
- public void testNativeScanner() throws Exception {
- String jarFileName = jarFileBase + "/defaultpar.par";
Scanner scanner = new NativeScanner();
+ assertEquals( "defaultpar", scanner.getUnqualifiedJarName( defaultPar.toURL() ) );
- final URL jarUrl = new URL( jarFileName );
- assertEquals( "defaultpar", scanner.getUnqualifiedJarName( jarUrl ) );
-
- Set<Class<? extends Annotation>> annotationsToLookFor = new HashSet<Class<? extends Annotation>>(3);
+ Set<Class<? extends Annotation>> annotationsToLookFor = new HashSet<Class<? extends Annotation>>( 3 );
annotationsToLookFor.add( Entity.class );
annotationsToLookFor.add( MappedSuperclass.class );
annotationsToLookFor.add( Embeddable.class );
- final Set<Class<?>> classes = scanner.getClassesInJar( jarUrl, annotationsToLookFor );
-
+ final Set<Class<?>> classes = scanner.getClassesInJar( defaultPar.toURL(), annotationsToLookFor );
+
assertEquals( 3, classes.size() );
assertTrue( classes.contains( ApplicationServer.class ) );
assertTrue( classes.contains( org.hibernate.ejb.test.pack.defaultpar.Version.class ) );
- Set<String> filePatterns = new HashSet<String>(2);
- filePatterns.add("**/*.hbm.xml");
- filePatterns.add("META-INF/orm.xml");
- final Set<NamedInputStream> files = scanner.getFilesInJar( jarUrl, filePatterns );
+ Set<String> filePatterns = new HashSet<String>( 2 );
+ filePatterns.add( "**/*.hbm.xml" );
+ filePatterns.add( "META-INF/orm.xml" );
+ final Set<NamedInputStream> files = scanner.getFilesInJar( defaultPar.toURL(), filePatterns );
assertEquals( 2, files.size() );
- for (NamedInputStream file : files ) {
+ for ( NamedInputStream file : files ) {
assertNotNull( file.getStream() );
file.getStream().close();
}
Property changes on: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/NativeScannerTest.java
___________________________________________________________________
Name: svn:keywords
+ Id
Copied: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/PackagedEntityManagerTest.java (from rev 18837, core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/PackagedEntityManagerTest.java)
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/PackagedEntityManagerTest.java (rev 0)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/PackagedEntityManagerTest.java 2010-02-23 12:57:17 UTC (rev 18858)
@@ -0,0 +1,465 @@
+// $Id:$
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.ejb.test.packaging;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Properties;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import javax.persistence.PersistenceException;
+
+import org.hibernate.ejb.AvailableSettings;
+import org.hibernate.ejb.HibernateEntityManagerFactory;
+import org.hibernate.ejb.test.Distributor;
+import org.hibernate.ejb.test.Item;
+import org.hibernate.ejb.test.pack.cfgxmlpar.Morito;
+import org.hibernate.ejb.test.pack.defaultpar.ApplicationServer;
+import org.hibernate.ejb.test.pack.defaultpar.IncrementListener;
+import org.hibernate.ejb.test.pack.defaultpar.Lighter;
+import org.hibernate.ejb.test.pack.defaultpar.Money;
+import org.hibernate.ejb.test.pack.defaultpar.Mouse;
+import org.hibernate.ejb.test.pack.defaultpar.OtherIncrementListener;
+import org.hibernate.ejb.test.pack.defaultpar.Version;
+import org.hibernate.ejb.test.pack.defaultpar_1_0.ApplicationServer1;
+import org.hibernate.ejb.test.pack.defaultpar_1_0.Lighter1;
+import org.hibernate.ejb.test.pack.defaultpar_1_0.Mouse1;
+import org.hibernate.ejb.test.pack.defaultpar_1_0.Version1;
+import org.hibernate.ejb.test.pack.excludehbmpar.Caipirinha;
+import org.hibernate.ejb.test.pack.explodedpar.Carpet;
+import org.hibernate.ejb.test.pack.explodedpar.Elephant;
+import org.hibernate.ejb.test.pack.externaljar.Scooter;
+import org.hibernate.ejb.test.pack.spacepar.Bug;
+import org.hibernate.ejb.test.pack.various.Airplane;
+import org.hibernate.ejb.test.pack.various.Seat;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.event.EventListeners;
+import org.hibernate.stat.Statistics;
+import org.hibernate.util.ConfigHelper;
+
+/**
+ * In this test we verify that it is possible to bootstrap Hibernate/JPA from
+ * various bundles (war, par, ...) using {@code Persistence.createEntityManagerFactory()}
+ * <p/>
+ * Each test will before its run build the required bundle and place them into the classpath.
+ *
+ * @author Gavin King
+ * @author Hardy Ferentschik
+ */
+@SuppressWarnings("unchecked")
+public class PackagedEntityManagerTest extends PackagingTestCase {
+
+ public void testDefaultPar() throws Exception {
+ File testPackage = buildDefaultPar();
+ addPackageToClasspath( testPackage );
+
+ // run the test
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory( "defaultpar", new HashMap() );
+ EntityManager em = emf.createEntityManager();
+ ApplicationServer as = new ApplicationServer();
+ as.setName( "JBoss AS" );
+ Version v = new Version();
+ v.setMajor( 4 );
+ v.setMinor( 0 );
+ v.setMicro( 3 );
+ as.setVersion( v );
+ Mouse mouse = new Mouse();
+ mouse.setName( "mickey" );
+ em.getTransaction().begin();
+ em.persist( as );
+ em.persist( mouse );
+ assertEquals( 1, em.createNamedQuery( "allMouse" ).getResultList().size() );
+ Lighter lighter = new Lighter();
+ lighter.name = "main";
+ lighter.power = " 250 W";
+ em.persist( lighter );
+ em.flush();
+ em.remove( lighter );
+ em.remove( mouse );
+ assertNotNull( as.getId() );
+ em.remove( as );
+ em.getTransaction().commit();
+ em.close();
+ emf.close();
+ }
+
+ public void testDefaultParForPersistence_1_0() throws Exception {
+ File testPackage = buildDefaultPar_1_0();
+ addPackageToClasspath( testPackage );
+
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory( "defaultpar_1_0", new HashMap() );
+ EntityManager em = emf.createEntityManager();
+ ApplicationServer1 as = new ApplicationServer1();
+ as.setName( "JBoss AS" );
+ Version1 v = new Version1();
+ v.setMajor( 4 );
+ v.setMinor( 0 );
+ v.setMicro( 3 );
+ as.setVersion( v );
+ Mouse1 mouse = new Mouse1();
+ mouse.setName( "mickey" );
+ em.getTransaction().begin();
+ em.persist( as );
+ em.persist( mouse );
+ assertEquals( 1, em.createNamedQuery( "allMouse_1_0" ).getResultList().size() );
+ Lighter1 lighter = new Lighter1();
+ lighter.name = "main";
+ lighter.power = " 250 W";
+ em.persist( lighter );
+ em.flush();
+ em.remove( lighter );
+ em.remove( mouse );
+ assertNotNull( as.getId() );
+ em.remove( as );
+ em.getTransaction().commit();
+ em.close();
+ emf.close();
+ }
+
+ public void testListenersDefaultPar() throws Exception {
+ File testPackage = buildDefaultPar();
+ addPackageToClasspath( testPackage );
+
+ IncrementListener.reset();
+ OtherIncrementListener.reset();
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory( "defaultpar", new HashMap() );
+ EntityManager em = emf.createEntityManager();
+ em.getTransaction().begin();
+ ApplicationServer as = new ApplicationServer();
+ as.setName( "JBoss AS" );
+ Version v = new Version();
+ v.setMajor( 4 );
+ v.setMinor( 0 );
+ v.setMicro( 3 );
+ as.setVersion( v );
+ em.persist( as );
+ em.flush();
+ assertEquals( "Failure in default listeners", 1, IncrementListener.getIncrement() );
+ assertEquals( "Failure in XML overriden listeners", 1, OtherIncrementListener.getIncrement() );
+
+ Mouse mouse = new Mouse();
+ mouse.setName( "mickey" );
+ em.persist( mouse );
+ em.flush();
+ assertEquals( "Failure in @ExcludeDefaultListeners", 1, IncrementListener.getIncrement() );
+ assertEquals( 1, OtherIncrementListener.getIncrement() );
+
+ Money money = new Money();
+ em.persist( money );
+ em.flush();
+ assertEquals( "Failure in @ExcludeDefaultListeners", 2, IncrementListener.getIncrement() );
+ assertEquals( 1, OtherIncrementListener.getIncrement() );
+
+ em.getTransaction().rollback();
+ em.close();
+ emf.close();
+ }
+
+ public void testExplodedPar() throws Exception {
+ File testPackage = buildExplodedPar();
+ addPackageToClasspath( testPackage );
+
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory( "explodedpar", new HashMap() );
+ EntityManager em = emf.createEntityManager();
+ org.hibernate.ejb.test.pack.explodedpar.Carpet carpet = new Carpet();
+ Elephant el = new Elephant();
+ el.setName( "Dumbo" );
+ carpet.setCountry( "Turkey" );
+ em.getTransaction().begin();
+ em.persist( carpet );
+ em.persist( el );
+ assertEquals( 1, em.createNamedQuery( "allCarpet" ).getResultList().size() );
+ assertNotNull( carpet.getId() );
+ em.remove( carpet );
+ em.getTransaction().commit();
+ em.close();
+ emf.close();
+ }
+
+ public void testExcludeHbmPar() throws Exception {
+ File testPackage = buildExcludeHbmPar();
+ addPackageToClasspath( testPackage );
+
+ EntityManagerFactory emf = null;
+ try {
+ emf = Persistence.createEntityManagerFactory( "excludehbmpar", new HashMap() );
+ }
+ catch ( PersistenceException e ) {
+ Throwable nested = e.getCause();
+ if ( nested == null ) {
+ throw e;
+ }
+ nested = nested.getCause();
+ if ( nested == null ) {
+ throw e;
+ }
+ if ( !( nested instanceof ClassNotFoundException ) ) {
+ throw e;
+ }
+ fail( "Try to process hbm file: " + e.getMessage() );
+ }
+ EntityManager em = emf.createEntityManager();
+ Caipirinha s = new Caipirinha( "Strong" );
+ em.getTransaction().begin();
+ em.persist( s );
+ em.getTransaction().commit();
+
+ em.getTransaction().begin();
+ s = em.find( Caipirinha.class, s.getId() );
+ em.remove( s );
+ em.getTransaction().commit();
+ em.close();
+ emf.close();
+ }
+
+ public void testCfgXmlPar() throws Exception {
+ File testPackage = buildCfgXmlPar();
+ addPackageToClasspath( testPackage );
+
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory( "cfgxmlpar", new HashMap() );
+ EntityManager em = emf.createEntityManager();
+ Item i = new Item();
+ i.setDescr( "Blah" );
+ i.setName( "factory" );
+ Morito m = new Morito();
+ m.setPower( "SuperStrong" );
+ em.getTransaction().begin();
+ em.persist( i );
+ em.persist( m );
+ em.getTransaction().commit();
+
+ em.getTransaction().begin();
+ i = em.find( Item.class, i.getName() );
+ em.remove( i );
+ em.remove( em.find( Morito.class, m.getId() ) );
+ em.getTransaction().commit();
+ em.close();
+ emf.close();
+ }
+
+ public void testSpacePar() throws Exception {
+ File testPackage = buildSpacePar();
+ addPackageToClasspath( testPackage );
+
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory( "space par", new HashMap() );
+ EntityManager em = emf.createEntityManager();
+ Bug bug = new Bug();
+ bug.setSubject( "Spaces in directory name don't play well on Windows" );
+ em.getTransaction().begin();
+ em.persist( bug );
+ em.flush();
+ em.remove( bug );
+ assertNotNull( bug.getId() );
+ em.getTransaction().rollback();
+ em.close();
+ emf.close();
+ }
+
+ public void testOverridenPar() throws Exception {
+ File testPackage = buildOverridenPar();
+ addPackageToClasspath( testPackage );
+
+ HashMap properties = new HashMap();
+ properties.put( AvailableSettings.JTA_DATASOURCE, null );
+ Properties p = new Properties();
+ p.load( ConfigHelper.getResourceAsStream( "/overridenpar.properties" ) );
+ properties.putAll( p );
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory( "overridenpar", properties );
+ EntityManager em = emf.createEntityManager();
+ org.hibernate.ejb.test.pack.overridenpar.Bug bug = new org.hibernate.ejb.test.pack.overridenpar.Bug();
+ bug.setSubject( "Allow DS overriding" );
+ em.getTransaction().begin();
+ em.persist( bug );
+ em.flush();
+ em.remove( bug );
+ assertNotNull( bug.getId() );
+ em.getTransaction().rollback();
+ em.close();
+ emf.close();
+ }
+
+ public void testListeners() throws Exception {
+ File testPackage = buildExplicitPar();
+ addPackageToClasspath( testPackage );
+
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
+ EntityManager em = emf.createEntityManager();
+ EventListeners eventListeners = em.unwrap( SessionImplementor.class ).getListeners();
+ assertEquals(
+ "Explicit pre-insert event through hibernate.ejb.event.pre-insert does not work",
+ eventListeners.getPreInsertEventListeners().length,
+ eventListeners.getPreUpdateEventListeners().length + 1
+ );
+
+ em.close();
+ emf.close();
+ }
+
+ public void testExtendedEntityManager() throws Exception {
+ File testPackage = buildExplicitPar();
+ addPackageToClasspath( testPackage );
+
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
+ EntityManager em = emf.createEntityManager();
+ Item item = new Item( "Mouse", "Micro$oft mouse" );
+ em.getTransaction().begin();
+ em.persist( item );
+ assertTrue( em.contains( item ) );
+ em.getTransaction().commit();
+
+ assertTrue( em.contains( item ) );
+
+ em.getTransaction().begin();
+ Item item1 = ( Item ) em.createQuery( "select i from Item i where descr like 'M%'" ).getSingleResult();
+ assertNotNull( item1 );
+ assertSame( item, item1 );
+ item.setDescr( "Micro$oft wireless mouse" );
+ assertTrue( em.contains( item ) );
+ em.getTransaction().commit();
+
+ assertTrue( em.contains( item ) );
+
+ em.getTransaction().begin();
+ item1 = em.find( Item.class, "Mouse" );
+ assertSame( item, item1 );
+ em.getTransaction().commit();
+ assertTrue( em.contains( item ) );
+
+ item1 = em.find( Item.class, "Mouse" );
+ assertSame( item, item1 );
+ assertTrue( em.contains( item ) );
+
+ item1 = ( Item ) em.createQuery( "select i from Item i where descr like 'M%'" ).getSingleResult();
+ assertNotNull( item1 );
+ assertSame( item, item1 );
+ assertTrue( em.contains( item ) );
+
+ em.getTransaction().begin();
+ assertTrue( em.contains( item ) );
+ em.remove( item );
+ em.remove( item ); //second remove should be a no-op
+ em.getTransaction().commit();
+
+ em.close();
+ emf.close();
+ }
+
+ public void testConfiguration() throws Exception {
+ File testPackage = buildExplicitPar();
+ addPackageToClasspath( testPackage );
+
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
+ Item item = new Item( "Mouse", "Micro$oft mouse" );
+ Distributor res = new Distributor();
+ res.setName( "Bruce" );
+ item.setDistributors( new HashSet<Distributor>() );
+ item.getDistributors().add( res );
+ Statistics stats = ( ( HibernateEntityManagerFactory ) emf ).getSessionFactory().getStatistics();
+ stats.clear();
+ stats.setStatisticsEnabled( true );
+
+ EntityManager em = emf.createEntityManager();
+ em.getTransaction().begin();
+
+ em.persist( res );
+ em.persist( item );
+ assertTrue( em.contains( item ) );
+
+ em.getTransaction().commit();
+ em.close();
+
+ assertEquals( 1, stats.getSecondLevelCachePutCount() );
+ assertEquals( 0, stats.getSecondLevelCacheHitCount() );
+
+ em = emf.createEntityManager();
+ em.getTransaction().begin();
+ Item second = em.find( Item.class, item.getName() );
+ assertEquals( 1, second.getDistributors().size() );
+ assertEquals( 1, stats.getSecondLevelCacheHitCount() );
+ em.getTransaction().commit();
+ em.close();
+
+ em = emf.createEntityManager();
+ em.getTransaction().begin();
+ second = em.find( Item.class, item.getName() );
+ assertEquals( 1, second.getDistributors().size() );
+ assertEquals( 3, stats.getSecondLevelCacheHitCount() );
+ for ( Distributor distro : second.getDistributors() ) {
+ em.remove( distro );
+ }
+ em.remove( second );
+ em.getTransaction().commit();
+ em.close();
+
+ stats.clear();
+ stats.setStatisticsEnabled( false );
+ emf.close();
+ }
+
+ public void testExternalJar() throws Exception {
+ File externalJar = buildExternalJar();
+ File testPackage = buildExplicitPar();
+ addPackageToClasspath( testPackage, externalJar );
+
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
+ EntityManager em = emf.createEntityManager();
+ Scooter s = new Scooter();
+ s.setModel( "Abadah" );
+ s.setSpeed( 85l );
+ em.getTransaction().begin();
+ em.persist( s );
+ em.getTransaction().commit();
+ em.close();
+ em = emf.createEntityManager();
+ em.getTransaction().begin();
+ s = em.find( Scooter.class, s.getModel() );
+ assertEquals( new Long( 85 ), s.getSpeed() );
+ em.remove( s );
+ em.getTransaction().commit();
+ em.close();
+ emf.close();
+ }
+
+ public void testORMFileOnMainAndExplicitJars() throws Exception {
+ File testPackage = buildExplicitPar();
+ addPackageToClasspath( testPackage );
+
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() );
+ EntityManager em = emf.createEntityManager();
+ Seat seat = new Seat();
+ seat.setNumber( "3B" );
+ Airplane plane = new Airplane();
+ plane.setSerialNumber( "75924418409052355" );
+ em.getTransaction().begin();
+ em.persist( seat );
+ em.persist( plane );
+ em.flush();
+ em.getTransaction().rollback();
+ em.close();
+ emf.close();
+ }
+}
\ No newline at end of file
Property changes on: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/PackagedEntityManagerTest.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Added: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/PackagingTestCase.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/PackagingTestCase.java (rev 0)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/PackagingTestCase.java 2010-02-23 12:57:17 UTC (rev 18858)
@@ -0,0 +1,359 @@
+// $Id:$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.ejb.test.packaging;
+
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.List;
+
+import junit.framework.TestCase;
+import org.jboss.shrinkwrap.api.ArchivePath;
+import org.jboss.shrinkwrap.api.ArchivePaths;
+import org.jboss.shrinkwrap.api.Archives;
+import org.jboss.shrinkwrap.api.exporter.ExplodedExporter;
+import org.jboss.shrinkwrap.api.exporter.ZipExporter;
+import org.jboss.shrinkwrap.api.spec.JavaArchive;
+import org.jboss.shrinkwrap.api.spec.WebArchive;
+
+import org.hibernate.ejb.test.Cat;
+import org.hibernate.ejb.test.Distributor;
+import org.hibernate.ejb.test.Item;
+import org.hibernate.ejb.test.Kitten;
+import org.hibernate.ejb.test.pack.cfgxmlpar.Morito;
+import org.hibernate.ejb.test.pack.defaultpar.ApplicationServer;
+import org.hibernate.ejb.test.pack.defaultpar.IncrementListener;
+import org.hibernate.ejb.test.pack.defaultpar.Lighter;
+import org.hibernate.ejb.test.pack.defaultpar.Money;
+import org.hibernate.ejb.test.pack.defaultpar.Mouse;
+import org.hibernate.ejb.test.pack.defaultpar.OtherIncrementListener;
+import org.hibernate.ejb.test.pack.defaultpar.Version;
+import org.hibernate.ejb.test.pack.defaultpar_1_0.ApplicationServer1;
+import org.hibernate.ejb.test.pack.defaultpar_1_0.IncrementListener1;
+import org.hibernate.ejb.test.pack.defaultpar_1_0.Lighter1;
+import org.hibernate.ejb.test.pack.defaultpar_1_0.Money1;
+import org.hibernate.ejb.test.pack.defaultpar_1_0.Mouse1;
+import org.hibernate.ejb.test.pack.defaultpar_1_0.Version1;
+import org.hibernate.ejb.test.pack.excludehbmpar.Caipirinha;
+import org.hibernate.ejb.test.pack.explodedpar.Carpet;
+import org.hibernate.ejb.test.pack.explodedpar.Elephant;
+import org.hibernate.ejb.test.pack.externaljar.Scooter;
+import org.hibernate.ejb.test.pack.spacepar.Bug;
+import org.hibernate.ejb.test.pack.various.Airplane;
+import org.hibernate.ejb.test.pack.various.Seat;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public abstract class PackagingTestCase extends TestCase {
+ protected static ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
+ protected static ClassLoader bundleClassLoader;
+ protected static File targetDir;
+
+ static {
+ // get a URL reference to something we now is part of the classpath (us)
+ URL myUrl = originalClassLoader.getResource(
+ PackagingTestCase.class.getName().replace( '.', '/' ) + ".class"
+ );
+ File myPath = new File( myUrl.getFile() );
+ // navigate back to '/target'
+ targetDir = myPath
+ .getParentFile() // target/classes/org/hibernate/ejb/test/packaging
+ .getParentFile() // target/classes/org/hibernate/ejb/test
+ .getParentFile() // target/classes/org/hibernate/ejb
+ .getParentFile() // target/classes/org/hibernate
+ .getParentFile() // target/classes/org
+ .getParentFile() // target/classes/
+ .getParentFile(); // target
+ File testPackagesDir = new File( targetDir, "bundles" );
+ try {
+ bundleClassLoader = new URLClassLoader( new URL[] { testPackagesDir.toURL() }, originalClassLoader );
+ }
+ catch ( MalformedURLException e ) {
+ fail( "Unable to build custom class loader" );
+ }
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ // add the bundle class loader in order for ShrinkWrap to build the test package
+ Thread.currentThread().setContextClassLoader( bundleClassLoader );
+ super.setUp();
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ super.tearDown();
+ // reset the classloader
+ Thread.currentThread().setContextClassLoader( originalClassLoader );
+ }
+
+ protected void addPackageToClasspath(File... testPackages) throws MalformedURLException {
+ List<URL> urlList = new ArrayList<URL>();
+ for ( File file : testPackages ) {
+ urlList.add( file.toURL() );
+ }
+ URLClassLoader classLoader = new URLClassLoader(
+ urlList.toArray( new URL[urlList.size()] ), originalClassLoader
+ );
+ Thread.currentThread().setContextClassLoader( classLoader );
+ }
+
+ protected File buildDefaultPar() {
+ String fileName = "defaultpar.par";
+ JavaArchive archive = Archives.create( fileName, JavaArchive.class );
+ archive.addClasses(
+ ApplicationServer.class,
+ Lighter.class,
+ Money.class,
+ Mouse.class,
+ OtherIncrementListener.class,
+ IncrementListener.class,
+ Version.class
+ );
+ ArchivePath path = ArchivePaths.create( "META-INF/orm.xml" );
+ archive.addResource( "defaultpar/META-INF/orm.xml", path );
+
+ path = ArchivePaths.create( "META-INF/persistence.xml" );
+ archive.addResource( "defaultpar/META-INF/persistence.xml", path );
+
+ path = ArchivePaths.create( "org/hibernate/ejb/test/pack/defaultpar/Mouse.hbm.xml" );
+ archive.addResource( "defaultpar/org/hibernate/ejb/test/pack/defaultpar/Mouse.hbm.xml", path );
+
+ path = ArchivePaths.create( "org/hibernate/ejb/test/pack/defaultpar/package-info.class" );
+ archive.addResource( "org/hibernate/ejb/test/pack/defaultpar/package-info.class", path );
+
+
+ File testPackage = new File( targetDir, fileName );
+ archive.as( ZipExporter.class ).exportZip( testPackage, true );
+ return testPackage;
+ }
+
+ protected File buildDefaultPar_1_0() {
+ String fileName = "defaultpar_1_0.par";
+ JavaArchive archive = Archives.create( fileName, JavaArchive.class );
+ archive.addClasses(
+ ApplicationServer1.class,
+ Lighter1.class,
+ Money1.class,
+ Mouse1.class,
+ IncrementListener1.class,
+ Version1.class
+ );
+ ArchivePath path = ArchivePaths.create( "META-INF/orm.xml" );
+ archive.addResource( "defaultpar_1_0/META-INF/orm.xml", path );
+
+ path = ArchivePaths.create( "META-INF/persistence.xml" );
+ archive.addResource( "defaultpar_1_0/META-INF/persistence.xml", path );
+
+ path = ArchivePaths.create( "org/hibernate/ejb/test/pack/defaultpar_1_0/Mouse.hbm.xml" );
+ archive.addResource( "defaultpar_1_0/org/hibernate/ejb/test/pack/defaultpar_1_0/Mouse1.hbm.xml", path );
+
+ path = ArchivePaths.create( "org/hibernate/ejb/test/pack/defaultpar_1_0/package-info.class" );
+ archive.addResource( "org/hibernate/ejb/test/pack/defaultpar_1_0/package-info.class", path );
+
+
+ File testPackage = new File( targetDir, fileName );
+ archive.as( ZipExporter.class ).exportZip( testPackage, true );
+ return testPackage;
+ }
+
+ protected File buildExplicitPar() {
+ String fileName = "explicitpar.par";
+ JavaArchive archive = Archives.create( fileName, JavaArchive.class );
+ archive.addClasses(
+ Airplane.class,
+ Seat.class,
+ Cat.class,
+ Kitten.class,
+ Distributor.class,
+ Item.class
+ );
+
+ ArchivePath path = ArchivePaths.create( "META-INF/orm.xml" );
+ archive.addResource( "explicitpar/META-INF/orm.xml", path );
+
+ path = ArchivePaths.create( "META-INF/persistence.xml" );
+ archive.addResource( "explicitpar/META-INF/persistence.xml", path );
+
+ File testPackage = new File( targetDir, fileName );
+ archive.as( ZipExporter.class ).exportZip( testPackage, true );
+ return testPackage;
+ }
+
+ protected File buildExplodedPar() {
+ String fileName = "explodedpar";
+ JavaArchive archive = Archives.create( fileName, JavaArchive.class );
+ archive.addClasses(
+ Elephant.class,
+ Carpet.class
+ );
+
+ ArchivePath path = ArchivePaths.create( "META-INF/persistence.xml" );
+ archive.addResource( "explodedpar/META-INF/persistence.xml", path );
+
+ path = ArchivePaths.create( "org/hibernate/ejb/test/pack/explodedpar/Elephant.hbm.xml" );
+ archive.addResource( "explodedpar/org/hibernate/ejb/test/pack/explodedpar/Elephant.hbm.xml", path );
+
+ path = ArchivePaths.create( "org/hibernate/ejb/test/pack/explodedpar/package-info.class" );
+ archive.addResource( "org/hibernate/ejb/test/pack/explodedpar/package-info.class", path );
+
+ File testPackage = new File( targetDir, fileName );
+ archive.as( ExplodedExporter.class ).exportExploded( targetDir );
+ return testPackage;
+ }
+
+ protected File buildExcludeHbmPar() {
+ String fileName = "excludehbmpar.par";
+ JavaArchive archive = Archives.create( fileName, JavaArchive.class );
+ archive.addClasses(
+ Caipirinha.class
+ );
+
+ ArchivePath path = ArchivePaths.create( "META-INF/orm2.xml" );
+ archive.addResource( "excludehbmpar/META-INF/orm2.xml", path );
+
+ path = ArchivePaths.create( "META-INF/persistence.xml" );
+ archive.addResource( "excludehbmpar/META-INF/persistence.xml", path );
+
+ path = ArchivePaths.create( "org/hibernate/ejb/test/pack/excludehbmpar/Mouse.hbm.xml" );
+ archive.addResource( "excludehbmpar/org/hibernate/ejb/test/pack/excludehbmpar/Mouse.hbm.xml", path );
+
+ File testPackage = new File( targetDir, fileName );
+ archive.as( ZipExporter.class ).exportZip( testPackage, true );
+ return testPackage;
+ }
+
+ protected File buildCfgXmlPar() {
+ String fileName = "cfgxmlpar.par";
+ JavaArchive archive = Archives.create( fileName, JavaArchive.class );
+ archive.addClasses(
+ Morito.class,
+ Item.class
+ );
+
+ ArchivePath path = ArchivePaths.create( "META-INF/persistence.xml" );
+ archive.addResource( "cfgxmlpar/META-INF/persistence.xml", path );
+
+ path = ArchivePaths.create( "org/hibernate/ejb/test/pack/cfgxmlpar/hibernate.cfg.xml" );
+ archive.addResource( "cfgxmlpar/org/hibernate/ejb/test/pack/cfgxmlpar/hibernate.cfg.xml", path );
+
+ File testPackage = new File( targetDir, fileName );
+ archive.as( ZipExporter.class ).exportZip( testPackage, true );
+ return testPackage;
+ }
+
+ protected File buildSpacePar() {
+ String fileName = "space par.par";
+ JavaArchive archive = Archives.create( fileName, JavaArchive.class );
+ archive.addClasses(
+ Bug.class
+ );
+
+ ArchivePath path = ArchivePaths.create( "META-INF/persistence.xml" );
+ archive.addResource( "space par/META-INF/persistence.xml", path );
+
+ File testPackage = new File( targetDir, fileName );
+ archive.as( ZipExporter.class ).exportZip( testPackage, true );
+ return testPackage;
+ }
+
+ protected File buildOverridenPar() {
+ String fileName = "overridenpar.jar";
+ JavaArchive archive = Archives.create( fileName, JavaArchive.class );
+ archive.addClasses(
+ org.hibernate.ejb.test.pack.overridenpar.Bug.class
+ );
+
+ ArchivePath path = ArchivePaths.create( "META-INF/persistence.xml" );
+ archive.addResource( "overridenpar/META-INF/persistence.xml", path );
+
+ path = ArchivePaths.create( "overridenpar.properties" );
+ archive.addResource( "overridenpar/overridenpar.properties", path );
+
+ File testPackage = new File( targetDir, fileName );
+ archive.as( ZipExporter.class ).exportZip( testPackage, true );
+ return testPackage;
+ }
+
+ protected File buildExternalJar() {
+ String fileName = "externaljar.jar";
+ JavaArchive archive = Archives.create( fileName, JavaArchive.class );
+ archive.addClasses(
+ Scooter.class
+ );
+
+ ArchivePath path = ArchivePaths.create( "META-INF/orm.xml" );
+ archive.addResource( "externaljar/META-INF/orm.xml", path );
+
+ File testPackage = new File( targetDir, fileName );
+ archive.as( ZipExporter.class ).exportZip( testPackage, true );
+ return testPackage;
+ }
+
+ protected File buildWar() {
+ String fileName = "war.war";
+ WebArchive archive = Archives.create( fileName, WebArchive.class );
+ archive.addClasses(
+ org.hibernate.ejb.test.pack.war.ApplicationServer.class,
+ org.hibernate.ejb.test.pack.war.IncrementListener.class,
+ org.hibernate.ejb.test.pack.war.Lighter.class,
+ org.hibernate.ejb.test.pack.war.Money.class,
+ org.hibernate.ejb.test.pack.war.Mouse.class,
+ org.hibernate.ejb.test.pack.war.OtherIncrementListener.class,
+ org.hibernate.ejb.test.pack.war.Version.class
+ );
+
+ ArchivePath path = ArchivePaths.create( "WEB-INF/classes/META-INF/orm.xml" );
+ archive.addResource( "war/WEB-INF/classes/META-INF/orm.xml", path );
+
+ path = ArchivePaths.create( "WEB-INF/classes/META-INF/persistence.xml" );
+ archive.addResource( "war/WEB-INF/classes/META-INF/persistence.xml", path );
+
+ path = ArchivePaths.create( "WEB-INF/classes/org/hibernate/ejb/test/pack/war/Mouse.hbm.xml" );
+ archive.addResource( "war/WEB-INF/classes/org/hibernate/ejb/test/pack/war/Mouse.hbm.xml", path );
+
+ File testPackage = new File( targetDir, fileName );
+ archive.as( ZipExporter.class ).exportZip( testPackage, true );
+ return testPackage;
+ }
+
+ protected File buildNestedEar(File includeFile) {
+ String fileName = "nestedjar.ear";
+ JavaArchive archive = Archives.create( fileName, JavaArchive.class );
+ archive.addResource( includeFile );
+
+ File testPackage = new File( targetDir, fileName );
+ archive.as( ZipExporter.class ).exportZip( testPackage, true );
+ return testPackage;
+ }
+
+ protected File buildNestedEarDir(File includeFile) {
+ String fileName = "nesteddir.ear";
+ JavaArchive archive = Archives.create( fileName, JavaArchive.class );
+ archive.addResource( includeFile );
+
+ File testPackage = new File( targetDir, fileName );
+ archive.as( ExplodedExporter.class ).exportExploded( targetDir );
+ return testPackage;
+ }
+}
+
+
Property changes on: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/packaging/PackagingTestCase.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: core/trunk/testing/src/main/java/org/hibernate/test/annotations/HibernateTestCase.java
===================================================================
--- core/trunk/testing/src/main/java/org/hibernate/test/annotations/HibernateTestCase.java 2010-02-23 12:11:34 UTC (rev 18857)
+++ core/trunk/testing/src/main/java/org/hibernate/test/annotations/HibernateTestCase.java 2010-02-23 12:57:17 UTC (rev 18858)
@@ -1,3 +1,4 @@
+// $Id:$
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
@@ -287,6 +288,10 @@
protected abstract Class<?>[] getAnnotatedClasses();
+ protected String[] getMappings() {
+ return new String[]{};
+ }
+
protected abstract void handleUnclosedResources();
protected abstract void closeResources();
14 years, 12 months
Hibernate SVN: r18857 - in core/trunk/cache-infinispan/src: test/java/org/hibernate/test/cache/infinispan/access and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: galder.zamarreno(a)jboss.com
Date: 2010-02-23 07:11:34 -0500 (Tue, 23 Feb 2010)
New Revision: 18857
Modified:
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/access/PutFromLoadValidator.java
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java
core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/access/PutFromLoadValidatorUnitTestCase.java
core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/AbstractCollectionRegionAccessStrategyTestCase.java
core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/ConcurrentWriteTest.java
core/trunk/cache-infinispan/src/test/resources/log4j.properties
Log:
[HHH-4944] (putFromLoad calls could store stale data) Fixed.
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/access/PutFromLoadValidator.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/access/PutFromLoadValidator.java 2010-02-23 12:09:45 UTC (rev 18856)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/access/PutFromLoadValidator.java 2010-02-23 12:11:34 UTC (rev 18857)
@@ -30,6 +30,7 @@
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@@ -46,28 +47,59 @@
* the potential to store stale data, since the data may have been removed from the
* database and the cache between the time when the data was read from the database
* and the actual call to <code>putFromLoad</code>.
+ * <p>
+ * The expected usage of this class by a thread that read the cache and did
+ * not find data is:
*
+ * <ol>
+ * <li> Call {@link #registerPendingPut(Object)}</li>
+ * <li> Read the database</li>
+ * <li> Call {@link #acquirePutFromLoadLock(Object)}
+ * <li> if above returns <code>false</code>, the thread should not cache the data;
+ * only if above returns <code>true</code>, put data in the cache and...</li>
+ * <li> then call {@link #releasePutFromLoadLock(Object)}</li>
+ * </ol>
+ * </p>
+ *
+ * <p>
+ * The expected usage by a thread that is taking an action such that any pending
+ * <code>putFromLoad</code> may have stale data and should not cache it is to either
+ * call
+ *
+ * <ul>
+ * <li> {@link #invalidateKey(Object)} (for a single key invalidation)</li>
+ * <li>or {@link #invalidateRegion()} (for a general invalidation all pending puts)</li>
+ * </ul>
+ * </p>
+ *
+ * <p>
+ * This class also supports the concept of "naked puts", which are calls to
+ * {@link #acquirePutFromLoadLock(Object)} without a preceding {@link #registerPendingPut(Object)}
+ * call.
+ * </p>
+ *
* @author Brian Stansberry
*
* @version $Revision: $
*/
public class PutFromLoadValidator {
/**
- * Period in ms after a removal during which a call to {@link #isPutValid(Object)} that hasn't
- * been {@link #registerPendingPut(Object) pre-registered} (aka a "naked put") will return false.
+ * Period (in ms) after a removal during which a call to
+ * {@link #acquirePutFromLoadLock(Object)} that hasn't been
+ * {@link #registerPendingPut(Object) pre-registered} (aka a "naked put")
+ * will return false.
+ * will return false.
*/
- public static final long NAKED_PUT_INVALIDATION_PERIOD = 10 * 1000;
+ public static final long NAKED_PUT_INVALIDATION_PERIOD = TimeUnit.SECONDS.toMillis(20);
- /** Period after which a pending put is placed in the over-age queue */
- private static final long PENDING_PUT_OVERAGE_PERIOD = 5 * 1000;
+ /** Period (in ms) after which a pending put is placed in the over-age queue */
+ private static final long PENDING_PUT_OVERAGE_PERIOD = TimeUnit.SECONDS.toMillis(5);
- /** Period before which we stop trying to clean out pending puts */
- private static final long PENDING_PUT_RECENT_PERIOD = 2 * 1000;
+ /** Period (in ms) before which we stop trying to clean out pending puts */
+ private static final long PENDING_PUT_RECENT_PERIOD = TimeUnit.SECONDS.toMillis(2);
- /**
- * Period after which a pending put is never expected to come in and should be cleaned
- */
- private static final long MAX_PENDING_PUT_DELAY = 2 * 60 * 1000;
+ /** Period (in ms) after which a pending put is never expected to come in and should be cleaned */
+ private static final long MAX_PENDING_PUT_DELAY = TimeUnit.SECONDS.toMillis(2 * 60);
/**
* Used to determine whether the owner of a pending put is a thread or a transaction
@@ -119,7 +151,7 @@
* Creates a new PutFromLoadValidator.
*
* @param transactionManager
- * transaction manager to use to associated changes with a transaction; may be
+ * transaction manager to use to associate changes with a transaction; may be
* <code>null</code>
*/
public PutFromLoadValidator(TransactionManager transactionManager) {
@@ -142,41 +174,136 @@
// ----------------------------------------------------------------- Public
- public boolean isPutValid(Object key) {
+ /**
+ * Acquire a lock giving the calling thread the right to put data in the
+ * cache for the given key.
+ * <p>
+ * <strong>NOTE:</strong> A call to this method that returns <code>true</code>
+ * should always be matched with a call to {@link #releasePutFromLoadLock(Object)}.
+ * </p>
+ *
+ * @param key the key
+ *
+ * @return <code>true</code> if the lock is acquired and the cache put
+ * can proceed; <code>false</code> if the data should not be cached
+ */
+ public boolean acquirePutFromLoadLock(Object key) {
boolean valid = false;
+ boolean locked = false;
long now = System.currentTimeMillis();
- PendingPutMap pending = pendingPuts.get(key);
- if (pending != null) {
- synchronized (pending) {
- PendingPut toCancel = pending.remove(getOwnerForPut());
- valid = toCancel != null;
- if (valid) {
- toCancel.completed = true;
- if (pending.size() == 0) {
- pendingPuts.remove(key);
+ // Important: Do cleanup before we acquire any locks so we
+ // don't deadlock with invalidateRegion
+ cleanOutdatedPendingPuts(now, true);
+
+ try {
+ PendingPutMap pending = pendingPuts.get(key);
+ if (pending != null) {
+ locked = pending.acquireLock(100, TimeUnit.MILLISECONDS);
+ if (locked) {
+ try {
+ PendingPut toCancel = pending.remove(getOwnerForPut());
+ if (toCancel != null) {
+ valid = !toCancel.completed;
+ toCancel.completed = true;
+ }
}
+ finally {
+ if (!valid) {
+ pending.releaseLock();
+ locked = false;
+ }
+ }
}
}
+ else {
+ // Key wasn't in pendingPuts, so either this is a "naked put"
+ // or regionRemoved has been called. Check if we can proceed
+ if (now > invalidationTimestamp) {
+ Long removedTime = recentRemovals.get(key);
+ if (removedTime == null || now > removedTime.longValue()) {
+ // It's legal to proceed. But we have to record this key
+ // in pendingPuts so releasePutFromLoadLock can find it.
+ // To do this we basically simulate a normal "register
+ // then acquire lock" pattern
+ registerPendingPut(key);
+ locked = acquirePutFromLoadLock(key);
+ valid = locked;
+ }
+ }
+ }
}
+ catch (Throwable t) {
- if (!valid) {
- if (now > invalidationTimestamp) {
- Long removedTime = recentRemovals.get(key);
- if (removedTime == null || now > removedTime.longValue()) {
- valid = true;
+ valid = false;
+
+ if (locked) {
+ PendingPutMap toRelease = pendingPuts.get(key);
+ if (toRelease != null) {
+ toRelease.releaseLock();
}
}
+
+ if (t instanceof RuntimeException) {
+ throw (RuntimeException) t;
+ } else if (t instanceof Error) {
+ throw (Error) t;
+ } else {
+ throw new RuntimeException(t);
+ }
}
- cleanOutdatedPendingPuts(now, true);
-
return valid;
}
- public void keyRemoved(Object key) {
+ /**
+ * Releases the lock previously obtained by a call to
+ * {@link #acquirePutFromLoadLock(Object)} that returned <code>true</code>.
+ *
+ * @param key the key
+ */
+ public void releasePutFromLoadLock(Object key) {
+ PendingPutMap pending = pendingPuts.get(key);
+ if (pending != null) {
+ if (pending.size() == 0) {
+ pendingPuts.remove(key);
+ }
+ pending.releaseLock();
+ }
+ }
+
+ /**
+ * Invalidates any {@link #registerPendingPut(Object) previously registered pending puts} ensuring a subsequent call to
+ * {@link #acquirePutFromLoadLock(Object)} will return <code>false</code>. <p> This method will block until any
+ * concurrent thread that has {@link #acquirePutFromLoadLock(Object) acquired the putFromLoad lock} for the given key
+ * has released the lock. This allows the caller to be certain the putFromLoad will not execute after this method
+ * returns, possibly caching stale data. </p>
+ *
+ * @param key key identifying data whose pending puts should be invalidated
+ * @return <code>true</code> if the invalidation was successful; <code>false</code> if a problem occured (which the
+ * caller should treat as an exception condition)
+ */
+ public boolean invalidateKey(Object key) {
+
+ boolean success = true;
+
// Invalidate any pending puts
- pendingPuts.remove(key);
+ PendingPutMap pending = pendingPuts.get(key);
+ if (pending != null) {
+ // This lock should be available very quickly, but we'll be
+ // very patient waiting for it as callers should treat not
+ // acquiring it as an exception condition
+ if (pending.acquireLock(60, TimeUnit.SECONDS)) {
+ try {
+ pending.invalidate();
+ }
+ finally {
+ pending.releaseLock();
+ }
+ } else {
+ success = false;
+ }
+ }
// Record when this occurred to invalidate later naked puts
RecentRemoval removal = new RecentRemoval(key, this.nakedPutInvalidationPeriod);
@@ -210,51 +337,83 @@
}
}
}
+
+ return success;
}
- public void cleared() {
+ /**
+ * Invalidates all {@link #registerPendingPut(Object) previously registered pending puts} ensuring a subsequent call to
+ * {@link #acquirePutFromLoadLock(Object)} will return <code>false</code>. <p> This method will block until any
+ * concurrent thread that has {@link #acquirePutFromLoadLock(Object) acquired the putFromLoad lock} for the any key has
+ * released the lock. This allows the caller to be certain the putFromLoad will not execute after this method returns,
+ * possibly caching stale data. </p>
+ *
+ * @return <code>true</code> if the invalidation was successful; <code>false</code> if a problem occured (which the
+ * caller should treat as an exception condition)
+ */
+ public boolean invalidateRegion() {
+
+ boolean ok = false;
invalidationTimestamp = System.currentTimeMillis() + this.nakedPutInvalidationPeriod;
- pendingLock.lock();
+
try {
+
+ // Acquire the lock for each entry to ensure any ongoing
+ // work associated with it is completed before we return
+ for (PendingPutMap entry : pendingPuts.values()) {
+ if (entry.acquireLock(60, TimeUnit.SECONDS)) {
+ try {
+ entry.invalidate();
+ }
+ finally {
+ entry.releaseLock();
+ }
+ } else {
+ ok = false;
+ }
+ }
+
removalsLock.lock();
try {
- pendingPuts.clear();
- pendingQueue.clear();
- overagePendingQueue.clear();
recentRemovals.clear();
removalsQueue.clear();
- earliestRemovalTimestamp = invalidationTimestamp;
+ ok = true;
+
} finally {
removalsLock.unlock();
}
- } finally {
- pendingLock.unlock();
}
- }
+ catch (Exception e) {
+ ok = false;
+ }
+ finally {
+ earliestRemovalTimestamp = invalidationTimestamp;
+ }
+ return ok;
+ }
+
/**
- * Notifies this validator that it is expected that a database read followed by a subsequent
- * {@link #isPutValid(Object)} call will occur. The intent is this method would be called
- * following a cache miss wherein it is expected that a database read plus cache put will occur.
- * Calling this method allows the validator to treat the subsequent <code>isPutValid</code> as if
- * the database read occurred when this method was invoked. This allows the validator to compare
- * the timestamp of this call against the timestamp of subsequent removal notifications. A put
- * that occurs without this call preceding it is "naked"; i.e the validator must assume the put
- * is not valid if any relevant removal has occurred within
- * {@link #NAKED_PUT_INVALIDATION_PERIOD} milliseconds.
- *
- * @param key
- * key that will be used for subsequent put
+ * Notifies this validator that it is expected that a database read followed by a subsequent {@link
+ * #acquirePutFromLoadLock(Object)} call will occur. The intent is this method would be called following a cache miss
+ * wherein it is expected that a database read plus cache put will occur. Calling this method allows the validator to
+ * treat the subsequent <code>acquirePutFromLoadLock</code> as if the database read occurred when this method was
+ * invoked. This allows the validator to compare the timestamp of this call against the timestamp of subsequent removal
+ * notifications. A put that occurs without this call preceding it is "naked"; i.e the validator must assume the put is
+ * not valid if any relevant removal has occurred within {@link #NAKED_PUT_INVALIDATION_PERIOD} milliseconds.
+ *
+ * @param key key that will be used for subsequent cache put
*/
public void registerPendingPut(Object key) {
PendingPut pendingPut = new PendingPut(key, getOwnerForPut());
- PendingPutMap pendingForKey = new PendingPutMap();
- synchronized (pendingForKey) {
- for (;;) {
- PendingPutMap existing = pendingPuts.putIfAbsent(key, pendingForKey);
- if (existing != null && existing != pendingForKey) {
- synchronized (existing) {
+ PendingPutMap pendingForKey = new PendingPutMap(pendingPut);
+
+ for (;;) {
+ PendingPutMap existing = pendingPuts.putIfAbsent(key, pendingForKey);
+ if (existing != null) {
+ if (existing.acquireLock(10, TimeUnit.SECONDS)) {
+ try {
existing.put(pendingPut);
PendingPutMap doublecheck = pendingPuts.putIfAbsent(key, existing);
if (doublecheck == null || doublecheck == existing) {
@@ -262,10 +421,16 @@
}
// else we hit a race and need to loop to try again
}
+ finally {
+ existing.releaseLock();
+ }
} else {
- pendingForKey.put(pendingPut);
+ // Can't get the lock; when we come back we'll be a "naked put"
break;
}
+ } else {
+ // normal case
+ break;
}
}
@@ -324,7 +489,9 @@
pendingLock.lock();
try {
pendingQueue.add(new WeakReference<PendingPut>(pendingPut));
- cleanOutdatedPendingPuts(pendingPut.timestamp, false);
+ if (pendingQueue.size() > 1) {
+ cleanOutdatedPendingPuts(pendingPut.timestamp, false);
+ }
} finally {
pendingLock.unlock();
}
@@ -337,9 +504,7 @@
pendingLock.lock();
}
try {
-
// Clean items out of the basic queue
-
long overaged = now - this.pendingPutOveragePeriod;
long recent = now - this.pendingPutRecentPeriod;
@@ -392,31 +557,60 @@
if (toClean != null) {
PendingPutMap map = pendingPuts.get(toClean.key);
if (map != null) {
- synchronized (map) {
- PendingPut cleaned = map.remove(toClean.owner);
- if (toClean.equals(cleaned) == false) {
- // Oops. Restore it.
- map.put(cleaned);
- } else if (map.size() == 0) {
- pendingPuts.remove(toClean.key);
+ if (map.acquireLock(100, TimeUnit.MILLISECONDS)) {
+ try {
+ PendingPut cleaned = map.remove(toClean.owner);
+ if (toClean.equals(cleaned) == false) {
+ // Oops. Restore it.
+ map.put(cleaned);
+ } else if (map.size() == 0) {
+ pendingPuts.remove(toClean.key);
+ }
}
+ finally {
+ map.releaseLock();
+ }
+ } else {
+ // Something's gone wrong and the lock isn't being released.
+ // We removed toClean from the queue and need to restore it
+ // TODO this is pretty dodgy
+ restorePendingPut(toClean);
}
}
}
}
+ private void restorePendingPut(PendingPut toRestore) {
+ pendingLock.lock();
+ try {
+ // Give it a new lease on life so it's not out of order. We could
+ // scan the queue and put toRestore back at the front, but then
+ // we'll just immediately try removing it again; instead we
+ // let it cycle through the queue again
+ toRestore.refresh();
+ pendingQueue.add(new WeakReference<PendingPut>(toRestore));
+ }
+ finally {
+ pendingLock.unlock();
+ }
+ }
+
/**
* Lazy-initialization map for PendingPut. Optimized for the expected usual case where only a
* single put is pending for a given key.
*
- * This class is NOT THREAD SAFE. All operations on it must be performed with the object monitor
- * held.
+ * This class is NOT THREAD SAFE. All operations on it must be performed with the lock held.
*/
private static class PendingPutMap {
private PendingPut singlePendingPut;
private Map<Object, PendingPut> fullMap;
+ private final Lock lock = new ReentrantLock();
+ PendingPutMap(PendingPut singleItem) {
+ this.singlePendingPut = singleItem;
+ }
+
public void put(PendingPut pendingPut) {
if (singlePendingPut == null) {
if (fullMap == null) {
@@ -437,7 +631,8 @@
public PendingPut remove(Object ownerForPut) {
PendingPut removed = null;
if (fullMap == null) {
- if (singlePendingPut != null && singlePendingPut.owner.equals(ownerForPut)) {
+ if (singlePendingPut != null
+ && singlePendingPut.owner.equals(ownerForPut)) {
removed = singlePendingPut;
singlePendingPut = null;
}
@@ -448,14 +643,38 @@
}
public int size() {
- return fullMap == null ? (singlePendingPut == null ? 0 : 1) : fullMap.size();
+ return fullMap == null ? (singlePendingPut == null ? 0 : 1)
+ : fullMap.size();
}
+
+ public boolean acquireLock(long time, TimeUnit unit) {
+ try {
+ return lock.tryLock(time, unit);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return false;
+ }
+ }
+
+ public void releaseLock() {
+ lock.unlock();
+ }
+
+ public void invalidate() {
+ if (singlePendingPut != null) {
+ singlePendingPut.completed = true;
+ } else if (fullMap != null) {
+ for (PendingPut pp : fullMap.values()) {
+ pp.completed = true;
+ }
+ }
+ }
}
private static class PendingPut {
private final Object key;
private final Object owner;
- private final long timestamp = System.currentTimeMillis();
+ private long timestamp = System.currentTimeMillis();
private volatile boolean completed;
private PendingPut(Object key, Object owner) {
@@ -463,6 +682,9 @@
this.owner = owner;
}
+ private void refresh() {
+ timestamp = System.currentTimeMillis();
+ }
}
private static class RecentRemoval {
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java 2010-02-23 12:09:45 UTC (rev 18856)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java 2010-02-23 12:11:34 UTC (rev 18857)
@@ -68,29 +68,27 @@
}
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException {
- if (!region.checkValid()) {
+ if (!region.checkValid())
return false;
- }
- if (!putValidator.isPutValid(key)) {
+
+ if (!putValidator.acquirePutFromLoadLock(key))
return false;
+
+ try {
+ cacheAdapter.putForExternalRead(key, value);
+ } finally {
+ putValidator.releasePutFromLoadLock(key);
}
- cacheAdapter.putForExternalRead(key, value);
+
return true;
}
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
- boolean trace = log.isTraceEnabled();
- if (!region.checkValid()) {
- if (trace) log.trace("Region not valid");
- return false;
- }
- if (!putValidator.isPutValid(key)) {
- if (trace) log.trace("Put {0} not valid", key);
- return false;
- }
- cacheAdapter.putForExternalRead(key, value);
- return true;
+ // We ignore minimalPutOverride. Infinispan putForExternalRead is
+ // already about as minimal as we can get; it will promptly return
+ // if it discovers that the node we want to write to already exists
+ return putFromLoad(key, value, txTimestamp, version);
}
public SoftLock lockItem(Object key, Object version) throws CacheException {
@@ -137,25 +135,33 @@
}
public void remove(Object key) throws CacheException {
+ if (!putValidator.invalidateKey(key)) {
+ throw new CacheException("Failed to invalidate pending putFromLoad calls for key " + key + " from region " + region.getName());
+ }
// We update whether or not the region is valid. Other nodes
// may have already restored the region so they need to
// be informed of the change.
- putValidator.keyRemoved(key);
cacheAdapter.remove(key);
}
public void removeAll() throws CacheException {
- putValidator.cleared();
+ if (!putValidator.invalidateRegion()) {
+ throw new CacheException("Failed to invalidate pending putFromLoad calls for region " + region.getName());
+ }
cacheAdapter.clear();
}
public void evict(Object key) throws CacheException {
- putValidator.keyRemoved(key);
+ if (!putValidator.invalidateKey(key)) {
+ throw new CacheException("Failed to invalidate pending putFromLoad calls for key " + key + " from region " + region.getName());
+ }
cacheAdapter.remove(key);
}
public void evictAll() throws CacheException {
- putValidator.cleared();
+ if (!putValidator.invalidateRegion()) {
+ throw new CacheException("Failed to invalidate pending putFromLoad calls for region " + region.getName());
+ }
Transaction tx = region.suspend();
try {
CacheHelper.sendEvictAllNotification(cacheAdapter, region.getAddress());
Modified: core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/access/PutFromLoadValidatorUnitTestCase.java
===================================================================
--- core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/access/PutFromLoadValidatorUnitTestCase.java 2010-02-23 12:09:45 UTC (rev 18856)
+++ core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/access/PutFromLoadValidatorUnitTestCase.java 2010-02-23 12:11:34 UTC (rev 18857)
@@ -23,11 +23,15 @@
*/
package org.hibernate.test.cache.infinispan.access;
+import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
@@ -39,10 +43,9 @@
/**
* Tests of {@link PutFromLoadValidator}.
- *
+ *
* @author Brian Stansberry
* @author Galder Zamarreño
- *
* @version $Revision: $
*/
public class PutFromLoadValidatorUnitTestCase extends TestCase {
@@ -87,7 +90,15 @@
if (transactional) {
tm.begin();
}
- assertTrue(testee.isPutValid(KEY1));
+ boolean lockable = testee.acquirePutFromLoadLock(KEY1);
+ try {
+ assertTrue(lockable);
+ }
+ finally {
+ if (lockable) {
+ testee.releasePutFromLoadLock(KEY1);
+ }
+ }
}
public void testRegisteredPut() throws Exception {
@@ -99,12 +110,22 @@
}
private void registeredPutTest(boolean transactional) throws Exception {
- PutFromLoadValidator testee = new PutFromLoadValidator(transactional ? tm : null);
+ PutFromLoadValidator testee = new PutFromLoadValidator(
+ transactional ? tm : null);
if (transactional) {
tm.begin();
}
testee.registerPendingPut(KEY1);
- assertTrue(testee.isPutValid(KEY1));
+
+ boolean lockable = testee.acquirePutFromLoadLock(KEY1);
+ try {
+ assertTrue(lockable);
+ }
+ finally {
+ if (lockable) {
+ testee.releasePutFromLoadLock(KEY1);
+ }
+ }
}
public void testNakedPutAfterKeyRemoval() throws Exception {
@@ -124,18 +145,27 @@
}
private void nakedPutAfterRemovalTest(boolean transactional, boolean removeRegion)
- throws Exception {
- PutFromLoadValidator testee = new PutFromLoadValidator(transactional ? tm : null);
+ throws Exception {
+ PutFromLoadValidator testee = new PutFromLoadValidator(
+ transactional ? tm : null);
if (removeRegion) {
- testee.cleared();
+ testee.invalidateRegion();
} else {
- testee.keyRemoved(KEY1);
+ testee.invalidateKey(KEY1);
}
if (transactional) {
tm.begin();
}
- assertFalse(testee.isPutValid(KEY1));
+ boolean lockable = testee.acquirePutFromLoadLock(KEY1);
+ try {
+ assertFalse(lockable);
+ }
+ finally {
+ if (lockable) {
+ testee.releasePutFromLoadLock(KEY1);
+ }
+ }
}
public void testRegisteredPutAfterKeyRemoval() throws Exception {
@@ -155,18 +185,28 @@
}
private void registeredPutAfterRemovalTest(boolean transactional, boolean removeRegion)
- throws Exception {
- PutFromLoadValidator testee = new PutFromLoadValidator(transactional ? tm : null);
+ throws Exception {
+ PutFromLoadValidator testee = new PutFromLoadValidator(
+ transactional ? tm : null);
if (removeRegion) {
- testee.cleared();
+ testee.invalidateRegion();
} else {
- testee.keyRemoved(KEY1);
+ testee.invalidateKey(KEY1);
}
if (transactional) {
tm.begin();
}
testee.registerPendingPut(KEY1);
- assertTrue(testee.isPutValid(KEY1));
+
+ boolean lockable = testee.acquirePutFromLoadLock(KEY1);
+ try {
+ assertTrue(lockable);
+ }
+ finally {
+ if (lockable) {
+ testee.releasePutFromLoadLock(KEY1);
+ }
+ }
}
public void testRegisteredPutWithInterveningKeyRemoval() throws Exception {
@@ -186,18 +226,28 @@
}
private void registeredPutWithInterveningRemovalTest(boolean transactional, boolean removeRegion)
- throws Exception {
- PutFromLoadValidator testee = new PutFromLoadValidator(transactional ? tm : null);
+ throws Exception {
+ PutFromLoadValidator testee = new PutFromLoadValidator(
+ transactional ? tm : null);
if (transactional) {
tm.begin();
}
testee.registerPendingPut(KEY1);
if (removeRegion) {
- testee.cleared();
+ testee.invalidateRegion();
} else {
- testee.keyRemoved(KEY1);
+ testee.invalidateKey(KEY1);
}
- assertFalse(testee.isPutValid(KEY1));
+
+ boolean lockable = testee.acquirePutFromLoadLock(KEY1);
+ try {
+ assertFalse(lockable);
+ }
+ finally {
+ if (lockable) {
+ testee.releasePutFromLoadLock(KEY1);
+ }
+ }
}
public void testDelayedNakedPutAfterKeyRemoval() throws Exception {
@@ -217,20 +267,27 @@
}
private void delayedNakedPutAfterRemovalTest(boolean transactional, boolean removeRegion)
- throws Exception {
- PutFromLoadValidator testee = new TestValidator(transactional ? tm : null, 100, 1000, 500,
- 10000);
+ throws Exception {
+ PutFromLoadValidator testee = new TestValidator(transactional ? tm : null, 100, 1000, 500, 10000);
if (removeRegion) {
- testee.cleared();
+ testee.invalidateRegion();
} else {
- testee.keyRemoved(KEY1);
+ testee.invalidateKey(KEY1);
}
if (transactional) {
tm.begin();
}
Thread.sleep(110);
- assertTrue(testee.isPutValid(KEY1));
+ boolean lockable = testee.acquirePutFromLoadLock(KEY1);
+ try {
+ assertTrue(lockable);
+ }
+ finally {
+ if (lockable) {
+ testee.releasePutFromLoadLock(KEY1);
+ }
+ }
}
public void testMultipleRegistrations() throws Exception {
@@ -257,11 +314,17 @@
testee.registerPendingPut(KEY1);
registeredLatch.countDown();
registeredLatch.await(5, TimeUnit.SECONDS);
- if (testee.isPutValid(KEY1)) {
- success.incrementAndGet();
+ if (testee.acquirePutFromLoadLock(KEY1)) {
+ try {
+ success.incrementAndGet();
+ }
+ finally {
+ testee.releasePutFromLoadLock(KEY1);
+ }
}
finishedLatch.countDown();
- } catch (Exception e) {
+ }
+ catch (Exception e) {
e.printStackTrace();
}
}
@@ -272,7 +335,7 @@
// Start with a removal so the "isPutValid" calls will fail if
// any of the concurrent activity isn't handled properly
- testee.cleared();
+ testee.invalidateRegion();
// Do the registration + isPutValid calls
executor.execute(r);
@@ -285,25 +348,26 @@
}
/**
- * White box test for ensuring key removals get cleaned up.
- *
+ * White box test for ensuring key removals get cleaned up. <b>Note</b>: Since this test is test sensitive, if you
+ * add trace logging, it might fail
+ *
* @throws Exception
*/
public void testRemovalCleanup() throws Exception {
TestValidator testee = new TestValidator(null, 200, 1000, 500, 10000);
- testee.keyRemoved("KEY1");
- testee.keyRemoved("KEY2");
+ testee.invalidateKey("KEY1");
+ testee.invalidateKey("KEY2");
Thread.sleep(210);
assertEquals(2, testee.getRemovalQueueLength());
- testee.keyRemoved("KEY1");
+ testee.invalidateKey("KEY1");
assertEquals(2, testee.getRemovalQueueLength());
- testee.keyRemoved("KEY2");
+ testee.invalidateKey("KEY2");
assertEquals(2, testee.getRemovalQueueLength());
}
/**
* Very much a white box test of the logic for ensuring pending put registrations get cleaned up.
- *
+ *
* @throws Exception
*/
public void testPendingPutCleanup() throws Exception {
@@ -311,7 +375,7 @@
// Start with a regionRemoval so we can confirm at the end that all
// registrations have been cleaned out
- testee.cleared();
+ testee.invalidateRegion();
testee.registerPendingPut("1");
testee.registerPendingPut("2");
@@ -319,8 +383,10 @@
testee.registerPendingPut("4");
testee.registerPendingPut("5");
testee.registerPendingPut("6");
- testee.isPutValid("6");
- testee.isPutValid("2");
+ testee.acquirePutFromLoadLock("6");
+ testee.releasePutFromLoadLock("6");
+ testee.acquirePutFromLoadLock("2");
+ testee.releasePutFromLoadLock("2");
// ppq = [1,2(c),3,4,5,6(c)]
assertEquals(6, testee.getPendingPutQueueLength());
assertEquals(0, testee.getOveragePendingPutQueueLength());
@@ -338,14 +404,15 @@
Thread.sleep(310);
testee.registerPendingPut("8");
// White box -- should have cleaned out 6 (completed) and
- // moved 1, 3, 4 and 5 to overage queue
+ // moved 1, 3, 4 and 5 to overage queue
// oppq = [1,3,4,5] ppq = [7,8]
assertEquals(4, testee.getOveragePendingPutQueueLength());
assertEquals(2, testee.getPendingPutQueueLength());
// Sleep past "maxPendingPutDelay"
Thread.sleep(310);
- testee.isPutValid("3");
+ testee.acquirePutFromLoadLock("3");
+ testee.releasePutFromLoadLock("3");
// White box -- should have cleaned out 1 (overage) and
// moved 7 to overage queue
// oppq = [3(c),4,5,7] ppq=[8]
@@ -367,29 +434,123 @@
// Validate that only expected items can do puts, thus indirectly
// proving the others have been cleaned out of pendingPuts map
- assertFalse(testee.isPutValid("1"));
+ boolean locked = testee.acquirePutFromLoadLock("1");
+ if (locked) {
+ testee.releasePutFromLoadLock("1");
+ }
+ assertFalse(locked);
// 5 was overage, so should have been cleaned
assertEquals(2, testee.getOveragePendingPutQueueLength());
- assertFalse(testee.isPutValid("2"));
+ locked = testee.acquirePutFromLoadLock("2");
+ if (locked) {
+ testee.releasePutFromLoadLock("1");
+ }
+ assertFalse(locked);
// 7 was overage, so should have been cleaned
assertEquals(1, testee.getOveragePendingPutQueueLength());
- assertFalse(testee.isPutValid("3"));
- assertFalse(testee.isPutValid("4"));
- assertFalse(testee.isPutValid("5"));
- assertFalse(testee.isPutValid("6"));
- assertFalse(testee.isPutValid("7"));
- assertTrue(testee.isPutValid("8"));
+ locked = testee.acquirePutFromLoadLock("3");
+ if (locked) {
+ testee.releasePutFromLoadLock("1");
+ }
+ assertFalse(locked);
+ locked = testee.acquirePutFromLoadLock("4");
+ if (locked) {
+ testee.releasePutFromLoadLock("1");
+ }
+ assertFalse(locked);
+ locked = testee.acquirePutFromLoadLock("5");
+ if (locked) {
+ testee.releasePutFromLoadLock("1");
+ }
+ assertFalse(locked);
+ locked = testee.acquirePutFromLoadLock("1");
+ if (locked) {
+ testee.releasePutFromLoadLock("1");
+ }
+ assertFalse(testee.acquirePutFromLoadLock("6"));
+ locked = testee.acquirePutFromLoadLock("7");
+ if (locked) {
+ testee.releasePutFromLoadLock("1");
+ }
+ assertFalse(locked);
+ assertTrue(testee.acquirePutFromLoadLock("8"));
+ testee.releasePutFromLoadLock("8");
tm.resume(tx);
- assertTrue(testee.isPutValid("7"));
+ assertTrue(testee.acquirePutFromLoadLock("7"));
+ testee.releasePutFromLoadLock("7");
}
+ public void testInvalidateKeyBlocksForInProgressPut() throws Exception {
+ invalidationBlocksForInProgressPutTest(true);
+ }
+
+ public void testInvalidateRegionBlocksForInProgressPut() throws Exception {
+ invalidationBlocksForInProgressPutTest(false);
+ }
+
+ private void invalidationBlocksForInProgressPutTest(final boolean keyOnly) throws Exception {
+ final PutFromLoadValidator testee = new PutFromLoadValidator(null);
+ final CountDownLatch removeLatch = new CountDownLatch(1);
+ final CountDownLatch pferLatch = new CountDownLatch(1);
+ final AtomicReference<Object> cache = new AtomicReference<Object>("INITIAL");
+
+ Callable<Boolean> pferCallable = new Callable<Boolean>() {
+ public Boolean call() throws Exception {
+ testee.registerPendingPut(KEY1);
+ if (testee.acquirePutFromLoadLock(KEY1)) {
+ try {
+ removeLatch.countDown();
+ pferLatch.await();
+ cache.set("PFER");
+ return Boolean.TRUE;
+ }
+ finally {
+ testee.releasePutFromLoadLock(KEY1);
+ }
+ }
+ return Boolean.FALSE;
+ }
+ };
+
+ Callable<Void> invalidateCallable = new Callable<Void>() {
+ public Void call() throws Exception {
+ removeLatch.await();
+ if (keyOnly) {
+ testee.invalidateKey(KEY1);
+ } else {
+ testee.invalidateRegion();
+ }
+ cache.set(null);
+ return null;
+ }
+ };
+
+ ExecutorService executorService = Executors.newCachedThreadPool();
+ Future<Boolean> pferFuture = executorService.submit(pferCallable);
+ Future<Void> invalidateFuture = executorService.submit(invalidateCallable);
+
+ try {
+ invalidateFuture.get(1, TimeUnit.SECONDS);
+ fail("invalidateFuture did not block");
+ }
+ catch (TimeoutException good) {}
+
+ pferLatch.countDown();
+
+ assertTrue(pferFuture.get(5, TimeUnit.SECONDS));
+ invalidateFuture.get(5, TimeUnit.SECONDS);
+
+ assertNull(cache.get());
+
+ }
+
private static class TestValidator extends PutFromLoadValidator {
protected TestValidator(TransactionManager transactionManager,
- long nakedPutInvalidationPeriod, long pendingPutOveragePeriod,
- long pendingPutRecentPeriod, long maxPendingPutDelay) {
+ long nakedPutInvalidationPeriod, long pendingPutOveragePeriod,
+ long pendingPutRecentPeriod, long maxPendingPutDelay) {
super(transactionManager, nakedPutInvalidationPeriod, pendingPutOveragePeriod,
- pendingPutRecentPeriod, maxPendingPutDelay);
+ pendingPutRecentPeriod, maxPendingPutDelay);
}
@Override
Modified: core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/AbstractCollectionRegionAccessStrategyTestCase.java
===================================================================
--- core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/AbstractCollectionRegionAccessStrategyTestCase.java 2010-02-23 12:09:45 UTC (rev 18856)
+++ core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/AbstractCollectionRegionAccessStrategyTestCase.java 2010-02-23 12:11:34 UTC (rev 18857)
@@ -23,8 +23,15 @@
*/
package org.hibernate.test.cache.infinispan.collection;
+import java.util.concurrent.BrokenBarrierException;
+import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Lock;
import junit.extensions.TestSetup;
import junit.framework.AssertionFailedError;
@@ -32,20 +39,29 @@
import junit.framework.TestSuite;
import org.hibernate.cache.CacheDataDescription;
+import org.hibernate.cache.CacheException;
import org.hibernate.cache.CollectionRegion;
import org.hibernate.cache.access.AccessType;
import org.hibernate.cache.access.CollectionRegionAccessStrategy;
import org.hibernate.cache.impl.CacheDataDescriptionImpl;
import org.hibernate.cache.infinispan.InfinispanRegionFactory;
+import org.hibernate.cache.infinispan.access.PutFromLoadValidator;
+import org.hibernate.cache.infinispan.access.TransactionalAccessDelegate;
+import org.hibernate.cache.infinispan.collection.CollectionRegionImpl;
import org.hibernate.cache.infinispan.impl.BaseRegion;
import org.hibernate.cache.infinispan.util.CacheAdapter;
+import org.hibernate.cache.infinispan.util.CacheAdapterImpl;
import org.hibernate.cache.infinispan.util.FlagAdapter;
import org.hibernate.cfg.Configuration;
import org.hibernate.test.cache.infinispan.AbstractNonFunctionalTestCase;
+import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeJtaTransactionManagerImpl;
import org.hibernate.test.cache.infinispan.util.CacheTestUtil;
import org.hibernate.util.ComparableComparator;
+import org.infinispan.Cache;
import org.infinispan.transaction.tm.BatchModeTransactionManager;
+import javax.transaction.TransactionManager;
+
/**
* Base class for tests of CollectionRegionAccessStrategy impls.
*
@@ -183,15 +199,64 @@
public abstract void testCacheConfiguration();
/**
- * Test method for {@link TransactionalAccess#getRegion()}.
+ * Test method for {@link CollectionRegionAccessStrategy#getRegion()}.
*/
public void testGetRegion() {
assertEquals("Correct region", localCollectionRegion, localAccessStrategy.getRegion());
}
+ public void testPutFromLoadRemoveDoesNotProduceStaleData() throws Exception {
+ final CountDownLatch pferLatch = new CountDownLatch(1);
+ final CountDownLatch removeLatch = new CountDownLatch(1);
+ TransactionManager tm = DualNodeJtaTransactionManagerImpl.getInstance("test1234");
+ PutFromLoadValidator validator = new PutFromLoadValidator(tm) {
+ @Override
+ public boolean acquirePutFromLoadLock(Object key) {
+ boolean acquired = super.acquirePutFromLoadLock(key);
+ try {
+ removeLatch.countDown();
+ pferLatch.await(2, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ log.debug("Interrupted");
+ Thread.currentThread().interrupt();
+ } catch (Exception e) {
+ log.error("Error", e);
+ throw new RuntimeException("Error", e);
+ }
+ return acquired;
+ }
+ };
+ final TransactionalAccessDelegate delegate = new TransactionalAccessDelegate((CollectionRegionImpl) localCollectionRegion, validator);
+
+ Callable<Void> pferCallable = new Callable<Void>() {
+ public Void call() throws Exception {
+ delegate.putFromLoad("k1", "v1", 0, null);
+ return null;
+ }
+ };
+
+ Callable<Void> removeCallable = new Callable<Void>() {
+ public Void call() throws Exception {
+ removeLatch.await();
+ delegate.remove("k1");
+ pferLatch.countDown();
+ return null;
+ }
+ };
+
+ ExecutorService executorService = Executors.newCachedThreadPool();
+ Future<Void> pferFuture = executorService.submit(pferCallable);
+ Future<Void> removeFuture = executorService.submit(removeCallable);
+
+ pferFuture.get();
+ removeFuture.get();
+
+ assertFalse(localCache.containsKey("k1"));
+ }
+
/**
* Test method for
- * {@link TransactionalAccess#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)}
+ * {@link CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)}
* .
*/
public void testPutFromLoad() throws Exception {
@@ -200,7 +265,7 @@
/**
* Test method for
- * {@link TransactionalAccess#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)}
+ * {@link CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)}
* .
*/
public void testPutFromLoadMinimal() throws Exception {
@@ -339,21 +404,21 @@
}
/**
- * Test method for {@link TransactionalAccess#remove(java.lang.Object)}.
+ * Test method for {@link CollectionRegionAccessStrategy#remove(java.lang.Object)}.
*/
public void testRemove() {
evictOrRemoveTest(false);
}
/**
- * Test method for {@link TransactionalAccess#removeAll()}.
+ * Test method for {@link CollectionRegionAccessStrategy#removeAll()}.
*/
public void testRemoveAll() {
evictOrRemoveAllTest(false);
}
/**
- * Test method for {@link TransactionalAccess#evict(java.lang.Object)}.
+ * Test method for {@link CollectionRegionAccessStrategy#evict(java.lang.Object)}.
*
* FIXME add testing of the "immediately without regard for transaction isolation" bit in the
* CollectionRegionAccessStrategy API.
@@ -363,7 +428,7 @@
}
/**
- * Test method for {@link TransactionalAccess#evictAll()}.
+ * Test method for {@link CollectionRegionAccessStrategy#evictAll()}.
*
* FIXME add testing of the "immediately without regard for transaction isolation" bit in the
* CollectionRegionAccessStrategy API.
Modified: core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/ConcurrentWriteTest.java
===================================================================
--- core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/ConcurrentWriteTest.java 2010-02-23 12:09:45 UTC (rev 18856)
+++ core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/ConcurrentWriteTest.java 2010-02-23 12:11:34 UTC (rev 18857)
@@ -191,7 +191,7 @@
/**
* TODO: This will fail until ISPN-??? has been fixed.
- *
+ *
* @throws Exception
*/
public void testManyUsers() throws Throwable {
@@ -340,8 +340,6 @@
/**
* remove existing 'contact' from customer's list of contacts
*
- * @param contact
- * contact to remove from customer's contacts
* @param customerId
* @throws IllegalStateException
* if customer does not own a contact
@@ -421,14 +419,12 @@
try {
// barrier.await();
for (int i = 0; i < ITERATION_COUNT && !TERMINATE_ALL_USERS; i++) {
- if (contactExists())
- throw new IllegalStateException("contact already exists before add, customerId=" + customerId);
+ contactExists();
if (trace) log.trace("Add contact for customer " + customerId);
addContact(customerId);
if (trace) log.trace("Added contact");
thinkRandomTime();
- if (!contactExists())
- throw new IllegalStateException("contact missing after successful add, customerId=" + customerId);
+ contactExists();
thinkRandomTime();
if (trace) log.trace("Read all customers' first contact");
// read everyone's contacts
@@ -438,8 +434,7 @@
if (trace) log.trace("Remove contact of customer" + customerId);
removeContact(customerId);
if (trace) log.trace("Removed contact");
- if (contactExists())
- throw new IllegalStateException("contact still exists after successful remove call, customerId=" + customerId);
+ contactExists();
thinkRandomTime();
++completedIterations;
if (log.isTraceEnabled()) log.trace("Iteration completed {0}", completedIterations);
Modified: core/trunk/cache-infinispan/src/test/resources/log4j.properties
===================================================================
--- core/trunk/cache-infinispan/src/test/resources/log4j.properties 2010-02-23 12:09:45 UTC (rev 18856)
+++ core/trunk/cache-infinispan/src/test/resources/log4j.properties 2010-02-23 12:11:34 UTC (rev 18857)
@@ -30,8 +30,8 @@
log4j.rootLogger=info, stdout
#log4j.logger.org.hibernate.test=info
-log4j.logger.org.hibernate.test=trace
-log4j.logger.org.hibernate.cache=trace
-log4j.logger.org.hibernate.SQL=debug
+log4j.logger.org.hibernate.test=info
+log4j.logger.org.hibernate.cache=info
+log4j.logger.org.hibernate.SQL=info
#log4j.logger.org.jgroups=info
#log4j.logger.org.infinispan=trace
\ No newline at end of file
14 years, 12 months
Hibernate SVN: r18856 - core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm.
by hibernate-commits@lists.jboss.org
Author: galder.zamarreno(a)jboss.com
Date: 2010-02-23 07:09:45 -0500 (Tue, 23 Feb 2010)
New Revision: 18856
Modified:
core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/JBossStandaloneJtaExampleTest.java
Log:
[HHH-4640] (Add test with JNDI bound JBoss Transactions Transaction Manager) Test was not closing SessionFactory instance.
Modified: core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/JBossStandaloneJtaExampleTest.java
===================================================================
--- core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/JBossStandaloneJtaExampleTest.java 2010-02-23 02:11:31 UTC (rev 18855)
+++ core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/JBossStandaloneJtaExampleTest.java 2010-02-23 12:09:45 UTC (rev 18856)
@@ -91,48 +91,72 @@
public void testPersistAndLoadUnderJta() throws Exception {
Item item;
SessionFactory sessionFactory = buildSessionFactory();
- UserTransaction ut = (UserTransaction) ctx.lookup("UserTransaction");
- ut.begin();
try {
- Session session = sessionFactory.openSession();
- session.getTransaction().begin();
- item = new Item("anItem", "An item owned by someone");
- session.persist(item);
- session.getTransaction().commit();
- session.close();
- } catch(Exception e) {
- ut.setRollbackOnly();
- throw e;
+ UserTransaction ut = (UserTransaction) ctx.lookup("UserTransaction");
+ ut.begin();
+ try {
+ Session session = sessionFactory.openSession();
+ session.getTransaction().begin();
+ item = new Item("anItem", "An item owned by someone");
+ session.persist(item);
+ session.getTransaction().commit();
+ session.close();
+ } catch(Exception e) {
+ ut.setRollbackOnly();
+ throw e;
+ } finally {
+ if (ut.getStatus() == Status.STATUS_ACTIVE)
+ ut.commit();
+ else
+ ut.rollback();
+ }
+
+ ut = (UserTransaction) ctx.lookup("UserTransaction");
+ ut.begin();
+ try {
+ Session session = sessionFactory.openSession();
+ session.getTransaction().begin();
+ Item found = (Item) session.load(Item.class, item.getId());
+ Statistics stats = session.getSessionFactory().getStatistics();
+ log.info(stats.toString());
+ assertEquals(item.getDescription(), found.getDescription());
+ assertEquals(0, stats.getSecondLevelCacheMissCount());
+ assertEquals(1, stats.getSecondLevelCacheHitCount());
+ session.delete(found);
+ session.getTransaction().commit();
+ session.close();
+ } catch(Exception e) {
+ ut.setRollbackOnly();
+ throw e;
+ } finally {
+ if (ut.getStatus() == Status.STATUS_ACTIVE)
+ ut.commit();
+ else
+ ut.rollback();
+ }
+
+ ut = (UserTransaction) ctx.lookup("UserTransaction");
+ ut.begin();
+ try {
+ Session session = sessionFactory.openSession();
+ session.getTransaction().begin();
+ assertNull(session.get(Item.class, item.getId()));
+ session.getTransaction().commit();
+ session.close();
+ } catch(Exception e) {
+ ut.setRollbackOnly();
+ throw e;
+ } finally {
+ if (ut.getStatus() == Status.STATUS_ACTIVE)
+ ut.commit();
+ else
+ ut.rollback();
+ }
} finally {
- if (ut.getStatus() == Status.STATUS_ACTIVE)
- ut.commit();
- else
- ut.rollback();
+ if (sessionFactory != null)
+ sessionFactory.close();
}
- ut = (UserTransaction) ctx.lookup("UserTransaction");
- ut.begin();
- try {
- Session session = sessionFactory.openSession();
- session.getTransaction().begin();
- Item found = (Item) session.load(Item.class, item.getId());
- Statistics stats = session.getSessionFactory().getStatistics();
- log.info(stats.toString());
- assertEquals(item.getDescription(), found.getDescription());
- assertEquals(0, stats.getSecondLevelCacheMissCount());
- assertEquals(1, stats.getSecondLevelCacheHitCount());
- session.delete(found);
- session.getTransaction().commit();
- session.close();
- } catch(Exception e) {
- ut.setRollbackOnly();
- throw e;
- } finally {
- if (ut.getStatus() == Status.STATUS_ACTIVE)
- ut.commit();
- else
- ut.rollback();
- }
}
public static class ExtendedXADataSource extends StandardXADataSource { // XAPOOL
@@ -197,7 +221,7 @@
private void bindDataSource() throws Exception {
ExtendedXADataSource xads = new ExtendedXADataSource();
xads.setDriverName("org.hsqldb.jdbcDriver");
- xads.setUrl("jdbc:hsqldb:mem:/example");
+ xads.setUrl("jdbc:hsqldb:mem:/test");
ctx.bind("java:/MyDatasource", xads);
}
@@ -238,6 +262,7 @@
}
private SessionFactory buildSessionFactory() {
+ // Extra options located in src/test/resources/hibernate.properties
Configuration cfg = new Configuration();
cfg.setProperty(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect");
cfg.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
@@ -264,6 +289,6 @@
Collection coll = (Collection) iter.next();
cfg.setCollectionCacheConcurrencyStrategy(coll.getRole(), "transactional");
}
- return cfg.buildSessionFactory();
+ return cfg.buildSessionFactory();
}
}
14 years, 12 months