Unify Batch and HQL test models

This commit is contained in:
Vlad Mihalcea 2016-02-04 11:36:33 +02:00
parent 9b60354e3e
commit 20b446b0ec
4 changed files with 110 additions and 117 deletions

View File

@ -13,6 +13,36 @@ Criteria queries offer a type-safe approach to querying. See <<chapters/query-c
[[query-api]] [[query-api]]
=== Query API === Query API
[[hql-examples-domain-model]]
=== Examples domain model
To better understand the further HQL and JPQL examples, it's time to familiarize the domain model entities that are used in all the examples features in this chapter.
[[hql-examples-domain-model-example]]
.Examples domain model
====
[source, JAVA, indent=0]
----
include::{sourcedir}/Person.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/AddressType.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/Partner.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/Phone.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/PhoneType.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/Call.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/Payment.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/CreditCardPayment.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/WireTransferPayment.java[tags=hql-examples-domain-model-example]
----
====
[[jpql-api]] [[jpql-api]]
=== JPA Query API === JPA Query API
@ -310,34 +340,6 @@ The `Iterator` returned from `Query#iterate` is actually a specially typed Itera
It is specialized to expose a `close()` method (again, inherited from `java.io.Closeable`). It is specialized to expose a `close()` method (again, inherited from `java.io.Closeable`).
When you are done with this `Iterator` you should close it, either by casting to `HibernateIterator` or `Closeable`, or by calling http://docs.jboss.org/hibernate/stable/core/javadocs/org/hibernate/Hibernate.html#close%28java.util.Iterator%29[`Hibernate.html#close(java.util.Iterator)`]. When you are done with this `Iterator` you should close it, either by casting to `HibernateIterator` or `Closeable`, or by calling http://docs.jboss.org/hibernate/stable/core/javadocs/org/hibernate/Hibernate.html#close%28java.util.Iterator%29[`Hibernate.html#close(java.util.Iterator)`].
[[hql-examples-domain-model]]
=== Examples domain model
To better understand the further HQL and JPQL examples, it's time to familiarize the domain model entities that are used in all the examples features in this chapter.
[[hql-examples-domain-model-example]]
.Examples domain model
====
[source, JAVA, indent=0]
----
include::{sourcedir}/Person.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/AddressType.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/Phone.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/PhoneType.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/Call.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/Payment.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/CreditCardPayment.java[tags=hql-examples-domain-model-example]
include::{sourcedir}/WireTransferPayment.java[tags=hql-examples-domain-model-example]
----
====
[[hql-case-sensitivity]] [[hql-case-sensitivity]]
=== Case Sensitivity === Case Sensitivity
@ -990,12 +992,10 @@ LOCATE::
Locates a string within another string. Locates a string within another string.
The third argument (optional) is used to denote a position from which to start looking. The third argument (optional) is used to denote a position from which to start looking.
[source, JAVA, indent=0] [source, JAVA, indent=0]
---- ----
locate( string_expression, string_expression[, numeric_expression] ) locate( string_expression, string_expression[, numeric_expression] )
---- ----
====
ABS:: ABS::
Calculates the mathematical absolute value of a numeric value. Calculates the mathematical absolute value of a numeric value.

View File

