Migrate User Guide HQL chapter extras to test folder

This commit is contained in:
Vlad Mihalcea 2016-02-04 10:57:48 +02:00
parent f69c4e7882
commit 9b60354e3e
69 changed files with 3724 additions and 1738 deletions

View File

@ -1,10 +0,0 @@
select count(*), sum( o.total ), avg( o.total ), min( o.total ), max( o.total )
from Order o
select count( distinct c.name )
from Customer c
select c.id, c.name, sum( o.total )
from Customer c
left join c.orders o
group by c.id, c.name

View File

@ -1,9 +0,0 @@
Query query = ...;
// in seconds
query.setTimeout( 2 );
// write to L2 caches, but do not read from them
query.setCacheMode( CacheMode.REFRESH );
// assuming query cache was enabled for the SessionFactory
query.setCacheable( true );
// add a comment to the generated SQL if enabled via the hibernate.use_sql_comments configuration property
query.setComment( "e pluribus unum" )

View File

@ -1 +0,0 @@
Query query = session.createQuery( "select e.id, e.name from MyEntity e" );

View File

@ -1 +0,0 @@
Query query = session.getNamedQuery( "my-predefined-named-query" );

View File

@ -1,3 +0,0 @@
List results =
session.createQuery( "select e from MyEntity e" )
.list();

View File

@ -1,4 +0,0 @@
Query query = session.createQuery(
"select e from MyEntity e where e.name like :filter"
);
query.setParameter( "filter", "D%", StringType.INSTANCE );

View File

@ -1,4 +0,0 @@
Query query = session.createQuery(
"select e from MyEntity e where e.name like :filter"
);
query.setParameter( "filter", "D%" );

View File

@ -1,9 +0,0 @@
Query query = session.createQuery(
"select e from MyEntity e where e.name like :filter"
);
query.setString( "filter", "D%" );
query = session.createQuery(
"select e from MyEntity e where e.active = :active"
);
query.setBoolean( "active", true );

View File

@ -1,4 +0,0 @@
MyEntity result = ( MyEntity ) session.createQuery(
"select e from MyEntity e where e.code = :code" )
.setParameter( "code", 123 )
.uniqueResult();

View File

@ -1,5 +0,0 @@
Query query = ...;
// timeout - in milliseconds
query.setHint( "javax.persistence.query.timeout", 2000 )
// Do not peform ( AUTO ) implicit flushing
query.setFlushMode( COMMIT );

View File

@ -1,6 +0,0 @@
Query query = em.createNamedQuery( "my-predefined-named-query" );
TypedQuery<MyEntity> query2 = em.createNamedQuery(
"my-predefined-named-query",
MyEntity.class
);

View File

@ -1,8 +0,0 @@
Query query = em.createQuery(
"select e from MyEntity e where name like :filter"
);
TypedQuery<MyEntity> query2 = em.createQuery(
"select e from MyEntity e where name like :filter"
MyEntity.class
);

View File

@ -1,9 +0,0 @@
Query query = em.createQuery(
"select e from MyEntity e where e.name like :filter"
);
query.setParameter( "filter", "D%" );
Query q2 = em.createQuery(
"select e from MyEntity e where e.activeDate > :activeDate"
);
q2.setParameter( "activeDate", new Date(), TemporalType.DATE );

View File

@ -1,9 +0,0 @@
select year( current_date() ) - year( c.dateOfBirth )
from Customer c
select c
from Customer c
where year( current_date() ) - year( c.dateOfBirth ) < 30
select o.customer, o.total + ( o.total * :salesTax )
from Order o

View File

@ -1,36 +0,0 @@
select cal
from Calendar cal
where maxelement(cal.holidays) > current_date()
select o
from Order o
where maxindex(o.items) > 100
select o
from Order o
where minelement(o.items) > 10000
select m
from Cat as m, Cat as kit
where kit in elements(m.kittens)
// the above query can be re-written in jpql standard way:
select m
from Cat as m, Cat as kit
where kit member of m.kittens
select p
from NameList l, Person p
where p.name = some elements(l.names)
select cat
from Cat cat
where exists elements(cat.kittens)
select p
from Player p
where 3 > all elements(p.scores)
select show
from Show show
where 'fizard' in indices(show.acts)

View File

@ -1,16 +0,0 @@
select c
from Customer c
join c.orders o
join o.lineItems l
join l.product p
where o.status = 'pending'
and p.status = 'backorder'
// alternate syntax
select c
from Customer c,
in(c.orders) o,
in(o.lineItems) l
join l.product p
where o.status = 'pending'
and p.status = 'backorder'