@ -6,12 +6,8 @@
*/ */
package org.hibernate.userguide.batch; package org.hibernate.userguide.batch;
import javax.persistence.Entity;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction; import javax.persistence.EntityTransaction;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Version;
import org.hibernate.CacheMode; import org.hibernate.CacheMode;
import org.hibernate.ScrollMode; import org.hibernate.ScrollMode;
@ -22,6 +18,10 @@ import org.hibernate.StatelessSession;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase; import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.resource.transaction.spi.TransactionStatus; import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.hibernate.userguide.hql.Call;
import org.hibernate.userguide.hql.Partner;
import org.hibernate.userguide.hql.Person;
import org.hibernate.userguide.hql.Phone;
import org.junit.Test; import org.junit.Test;
@ -40,7 +40,9 @@ public class BatchTest extends BaseEntityManagerFunctionalTestCase {
@Override @Override
protected Class<?>[] getAnnotatedClasses() { protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] { return new Class<?>[] {
Customer.class, Person.class,
Phone.class,
Call.class,
Partner.class Partner.class
}; };
} }
@ -58,17 +60,17 @@ public class BatchTest extends BaseEntityManagerFunctionalTestCase {
@Test @Test
public void testBulk() { public void testBulk() {
doInJPA( this::entityManagerFactory, entityManager -> { doInJPA( this::entityManagerFactory, entityManager -> {
entityManager.persist( new Customer( "Vlad" ) ); entityManager.persist( new Person( "Vlad" ) );
entityManager.persist( new Customer( "Mihalcea" ) ); entityManager.persist( new Person( "Mihalcea" ) );
} ); } );
doInJPA( this::entityManagerFactory, entityManager -> { doInJPA( this::entityManagerFactory, entityManager -> {
String oldName = "Vlad"; String oldName = "Vlad";
String newName = "Alexandru"; String newName = "Alexandru";
//tag::batch-bulk-jpql-update-example[] //tag::batch-bulk-jpql-update-example[]
int updatedEntities = entityManager.createQuery( int updatedEntities = entityManager.createQuery(
"update Customer c " + "update Person p " +
"set c.name = :newName " + "set p.name = :newName " +
"where c.name = :oldName" ) "where p.name = :oldName" )
.setParameter( "oldName", oldName ) .setParameter( "oldName", oldName )
.setParameter( "newName", newName ) .setParameter( "newName", newName )
.executeUpdate(); .executeUpdate();
@ -83,7 +85,7 @@ public class BatchTest extends BaseEntityManagerFunctionalTestCase {
Session session = entityManager.unwrap( Session.class ); Session session = entityManager.unwrap( Session.class );
//tag::batch-bulk-hql-update-example[] //tag::batch-bulk-hql-update-example[]
int updatedEntities = session.createQuery( int updatedEntities = session.createQuery(
"update Customer " + "update Person " +
"set name = :newName " + "set name = :newName " +
"where name = :oldName" ) "where name = :oldName" )
.setParameter( "oldName", oldName ) .setParameter( "oldName", oldName )
@ -100,7 +102,7 @@ public class BatchTest extends BaseEntityManagerFunctionalTestCase {
Session session = entityManager.unwrap( Session.class ); Session session = entityManager.unwrap( Session.class );
//tag::batch-bulk-hql-update-version-example[] //tag::batch-bulk-hql-update-version-example[]
int updatedEntities = session.createQuery( int updatedEntities = session.createQuery(
"update versioned Customer " + "update versioned Person " +
"set name = :newName " + "set name = :newName " +
"where name = :oldName" ) "where name = :oldName" )
.setParameter( "oldName", oldName ) .setParameter( "oldName", oldName )
@ -115,8 +117,8 @@ public class BatchTest extends BaseEntityManagerFunctionalTestCase {
//tag::batch-bulk-jpql-delete-example[] //tag::batch-bulk-jpql-delete-example[]
int deletedEntities = entityManager.createQuery( int deletedEntities = entityManager.createQuery(
"delete Customer c " + "delete Person p " +
"where c.name = :name" ) "where p.name = :name" )
.setParameter( "name", name ) .setParameter( "name", name )
.executeUpdate(); .executeUpdate();
//end::batch-bulk-jpql-delete-example[] //end::batch-bulk-jpql-delete-example[]
@ -124,16 +126,13 @@ public class BatchTest extends BaseEntityManagerFunctionalTestCase {
} ); } );
doInJPA( this::entityManagerFactory, entityManager -> { doInJPA( this::entityManagerFactory, entityManager -> {
String name = "Mihalcea";
Session session = entityManager.unwrap( Session.class ); Session session = entityManager.unwrap( Session.class );
//tag::batch-bulk-hql-insert-example[] //tag::batch-bulk-hql-insert-example[]
int insertedEntities = session.createQuery( int insertedEntities = session.createQuery(
"insert into Partner (id, name) " + "insert into Partner (id, name) " +
"select c.id, c.name " + "select p.id, p.name " +
"from Customer c " + "from Person p ")
"where name = :name" )
.setParameter( "name", name )
.executeUpdate(); .executeUpdate();
//end::batch-bulk-hql-insert-example[] //end::batch-bulk-hql-insert-example[]
assertEquals(1, insertedEntities); assertEquals(1, insertedEntities);
@ -145,7 +144,7 @@ public class BatchTest extends BaseEntityManagerFunctionalTestCase {
Session session = entityManager.unwrap( Session.class ); Session session = entityManager.unwrap( Session.class );
//tag::batch-bulk-hql-delete-example[] //tag::batch-bulk-hql-delete-example[]
int deletedEntities = session.createQuery( int deletedEntities = session.createQuery(
"delete Customer " + "delete Person " +
"where name = :name" ) "where name = :name" )
.setParameter( "name", name ) .setParameter( "name", name )
.executeUpdate(); .executeUpdate();
@ -165,8 +164,8 @@ public class BatchTest extends BaseEntityManagerFunctionalTestCase {
txn.begin(); txn.begin();
for ( int i = 0; i < 100_000; i++ ) { for ( int i = 0; i < 100_000; i++ ) {
Customer customer = new Customer( String.format( "Customer %d", i ) ); Person Person = new Person( String.format( "Person %d", i ) );
entityManager.persist( customer ); entityManager.persist( Person );
} }
txn.commit(); txn.commit();
@ -195,8 +194,8 @@ public class BatchTest extends BaseEntityManagerFunctionalTestCase {
int batchSize = 25; int batchSize = 25;
for ( int i = 0; i < entityCount; ++i ) { for ( int i = 0; i < entityCount; ++i ) {
Customer customer = new Customer( String.format( "Customer %d", i ) ); Person Person = new Person( String.format( "Person %d", i ) );
entityManager.persist( customer ); entityManager.persist( Person );
if ( i % batchSize == 0 ) { if ( i % batchSize == 0 ) {
//flush a batch of inserts and release memory //flush a batch of inserts and release memory
@ -235,14 +234,14 @@ public class BatchTest extends BaseEntityManagerFunctionalTestCase {
Session session = entityManager.unwrap( Session.class ); Session session = entityManager.unwrap( Session.class );
scrollableResults = session scrollableResults = session
.createQuery( "select c from Customer c" ) .createQuery( "select p from Person p" )
.setCacheMode( CacheMode.IGNORE ) .setCacheMode( CacheMode.IGNORE )
.scroll( ScrollMode.FORWARD_ONLY ); .scroll( ScrollMode.FORWARD_ONLY );
int count = 0; int count = 0;
while ( scrollableResults.next() ) { while ( scrollableResults.next() ) {
Customer customer = (Customer) scrollableResults.get( 0 ); Person Person = (Person) scrollableResults.get( 0 );
processCustomer(customer); processPerson(Person);
if ( ++count % batchSize == 0 ) { if ( ++count % batchSize == 0 ) {
//flush a batch of updates and release memory: //flush a batch of updates and release memory:
entityManager.flush(); entityManager.flush();
@ -280,13 +279,13 @@ public class BatchTest extends BaseEntityManagerFunctionalTestCase {
txn.begin(); txn.begin();
scrollableResults = statelessSession scrollableResults = statelessSession
.createQuery( "select c from Customer c" ) .createQuery( "select p from Person p" )
.scroll(ScrollMode.FORWARD_ONLY); .scroll(ScrollMode.FORWARD_ONLY);
while ( scrollableResults.next() ) { while ( scrollableResults.next() ) {
Customer customer = (Customer) scrollableResults.get( 0 ); Person Person = (Person) scrollableResults.get( 0 );
processCustomer(customer); processPerson(Person);
statelessSession.update( customer ); statelessSession.update( Person );
} }
txn.commit(); txn.commit();
@ -304,63 +303,10 @@ public class BatchTest extends BaseEntityManagerFunctionalTestCase {
//end::batch-stateless-session-example[] //end::batch-stateless-session-example[]
} }
private void processCustomer(Customer customer) { private void processPerson(Person Person) {
if ( customer.getId() % 1000 == 0 ) { if ( Person.getId() % 1000 == 0 ) {
log.infof( "Processing [%s]", customer.getName()); log.infof( "Processing [%s]", Person.getName());
} }
} }
@Entity(name = "Customer")
public static class Customer {
@Id
@GeneratedValue
private Long id;
@Version
private int version;
private String name;
public Customer() {}
public Customer(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
}
@Entity(name = "Partner")
public static class Partner {
@Id
@GeneratedValue
private Long id;
@Version
private int version;
private String name;
public Partner() {}
public Partner(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
}
} }

View File

@ -0,0 +1,43 @@
package org.hibernate.userguide.hql;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Version;
/**
* @author Vlad Mihalcea
*/
//tag::hql-examples-domain-model-example[]
@Entity
public class Partner {
@Id
@GeneratedValue
private Long id;
@Version
private int version;
private String name;
//Getters and setters are omitted for brevity
//end::hql-examples-domain-model-example[]
public Partner() {
}
public Partner(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
//tag::hql-examples-domain-model-example[]
}
//end::hql-examples-domain-model-example[]

View File

@ -18,6 +18,7 @@ import javax.persistence.OneToMany;
import javax.persistence.OrderColumn; import javax.persistence.OrderColumn;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.persistence.Version;
/** /**
* @author Vlad Mihalcea * @author Vlad Mihalcea
@ -55,6 +56,9 @@ public class Person {
@MapKeyEnumerated(EnumType.STRING) @MapKeyEnumerated(EnumType.STRING)
private Map<AddressType, String> addresses = new HashMap<>(); private Map<AddressType, String> addresses = new HashMap<>();
@Version
private int version;
//Getters and setters are omitted for brevity //Getters and setters are omitted for brevity
//end::hql-examples-domain-model-example[] //end::hql-examples-domain-model-example[]