View File

@ -1,3 +0,0 @@
select 'Mr. ' || c.name.first || ' ' || c.name.last
from Customer c
where c.gender = Gender.MALE

View File

@ -1,4 +0,0 @@
select new the.felidae.Family( mother, mate, offspr )
from DomesticCat as mother
join mother.mate as mate
left join mother.kittens as offspr

View File

@ -1,7 +0,0 @@
select o
from Order o
where o.lineItems is empty
select c
from Customer c
where c.pastDueBills is not empty

View File

@ -1,8 +0,0 @@
select p
from Payment p
where type(p) = CreditCardPayment
select p
from Payment p
where type(p) = :aType

View File

@ -1,10 +0,0 @@
// retrieve the total for all orders
select sum( o.total )
from Order o
// retrieve the total of all orders
// *grouped by* customer
select c.id, sum( o.total )
from Order o
inner join o.customer c
group by c.id

View File

@ -1,5 +0,0 @@
select c.id, sum( o.total )
from Order o
inner join o.customer c
group by c.id
having sum( o.total ) > 10000.00

View File

@ -1,22 +0,0 @@
select o
from Order o
where o.items[0].id = 1234
select p
from Person p, Calendar c
where c.holidays['national day'] = p.birthDay
and p.nationality.calendar = c
select i
from Item i, Order o
where o.items[ o.deliveredItemIndices[0] ] = i
and o.id = 11
select i
from Item i, Order o
where o.items[ maxindex(o.items) ] = i
and o.id = 11
select i
from Item i, Order o
where o.items[ size(o.items) - 1 ] = i

View File

@ -1,10 +0,0 @@
select c
from Customer c
join c.chiefExecutive ceo
where ceo.age < 25
// same query but specifying join type as 'inner' explicitly
select c
from Customer c
inner join c.chiefExecutive ceo
where ceo.age < 25

View File

@ -1,15 +0,0 @@
// get customers who have orders worth more than $5000
// or who are in "preferred" status
select distinct c
from Customer c
left join c.orders o
where o.value > 5000.00
or c.status = 'preferred'
// functionally the same query but using the
// 'left outer' phrase
select distinct c
from Customer c
left outer join c.orders o
where o.value > 5000.00
or c.status = 'preferred'

View File

@ -1,3 +0,0 @@
select c
from Customer c
left join fetch c.orders o

View File

@ -1,9 +0,0 @@
select c
from Customer c
where c.chiefExecutive.age < 25
// same as
select c
from Customer c
inner join c.chiefExecutive ceo
where ceo.age < 25

View File

@ -1,19 +0,0 @@
select c
from Customer c
where c.chiefExecutive.age < 25
and c.chiefExecutive.address.state = 'TX'
// same as
select c
from Customer c
inner join c.chiefExecutive ceo
where ceo.age < 25
and ceo.address.state = 'TX'
// same as
select c
from Customer c
inner join c.chiefExecutive ceo
inner join ceo.address a
where ceo.age < 25
and a.state = 'TX'

View File

@ -1,4 +0,0 @@
select distinct c
from Customer c
left join c.orders o
on o.value > 5000.00

View File

@ -1,4 +0,0 @@
select distinct c
from Customer c
left join c.orders o
with o.value > 5000.00

View File

@ -1,15 +0,0 @@
String queryString =
"select c " +
"from Customer c " +
"where c.name = ?1 " +
" or c.nickName = ?1";
// HQL - as you can see, handled just like named parameters in terms of API
List customers = session.createQuery( queryString )
.setParameter( "1", theNameOfInterest )
.list();
// JPQL
List<Customer> customers = entityManager.createQuery( queryString, Customer.class )
.setParameter( 1, theNameOfInterest )
.getResultList();

View File

@ -1,4 +0,0 @@
select new list(mother, offspr, mate.name)
from DomesticCat as mother
inner join mother.mate as mate
left outer join mother.kittens as offspr

View File

@ -1 +0,0 @@
locate( string_expression, string_expression[, numeric_expression] )

View File

@ -1,7 +0,0 @@
select new map( mother as mother, offspr as offspr, mate as mate )
from DomesticCat as mother
inner join mother.mate as mate
left outer join mother.kittens as offspr
select new map( max(c.bodyWeight) as max, min(c.bodyWeight) as min, count(*) as n )
from Cat c

View File

@ -1,8 +0,0 @@
select p
from Person p
where 'John' member of p.nickNames
select p
from Person p
where p.name.first = 'Joseph'
and 'Joey' not member of p.nickNames

View File

@ -1,5 +0,0 @@
// build a product between customers and active mailing campaigns so we can spam!
select distinct cust, camp
from Customer cust, Campaign camp
where camp.type = 'mail'
and current_timestamp() between camp.activeRange.start and camp.activeRange.end

View File

@ -1,5 +0,0 @@
// retrieve all customers with headquarters in the same state as Acme's headquarters
select distinct c1
from Customer c1, Customer c2
where c1.address.state = c2.address.state
and c2.name = 'Acme'

View File

@ -1,15 +0,0 @@
String queryString =
"select c " +
"from Customer c " +
"where c.name = :name " +
" or c.nickName = :name";
// HQL
List customers = session.createQuery( queryString )
.setParameter( "name", theNameOfInterest )
.list();
// JPQL
List<Customer> customers = entityManager.createQuery( queryString, Customer.class )
.setParameter( "name", theNameOfInterest )
.getResultList();

View File

@ -1,8 +0,0 @@
// return customers who have changed their last name
select nullif( c.previousName.last, c.name.last )
from Customer c
// equivalent CASE expression
select case when c.previousName.last = c.name.last then null
else c.previousName.last end
from Customer c

View File

@ -1,29 +0,0 @@
// simple integer literal
select o
from Order o
where o.referenceNumber = 123
// simple integer literal, typed as a long
select o
from Order o
where o.referenceNumber = 123L
// decimal notation
select o
from Order o
where o.total > 5000.00
// decimal notation, typed as a float
select o
from Order o
where o.total > 5000.00F
// scientific notation
select o
from Order o
where o.total > 5e+3
// scientific notation, typed as a float
select o
from Order o
where o.total > 5e+3F

View File

@ -1,10 +0,0 @@
// legal because p.name is implicitly part of p
select p
from Person p
order by p.name
select c.id, sum( o.total ) as t
from Order o
inner join o.customer c
group by c.id
order by t

View File

@ -1,19 +0,0 @@
select p
from Customer c
join c.paymentHistory p
where c.id = 123
and index(p) between 0 and 9
select c
from Customer c
where c.president.dateOfBirth
between {d '1945-01-01'}
and {d '1965-01-01'}
select o
from Order o
where o.total between 500 and 5000
select p
from Person p
where p.name between 'A' and 'E'

View File

@ -1,34 +0,0 @@
// numeric comparison
select c
from Customer c
where c.chiefExecutive.age < 30
// string comparison
select c
from Customer c
where c.name = 'Acme'
// datetime comparison
select c
from Customer c
where c.inceptionDate < {d '2000-01-01'}
// enum comparison
select c
from Customer c
where c.chiefExecutive.gender = com.acme.Gender.MALE
// boolean comparison
select c
from Customer c
where c.sendEmail = true
// entity type comparison
select p
from Payment p
where type(p) = WireTransferPayment
// entity value comparison
select c
from Customer c
where c.chiefExecutive = c.chiefTechnologist

View File

@ -1,9 +0,0 @@
// select all players that scored at least 3 points
// in every game.
select p
from Player p
where 3 > all (
select spg.points
from StatsPerGame spg
where spg.player = p
)

View File

@ -1,37 +0,0 @@
select p
from Payment p
where type(p) in (CreditCardPayment, WireTransferPayment)
select c
from Customer c
where c.hqAddress.state in ('TX', 'OK', 'LA', 'NM')
select c
from Customer c
where c.hqAddress.state in ?
select c
from Customer c
where c.hqAddress.state in (
select dm.state
from DeliveryMetadata dm
where dm.salesTax is not null
)
// Not JPQL compliant!
select c
from Customer c
where
( c.firstName, c.lastName ) in (
( 'John','Doe' ),
( 'Jane','Doe' )
)
// Not JPQL compliant!
select c
from Customer c
where c.chiefExecutive in (
select p
from Person p
where ...
)

View File

@ -1,4 +0,0 @@
// find any with name starting with "sp_"
select sp
from StoredProcedureMetadata sp
where sp.name like 'sp|_%' escape '|'

View File

@ -1,7 +0,0 @@
select p
from Person p
where p.name like '%Schmidt'
select p
from Person p
where p.name not like 'Jingleheimmer%'

View File

@ -1,9 +0,0 @@
// select everyone with an associated address
select p
from Person p
where p.address is not null
// select everyone without an associated address
select p
from Person p
where p.address is null

View File

@ -1,33 +0,0 @@
// Product.images is a Map<String,String>, where the Map key is the image name and the Map value is the image path
// select all the image file paths (the map value) for Product#123
select i
from Product p
join p.images i
where p.id = 123
// same as above
select value(i)
from Product p
join p.images i
where p.id = 123
// select all the image names (the map key) for Product#123
select key(i)
from Product p
join p.images i
where p.id = 123
// select all the image names and file paths (the 'Map.Entry') for Product#123
select entry(i)
from Product p
join p.images i
where p.id = 123
// total the value of the initial line items for all orders for a customer
select sum( li.amount )
from Customer c
join c.orders o
join o.lineItems li
where c.id = 123
and index(li) = 1

View File

@ -1,9 +0,0 @@
select case when c.name.first is not null then c.name.first
when c.nickName is not null then c.nickName
else '<no first name>' end
from Customer c
// Again, the abbreviated form coalesce can handle this a
// little more succinctly
select coalesce( c.name.first, c.nickName, '<no first name>' )
from Customer c

View File

@ -1,16 +0,0 @@
select case c.nickName when null then '<no nick name>' else c.nickName end
from Customer c
// This NULL checking is such a common case that most dbs
// define an abbreviated CASE form. For example:
select nvl( c.nickName, '<no nick name>' )
from Customer c
// or:
select isnull( c.nickName, '<no nick name>' )
from Customer c
// the standard coalesce abbreviated form can be used
// to achieve the same result:
select coalesce( c.nickName, '<no nick name>' )
from Customer c

View File

@ -1,2 +0,0 @@
select c
from com.acme.Cat c

View File

@ -1,8 +0,0 @@
int createdEntities = session.createQuery(
"insert into DelinquentAccount " +
" ( id, name ) " +
"select " +
" c.id, c.name " +
"from Customer c " +
"where ..."
).executeUpdate();

View File

@ -1,9 +0,0 @@
String hqlUpdate=
"update Customer c "+
"set c.name = :newName "+
"where c.name = :oldName";
int updatedEntities=session.createQuery(hqlUpdate)
.setString("newName",newName)
.setString("oldName",oldName)
.executeUpdate();

View File

@ -1,9 +0,0 @@
String hqlVersionedUpdate=
"update versioned Customer c "+
"set c.name = :newName "+
"where c.name = :oldName";
int updatedEntities=s.createQuery(hqlUpdate)
.setString("newName",newName)
.setString("oldName",oldName)
.executeUpdate();

View File

@ -1,9 +0,0 @@
String jpqlUpdate=
"update Customer c "+
"set c.name = :newName "+
"where c.name = :oldName";
int updatedEntities=entityManager.createQuery(jpqlUpdate)
.setString("newName",newName)
.setString("oldName",oldName)
.executeUpdate();

View File

@ -1,8 +0,0 @@
select c
from Customer c
where c.name = 'Acme'
select c
from Customer c
where c.name = 'Acme''s Pretzel Logic'

View File

@ -0,0 +1,11 @@
package org.hibernate.userguide.hql;
/**
* @author Vlad Mihalcea
*/
//tag::hql-examples-domain-model-example[]
public enum AddressType {
HOME,
OFFICE
}
//end::hql-examples-domain-model-example[]

View File

@ -0,0 +1,65 @@
package org.hibernate.userguide.hql;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
/**
* @author Vlad Mihalcea
*/
//tag::hql-examples-domain-model-example[]
@Entity(name = "Call")
public class Call {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private Phone phone;
private Date timestamp;
private int duration;
//Getters and setters are omitted for brevity
//end::hql-examples-domain-model-example[]
public Call() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Phone getPhone() {
return phone;
}
public void setPhone(Phone phone) {
this.phone = phone;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
//tag::hql-examples-domain-model-example[]
}
//end::hql-examples-domain-model-example[]

View File

@ -0,0 +1,25 @@
package org.hibernate.userguide.hql;
/**
* @author Vlad Mihalcea
*/
//tag::hql-select-clause-dynamic-instantiation-example[]
public class CallStatistics {
private final long count;
private final long total;
private final int min;
private final int max;
private final double abg;
public CallStatistics(long count, long total, int min, int max, double abg) {
this.count = count;
this.total = total;
this.min = min;
this.max = max;
this.abg = abg;
}
//Getters and setters omitted for brevity
}
//end::hql-select-clause-dynamic-instantiation-example[]

View File

@ -0,0 +1,12 @@
package org.hibernate.userguide.hql;
import javax.persistence.Entity;
/**
* @author Vlad Mihalcea
*/
//tag::hql-examples-domain-model-example[]
@Entity
public class CreditCardPayment extends Payment {
}
//end::hql-examples-domain-model-example[]

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,66 @@
package org.hibernate.userguide.hql;
import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.ManyToOne;
/**
* @author Vlad Mihalcea
*/
//tag::hql-examples-domain-model-example[]
@Entity
@Inheritance
public class Payment {
@Id
@GeneratedValue
private Long id;
private BigDecimal amount;
private boolean completed;
@ManyToOne
private Person person;
//Getters and setters are omitted for brevity
//end::hql-examples-domain-model-example[]
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
//tag::hql-examples-domain-model-example[]
}
//end::hql-examples-domain-model-example[]

View File

@ -0,0 +1,114 @@
package org.hibernate.userguide.hql;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.CascadeType;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MapKeyEnumerated;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OrderColumn;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* @author Vlad Mihalcea
*/
//tag::hql-examples-domain-model-example[]
//tag::jpql-api-named-query-example[]
@NamedQueries(
@NamedQuery(
name = "get_person_by_name",
query = "select p from Person p where name = :name"
)
)
//end::jpql-api-named-query-example[]
@Entity
public class Person {
@Id
@GeneratedValue
private Long id;
private String name;
private String nickName;
private String address;
@Temporal(TemporalType.TIMESTAMP )
private Date createdOn;
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
@OrderColumn(name = "order_id")
private List<Phone> phones = new ArrayList<>();
@ElementCollection
@MapKeyEnumerated(EnumType.STRING)
private Map<AddressType, String> addresses = new HashMap<>();
//Getters and setters are omitted for brevity
//end::hql-examples-domain-model-example[]
public Person() {}
public Person(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public List<Phone> getPhones() {
return phones;
}
public Map<AddressType, String> getAddresses() {
return addresses;
}
public void addPhone(Phone phone) {
phones.add( phone );
phone.setPerson( this );
}
//tag::hql-examples-domain-model-example[]
}
//end::hql-examples-domain-model-example[]

View File

@ -0,0 +1,107 @@
package org.hibernate.userguide.hql;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.CascadeType;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.MapKey;
import javax.persistence.MapKeyTemporal;
import javax.persistence.OneToMany;
import javax.persistence.TemporalType;
/**
* @author Vlad Mihalcea
*/
//tag::hql-examples-domain-model-example[]
@Entity
public class Phone {
@Id
private Long id;
@ManyToOne
private Person person;
private String number;
@Enumerated(EnumType.STRING)
private PhoneType type;
@OneToMany(mappedBy = "phone", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Call> calls = new ArrayList<>( );
//tag::hql-collection-qualification-example[]
@OneToMany(mappedBy = "phone")
@MapKey(name = "timestamp")
@MapKeyTemporal(TemporalType.TIMESTAMP )
private Map<Date, Call> callHistory = new HashMap<>();
//end::hql-collection-qualification-example[]
@ElementCollection
private List<Date> repairTimestamps = new ArrayList<>( );
//Getters and setters are omitted for brevity
//end::hql-examples-domain-model-example[]
public Phone() {}
public Phone(String number) {
this.number = number;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNumber() {
return number;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public PhoneType getType() {
return type;
}
public void setType(PhoneType type) {
this.type = type;
}
public List<Call> getCalls() {
return calls;
}
public Map<Date, Call> getCallHistory() {
return callHistory;
}
public List<Date> getRepairTimestamps() {
return repairTimestamps;
}
public void addCall(Call call) {
calls.add( call );
callHistory.put( call.getTimestamp(), call );
call.setPhone( this );
}
//tag::hql-examples-domain-model-example[]
}
//end::hql-examples-domain-model-example[]

View File

@ -0,0 +1,11 @@
package org.hibernate.userguide.hql;
/**
* @author Vlad Mihalcea
*/
//tag::hql-examples-domain-model-example[]
public enum PhoneType {
LAND_LINE,
MOBILE;
}
//end::hql-examples-domain-model-example[]

View File

@ -0,0 +1,12 @@
package org.hibernate.userguide.hql;
import javax.persistence.Entity;
/**
* @author Vlad Mihalcea
*/
//tag::hql-examples-domain-model-example[]
@Entity
public class WireTransferPayment extends Payment {
}
//end::hql-examples-domain-model-example[]