#2069 - Add ebean-querybean, querybean-generator and kotlin-querybean-generator as modules

This commit is contained in:
rob bygrave committed 2020-10-09 00:02:09 +13:00
1 parent bc055fea25
commit 038db79737
140 files changed
+11583

No files matched your search

@@ -0,0 +1,16 @@
package org.example.domain;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
@Inheritance
@DiscriminatorValue("CAT")
@Entity
public class ACat extends Animal {
public ACat(String name) {
super(name);
}
}
@@ -0,0 +1,26 @@
package org.example.domain;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
@Inheritance
@DiscriminatorValue("DOG")
@Entity
public class ADog extends Animal {
private String registration;
public ADog(String name, String registration) {
super(name);
this.registration = registration;
}
public String getRegistration() {
return registration;
}
public void setRegistration(String registration) {
this.registration = registration;
}
}
@@ -0,0 +1,16 @@
package org.example.domain;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
@Inheritance
@DiscriminatorValue("WC")
@Entity
public class AWildCat extends ACat {
public AWildCat(String name) {
super(name);
}
}
@@ -0,0 +1,100 @@
package org.example.domain;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.Size;
/**
* Address entity bean.
*/
@Entity
@Table(name = "o_address")
public class Address extends BaseModel {
@Size(max = 100)
String line1;
@Size(max = 100)
String line2;
@Size(max = 100)
String city;
@ManyToOne
Country country;
/**
* Create a copy of the address. Used to provide a 'snapshot' of
* the shippingAddress for a give order.
*/
public Address createCopy() {
Address copy = new Address();
copy.setLine1(line1);
copy.setLine2(line2);
copy.setCity(city);
copy.setCountry(country);
return copy;
}
public String toString() {
return id + " " + line1 + " " + line2 + " " + city + " " + country;
}
/**
* Return line 1.
*/
public String getLine1() {
return line1;
}
/**
* Set line 1.
*/
public void setLine1(String line1) {
this.line1 = line1;
}
/**
* Return line 2.
*/
public String getLine2() {
return line2;
}
/**
* Set line 2.
*/
public void setLine2(String line2) {
this.line2 = line2;
}
/**
* Return city.
*/
public String getCity() {
return city;
}
/**
* Set city.
*/
public void setCity(String city) {
this.city = city;
}
/**
* Return country.
*/
public Country getCountry() {
return country;
}
/**
* Set country.
*/
public void setCountry(Country country) {
this.country = country;
}
}
@@ -0,0 +1,49 @@
package org.example.domain;
import io.ebean.Model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.Version;
@Entity
@Inheritance
public abstract class Animal extends Model {
@Id
long id;
@Version
long version;
String name;
public Animal(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,69 @@
package org.example.domain;
import io.ebean.Model;
import io.ebean.annotation.CreatedTimestamp;
import io.ebean.annotation.UpdatedTimestamp;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
import java.sql.Timestamp;
/**
* Base domain object with Id, version, whenCreated and whenUpdated.
*
* <p>
* Extending Model to enable the 'active record' style.
*
* <p>
* whenCreated and whenUpdated are generally useful for maintaining external search services (like
* elasticsearch) and audit.
*/
@MappedSuperclass
public abstract class BaseModel extends Model {
@Id
Long id;
@Version
Long version;
@CreatedTimestamp
Timestamp whenCreated;
@UpdatedTimestamp
Timestamp whenUpdated;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public Timestamp getWhenCreated() {
return whenCreated;
}
public void setWhenCreated(Timestamp whenCreated) {
this.whenCreated = whenCreated;
}
public Timestamp getWhenUpdated() {
return whenUpdated;
}
public void setWhenUpdated(Timestamp whenUpdated) {
this.whenUpdated = whenUpdated;
}
}
@@ -0,0 +1,110 @@
package org.example.domain;
import io.ebean.annotation.DbArray;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.List;
/**
* Contact entity bean.
*/
@Entity
@Table(name="be_contact")
public class Contact extends BaseModel {
@DbArray
List<String> phoneNumbers = new ArrayList();
@Column(length=50)
String firstName;
@Column(length=50)
String lastName;
@Column(length=200)
String email;
@Column(length=20)
String phone;
@ManyToOne(optional=false)
Customer customer;
@OneToMany(mappedBy = "contact")
List<ContactNote> notes;
/**
* Default constructor.
*/
public Contact() {
}
/**
* Construct with a firstName and lastName.
*/
public Contact(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List<ContactNote> getNotes() {
return notes;
}
public void setNotes(List<ContactNote> notes) {
this.notes = notes;
}
public List<String> getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}
@@ -0,0 +1,46 @@
package org.example.domain;
import io.ebean.Finder;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
@Entity
public class ContactNote extends BaseModel {
public static final Finder<Long, ContactNote> find = new Finder<>(ContactNote.class);
@ManyToOne(optional = false)
Contact contact;
String title;
@Lob
String note;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
}
@@ -0,0 +1,59 @@
package org.example.domain;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Country entity bean.
*/
@Entity
@Table(name="o_country")
public class Country {
@Id
//@Size(max=2)
String code;
//@Size(max=60)
String name;
public Country(String code, String name) {
this.code = code;
this.name = name;
}
public String toString() {
return code;
}
/**
* Return code.
*/
public String getCode() {
return code;
}
/**
* Set code.
*/
public void setCode(String code) {
this.code = code;
}
/**
* Return name.
*/
public String getName() {
return name;
}
/**
* Set name.
*/
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,172 @@
package org.example.domain;
import io.ebean.annotation.Cache;
import io.ebean.annotation.EnumValue;
import io.ebean.types.Inet;
import org.example.domain.finder.CustomerFinder;
import org.example.domain.otherpackage.PhoneNumber;
import org.example.domain.otherpackage.ValidEmail;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Customer entity bean.
*/
@Cache
@Entity
@Table(name = "be_customer")
public class Customer extends BaseModel {
/**
* Convenience Finder for 'active record' style.
*/
public static final CustomerFinder find = new CustomerFinder();
public enum Status {
@EnumValue("G")
GOOD,
@EnumValue("B")
BAD,
@EnumValue("M")
MIDDLING
}
Status status;
boolean inactive;
PhoneNumber phoneNumber;
ValidEmail email;
@Column(length = 100)
String name;
Date registered;
Inet currentInet;
@Column(length = 1000)
String comments;
@ManyToOne(cascade = CascadeType.ALL)
Address billingAddress;
@ManyToOne(cascade = CascadeType.ALL)
Address shippingAddress;
@OneToMany(mappedBy = "customer", cascade = CascadeType.PERSIST)
List<Contact> contacts;
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public boolean isInactive() {
return inactive;
}
public void setInactive(boolean inactive) {
this.inactive = inactive;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getRegistered() {
return registered;
}
public void setRegistered(Date registered) {
this.registered = registered;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Inet getCurrentInet() {
return currentInet;
}
public void setCurrentInet(Inet currentInet) {
this.currentInet = currentInet;
}
public Address getBillingAddress() {
return billingAddress;
}
public void setBillingAddress(Address billingAddress) {
this.billingAddress = billingAddress;
}
public Address getShippingAddress() {
return shippingAddress;
}
public void setShippingAddress(Address shippingAddress) {
this.shippingAddress = shippingAddress;
}
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
public PhoneNumber getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(final PhoneNumber phoneNumber) {
this.phoneNumber = phoneNumber;
}
public ValidEmail getEmail() {
return email;
}
public void setEmail(final ValidEmail email) {
this.email = email;
}
/**
* Helper method to add a contact to the customer.
*/
public void addContact(Contact contact) {
if (contacts == null) {
contacts = new ArrayList<>();
}
// setting the customer is automatically done when Ebean does
// a cascade save from customer to contacts.
contact.setCustomer(this);
contacts.add(contact);
}
}
@@ -0,0 +1,137 @@
package org.example.domain;
import io.ebean.Finder;
import io.ebean.Model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
/**
* Order entity bean.
*/
@Entity
@Table(name = "o_order")
public class Order extends BaseModel {
public static final Finder<Long,Order> find = new Finder<>(Order.class);
public enum Status {
NEW, APPROVED, SHIPPED, COMPLETE
}
Status status;
Date orderDate;
Date shipDate;
@NotNull
@ManyToOne
Customer customer;
@ManyToOne
Address shippingAddress;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "order")
@OrderBy("id asc")
List<OrderDetail> details;
public String toString() {
return id + " status:" + status + " customer:" + customer;
}
/**
* Return order date.
*/
public Date getOrderDate() {
return orderDate;
}
/**
* Set order date.
*/
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
/**
* Return ship date.
*/
public Date getShipDate() {
return shipDate;
}
/**
* Set ship date.
*/
public void setShipDate(Date shipDate) {
this.shipDate = shipDate;
}
/**
* Return status.
*/
public Status getStatus() {
return status;
}
/**
* Set status.
*/
public void setStatus(Status status) {
this.status = status;
}
/**
* Return customer.
*/
public Customer getCustomer() {
return customer;
}
/**
* Set customer.
*/
public void setCustomer(Customer customer) {
this.customer = customer;
}
/**
* Set the customer with their current shipping address.
*/
public void setCustomerWithShipping(Customer customer) {
this.customer = customer;
this.shippingAddress = customer.getShippingAddress();
}
/**
* Return details.
*/
public List<OrderDetail> getDetails() {
return details;
}
/**
* Set details.
*/
public void setDetails(List<OrderDetail> details) {
this.details = details;
}
public void addDetail(OrderDetail detail) {
if (details == null) {
details = new ArrayList<>();
}
details.add(detail);
}
}
@@ -0,0 +1,99 @@
package org.example.domain;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* Order Detail entity bean.
*/
@Entity
@Table(name = "o_order_detail")
public class OrderDetail extends BaseModel {
@ManyToOne
Order order;
Integer orderQty;
Integer shipQty;
Double unitPrice;
@ManyToOne
Product product;
public OrderDetail() {
}
public OrderDetail(Product product, Integer orderQty, Double unitPrice) {
this.product = product;
this.orderQty = orderQty;
this.unitPrice = unitPrice;
}
/**
* Return order qty.
*/
public Integer getOrderQty() {
return orderQty;
}
/**
* Set order qty.
*/
public void setOrderQty(Integer orderQty) {
this.orderQty = orderQty;
}
/**
* Return ship qty.
*/
public Integer getShipQty() {
return shipQty;
}
/**
* Set ship qty.
*/
public void setShipQty(Integer shipQty) {
this.shipQty = shipQty;
}
public Double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(Double unitPrice) {
this.unitPrice = unitPrice;
}
/**
* Return order.
*/
public Order getOrder() {
return order;
}
/**
* Set order.
*/
public void setOrder(Order order) {
this.order = order;
}
/**
* Return product.
*/
public Product getProduct() {
return product;
}
/**
* Set product.
*/
public void setProduct(Product product) {
this.product = product;
}
}
@@ -0,0 +1,47 @@
package org.example.domain;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.Size;
/**
* Product entity bean.
*/
@Entity
@Table(name = "o_product")
public class Product extends BaseModel {
@Size(max = 20)
String sku;
String name;
/**
* Return sku.
*/
public String getSku() {
return sku;
}
/**
* Set sku.
*/
public void setSku(String sku) {
this.sku = sku;
}
/**
* Return name.
*/
public String getName() {
return name;
}
/**
* Set name.
*/
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,19 @@
package org.example.domain;
import java.util.ArrayList;
public class SomePojo {
String name;
ArrayList<String> foos = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,18 @@
package org.example.domain.finder;
import io.ebean.Finder;
import org.example.domain.Customer;
import org.example.domain.query.QCustomer;
/**
*/
public class CustomerFinder extends Finder<Long,Customer> {
public CustomerFinder() {
super(Customer.class);
}
public QCustomer typed() {
return new QCustomer();
}
}
@@ -0,0 +1,4 @@
package org.example.domain.otherpackage;
public interface Email<T> extends Comparable<T> {
}
@@ -0,0 +1,17 @@
package org.example.domain.otherpackage;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class PhoneAttributeConverter implements AttributeConverter<PhoneNumber, String> {
@Override
public String convertToDatabaseColumn(final PhoneNumber attribute) {
return attribute.getMsisdn();
}
@Override
public PhoneNumber convertToEntityAttribute(final String dbData) {
return new PhoneNumber(dbData);
}
}
@@ -0,0 +1,13 @@
package org.example.domain.otherpackage;
public class PhoneNumber {
private final String msisdn;
public PhoneNumber(final String msisdn) {
this.msisdn = msisdn;
}
public String getMsisdn() {
return msisdn;
}
}
@@ -0,0 +1,18 @@
package org.example.domain.otherpackage;
public class ValidEmail implements Email<ValidEmail> {
private final String emailAddress;
public ValidEmail(final String emailAddress) {
this.emailAddress = emailAddress;
}
public String getEmailAddress() {
return emailAddress;
}
@Override
public int compareTo(final ValidEmail o) {
return emailAddress.compareTo(o.emailAddress);
}
}
@@ -0,0 +1,17 @@
package org.example.domain.otherpackage;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class ValidEmailAttributeConverter implements AttributeConverter<ValidEmail, String> {
@Override
public String convertToDatabaseColumn(final ValidEmail attribute) {
return attribute.getEmailAddress();
}
@Override
public ValidEmail convertToEntityAttribute(final String dbData) {
return new ValidEmail(dbData);
}
}
@@ -0,0 +1,62 @@
package org.querytest;
import org.example.domain.Customer;
import org.junit.Test;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
public class QCustomerAndOrTest {
@Test
public void testEndAnd() {
Date fiveDays = fiveDaysAgo();
Customer.find.typed()
.status.equalTo(Customer.Status.GOOD)
.or()
.id.greaterThan(1000)
.and()
.name.startsWith("super")
.registered.after(fiveDays)
.endAnd()
.orderBy().id.desc()
.findList();
}
@Test
public void testQuery() {
Date fiveDays = fiveDaysAgo();
Customer.find.typed().name.like("DoesNotExist").delete();
List<Customer> customers =
Customer.find.typed()
.status.equalTo(Customer.Status.GOOD)
.or()
.id.greaterThan(1000)
.and()
.name.startsWith("super")
.registered.after(fiveDays)
.endJunction()
.orderBy().id.desc()
.findList();
// where t0.status = ? and (t0.id > ? or (t0.name like ? and t0.registered > ? ) ) order by t0.id desc; --bind(GOOD,1000,super%,Wed Jul 22 00:00:00 NZST 2015)
// where t0.status = ? and (t0.id > ? or (t0.name like ? and t0.registered > ? ) ) order by t0.id; --bind(GOOD,1000,super%,Wed Jul 22 00:00:00 NZST 2015)
// //where t0.id > ? and (t0.id < ? or (t0.name like ? and t0.name like ? ) ) order by t0.id; --bind(12,1234,one,two)
//
}
private Date fiveDaysAgo() {
LocalDateTime fiveDaysAgo = LocalDate.now().atStartOfDay().minusDays(5);
return new Date(fiveDaysAgo.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
}
}
@@ -0,0 +1,37 @@
package org.querytest;
import org.example.domain.Customer;
import org.example.domain.query.QCustomer;
import org.junit.Test;
import java.util.Date;
import java.util.List;
public class QCustomerSimpleLikeQueryTest {
@Test
public void testQuery() {
List<Customer> customers =
new QCustomer()
.name.ilike("rob")
.status.equalTo(Customer.Status.GOOD)
.registered.after(new Date())
.contacts.email.endsWith("@foo.com")
.orderBy()
.name.asc()
.registered.desc()
.findList();
//where lower(t0.name) like ? and t0.status = ? and t0.registered > ? and u1.email like ? order by t0.name, t0.registered desc; --bind(rob,GOOD,Mon Jul 27 12:05:37 NZST 2015,%@foo.com)
}
@Test
public void testFindEach() {
new QCustomer()
.status.equalTo(Customer.Status.GOOD)
.orderBy().id.asc()
.findEach(customer -> System.out.println("-- visit " + customer));
}
}
@@ -0,0 +1,842 @@
package org.querytest;
import io.ebean.DB;
import io.ebean.Database;
import io.ebean.PagedList;
import io.ebean.Query;
import io.ebean.QueryIterator;
import io.ebean.Transaction;
import io.ebean.annotation.Transactional;
import io.ebean.types.Inet;
import org.example.domain.ACat;
import org.example.domain.ADog;
import org.example.domain.Address;
import org.example.domain.Animal;
import org.example.domain.Country;
import org.example.domain.Customer;
import org.example.domain.otherpackage.PhoneNumber;
import org.example.domain.otherpackage.ValidEmail;
import org.example.domain.query.QAnimal;
import org.example.domain.query.QContact;
import org.example.domain.query.QCustomer;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.StringJoiner;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.example.domain.query.QAddress.Alias.country;
import static org.example.domain.query.QAddress.Alias.line1;
import static org.example.domain.query.QContact.Alias.lastName;
import static org.example.domain.query.QCustomer.Alias.billingAddress;
public class QCustomerTest {
@Rule
public final TestName testName = new TestName();
@Test
public void findWithTransaction() {
final Database database = DB.getDefault();
try (Transaction txn = database.createTransaction()) {
Customer customer = new Customer();
customer.setName("explicitTransaction");
database.save(customer, txn);
final Customer found = new QCustomer(txn)
.name.eq("explicitTransaction")
.findOne();
assertThat(found).isNotNull();
// not found using other transaction
final Customer foundNot = new QCustomer()
.name.eq("explicitTransaction")
.findOne();
assertThat(foundNot).isNull();
txn.commit();
}
}
@Test
public void findSingleAttribute() {
List<String> names = new QCustomer()
.setDistinct(true)
.select(QCustomer.alias().name)
.status.equalTo(Customer.Status.BAD)
.findSingleAttributeList();
assertThat(names).isNotNull();
}
@Test
public void findIterate() {
Customer cust = new Customer();
cust.setName("foo");
cust.setStatus(Customer.Status.GOOD);
cust.save();
List<Long> ids = new QCustomer()
.status.equalTo(Customer.Status.GOOD)
.findIds();
assertThat(ids).isNotEmpty();
Map<List, Customer> map = new QCustomer()
.status.equalTo(Customer.Status.GOOD)
.findMap();
assertThat(map.size()).isEqualTo(ids.size());
QueryIterator<Customer> iterate = new QCustomer()
.status.equalTo(Customer.Status.GOOD)
.findIterate();
try {
while (iterate.hasNext()) {
Customer customer = iterate.next();
assertThat(customer.getName()).isNotNull();
}
} finally {
iterate.close();
}
}
@Test
public void isEmpty() {
new QCustomer()
.contacts.isEmpty()
.findList();
new QCustomer()
.contacts.isNotEmpty()
.findList();
}
@Transactional
@Test
public void forUpdate() {
new QCustomer()
.id.eq(42)
.forUpdate()
.findOne();
new QCustomer()
.id.eq(42)
.forUpdateNoWait()
.findOne();
new QCustomer()
.id.eq(42)
.forUpdateSkipLocked()
.findOne();
}
@Ignore
@Test
public void arrayContains() {
new QContact()
.phoneNumbers.contains("4312")
.findList();
new QCustomer()
.contacts.phoneNumbers.contains("4312")
.findList();
}
@Test
public void setIncludeSoftDeletes() {
new QCustomer()
.setIdIn(42L)
.setIncludeSoftDeletes()
.findList();
}
@Test
public void testIdIn() {
new QCustomer()
.setIdIn("1", "2")
.findList();
new QCustomer()
.id.in(1L, 2L, 3L)
.findList();
}
@Test
public void testIn() {
new QCustomer()
.id.in(34L, 33L)
.name.in("asd", "foo", "bar")
.registered.in(new Date())
.findList();
}
@Test
public void usingTransaction() {
try (Transaction transaction = DB.getDefault().createTransaction()) {
new QCustomer()
.registered.isNull()
.usingTransaction(transaction)
.findList();
}
}
@Test
public void usingConnection() throws SQLException {
Customer cust = new Customer();
cust.setName("usingConnection");
cust.setStatus(Customer.Status.GOOD);
cust.save();
DataSource dataSource = DB.getDefault().getPluginApi().getDataSource();
try (Connection connection = dataSource.getConnection()) {
List<Customer> foo = new QCustomer()
.name.eq("usingConnection")
.usingConnection(connection)
.findList();
assertThat(foo).hasSize(1);
}
}
@Test
public void testAssocOne() {
Address address = new Address();
address.setId(41L);
new QCustomer()
.billingAddress.eq(address)
.findList();
new QCustomer()
.billingAddress.equalTo(address)
.findList();
new QCustomer()
.billingAddress.ne(address)
.findList();
new QCustomer()
.billingAddress.notEqualTo(address)
.findList();
}
@Test
public void testInOrEmpty() {
List<String> names = Arrays.asList("asd", "foo", "bar");
new QCustomer()
.registered.before(new Date())
.name.inOrEmpty(names)
.findList();
new QCustomer()
.registered.before(new Date())
.name.inOrEmpty(null)
.findList();
names = Collections.emptyList();
new QCustomer()
.registered.before(new Date())
.name.inOrEmpty(names)
.findList();
}
@Test
public void testNotIn() {
new QCustomer()
.id.isIn(34L, 33L)
.name.notIn("asd", "foo", "bar")
.registered.in(new Date())
.findList();
}
@Test
public void testQueryBoolean() {
new QCustomer()
.name.contains("rob")
//.setUseDocStore(true)
.setMaxRows(10)
.findPagedList();
new QCustomer()
.inactive.isFalse()
.findList();
}
@Test
public void testFindOne() {
new QCustomer()
.name.isIn("rob", "foo")
//.setUseDocStore(true)
.setMaxRows(1)
.findOne();
Optional<Customer> maybe = new QCustomer()
.name.contains("rob")
//.setUseDocStore(true)
.setMaxRows(1)
.findOneOrEmpty();
maybe.isPresent();
new QCustomer()
.inactive.isFalse()
.findList();
}
private void insertCustomer(String name) {
Customer cust = new Customer();
cust.setName(name);
cust.setStatus(Customer.Status.GOOD);
cust.save();
}
@Test
public void testFindStream() {
insertCustomer("stream1");
insertCustomer("stream2");
StringJoiner sb = new StringJoiner("|");
try (Stream<Customer> stream = new QCustomer()
.name.startsWith("stream")
.id.asc()
.findStream()) {
stream.forEach(it -> sb.add(it.getName()));
}
assertThat(sb.toString()).isEqualTo("stream1|stream2");
}
@Test
public void testFindLargeStream() {
insertCustomer("largeStream1");
insertCustomer("largeStream2");
insertCustomer("largeStream3");
StringJoiner sb = new StringJoiner("|");
try (Stream<Customer> stream = new QCustomer()
.name.startsWith("largeStream")
.id.asc()
.findLargeStream()) {
stream.forEach(it -> sb.add(it.getName()));
}
assertThat(sb.toString()).isEqualTo("largeStream1|largeStream2|largeStream3");
}
@Test
public void testFilterMany() {
Customer cust = new Customer();
cust.setName("Postgres Foo");
cust.setStatus(Customer.Status.GOOD);
cust.save();
new QCustomer()
.name.startsWith("Postgres")
.contacts.filterMany("firstName istartsWith ?", "Rob")
.findList();
final LocalDate startDate = LocalDate.now().minusDays(7);
final LocalDate endDate = LocalDate.now();
new QCustomer()
.name.startsWith("Postgres")
.contacts.filterMany("whenCreated inRange ? to ?", startDate, endDate)
.findList();
}
@Test
public void testDate_lessThan() {
assertContains(new QCustomer().registered.lt(new Date()).query(), " where t0.registered < ?");
assertContains(new QCustomer().registered.before(new Date()).query(), " where t0.registered < ?");
assertContains(new QCustomer().registered.lessThan(new Date()).query(), " where t0.registered < ?");
}
@Test
public void testDate_lessOrEqualTo() {
assertContains(new QCustomer().registered.le(new Date()).query(), " where t0.registered <= ?");
assertContains(new QCustomer().registered.lessOrEqualTo(new Date()).query(), " where t0.registered <= ?");
}
@Test
public void testDate_greaterThan() {
assertContains(new QCustomer().registered.after(new Date()).query(), " where t0.registered > ?");
assertContains(new QCustomer().registered.gt(new Date()).query(), " where t0.registered > ?");
assertContains(new QCustomer().registered.greaterThan(new Date()).query(), " where t0.registered > ?");
}
@Test
public void testDate_greaterOrEqualTo() {
assertContains(new QCustomer().registered.ge(new Date()).query(), " where t0.registered >= ?");
assertContains(new QCustomer().registered.greaterOrEqualTo(new Date()).query(), " where t0.registered >= ?");
}
private void assertContains(Query<Customer> query, String match) {
query.findList();
assertThat(query.getGeneratedSql()).contains(match);
}
@Test
public void query_setAllowLoadErrors() {
new QCustomer()
.status.in(Customer.Status.GOOD)
.setAllowLoadErrors()
.findList();
}
@Test
public void query_setInheritType() {
ACat cat = new ACat("C1");
cat.save();
ACat cat2 = new ACat("C2");
cat2.save();
ADog dog = new ADog("D1", "D878");
dog.save();
List<Animal> animals = new QAnimal()
.id.greaterOrEqualTo(1L)
.setInheritType(ACat.class)
.findList();
System.out.println(animals);
}
@Test
public void select_assocManyToOne() {
Country nz = new Country("NZ", "New Zealand");
DB.merge(nz);
Address address = new Address();
address.setLine1("42 below");
address.setCountry(nz);
Customer customer0 = new Customer();
customer0.setName("asdBilling0");
customer0.setBillingAddress(address);
customer0.save();
Customer customer1 = new Customer();
customer1.setName("asdBilling1");
customer1.setBillingAddress(new Address());
customer1.save();
List<Long> billingAddressIds
= new QCustomer()
.select(billingAddress)
.name.startsWith("asdBilling")
.findSingleAttributeList();
assertThat(billingAddressIds).hasSize(2);
Map<Long,Customer> map
= new QCustomer()
.billingAddress.id.asMapKey()
.name.startsWith("asdBilling")
.findMap();
assertThat(map).hasSize(2);
List<Customer> customers = new QCustomer()
.billingAddress.fetch(line1, country)
.findList();
assertThat(customers).isNotEmpty();
}
@Test
public void query_fetchString() {
Customer cust = new Customer();
cust.setName("baz");
cust.setCurrentInet(new Inet("129.1.1.4"));
cust.setStatus(Customer.Status.GOOD);
cust.save();
new QCustomer()
.currentInet.eq(Inet.of("129.1.1.4"))
.findList();
new QCustomer()
.currentInet.in(Inet.setOf("129.1.1.4","129.1.1.5"))
.findList();
new QCustomer()
.contacts.fetch("email")
.orderBy()
.name.asc()
.contacts.email.asc()
.findList();
new QCustomer()
.contacts.fetchQuery("email")
.orderBy()
.name.asc()
.contacts.email.asc()
.findList();
}
@Test
public void query_setBaseTable() {
new QCustomer()
.setBaseTable("BE_CUSTOMER")
.findList();
}
@Test
public void query_rawOrEmpty() {
List<String> names = Arrays.asList("A", "B");
new QCustomer()
.rawOrEmpty("name in (?1)", names)
.findList();
new QCustomer()
.rawOrEmpty("name in (?1)", null)
.findList();
new QCustomer()
.rawOrEmpty("name in (?1)", new ArrayList<Long>())
.findList();
}
@Test
public void query_orNull() {
new QCustomer()
.name.equalToOrNull("A")
.findList();
new QCustomer()
.name.eqOrNull("A")
.findList();
new QCustomer()
.name.greaterThanOrNull("B")
.findList();
new QCustomer()
.name.lessThanOrNull("C")
.findList();
new QCustomer()
.name.gtOrNull("GT1")
.name.geOrNull("GE1")
.name.ltOrNull("LT1")
.name.leOrNull("LE1")
.findList();
}
@Test
public void query_inRange() {
new QCustomer()
.name.inRange("A", "B")
.findList();
new QCustomer()
.name.greaterOrEqualTo("A")
.name.lessThan("B")
.findList();
new QContact()
.firstName.inRangeWith(lastName, "B")
.findList();
}
@Test
public void query_exists() {
boolean customerExists =
new QCustomer()
.name.equalTo("DoesNotExistReally")
.exists();
assertThat(customerExists).isFalse();
}
@Test
public void testQuery() {
QContact contact = QContact.alias();
QCustomer cust = QCustomer.alias();
new QCustomer()
// tune query
.select(cust.name)
.status.isIn(Customer.Status.BAD, Customer.Status.BAD)
.contacts.fetch()
// predicates
.findList();
new QCustomer()
// tune query
.select(cust.name)
.contacts.fetch()
// predicates
.findList();
new QCustomer()
// tune query
.select(cust.id, cust.name)
.contacts.fetch(contact.firstName, contact.lastName, contact.email)
// predicates
.id.greaterThan(1)
.findList();
PagedList<Customer> pagedList = new QCustomer()
// tune query
.select(cust.id, cust.name)
.contacts.fetch(contact.firstName, contact.lastName, contact.email)
// predicates
.id.greaterThan(1)
.setFirstRow(20)
.setMaxRows(10)
.findPagedList();
pagedList.getList();
pagedList.getList();
// new QCustomer()
// .asDraft()
// .findList();
//
// new QCustomer()
// .includeSoftDeletes()
// .findList();
// List<Contact> contacts
// = new QContact()
// .email.like("asd")
// .notes.title.like("asd")
// .orderBy()
// .id.desc()
// .findList();
//
// List<Customer> customers = new QCustomer()
// .id.eq(1234)
// .status.equalTo(Customer.Status.BAD)
// .status.in(Customer.Status.GOOD, Customer.Status.MIDDLING)
// //.status.eq(Order.Status.APPROVED)
// .name.like("asd")
// .name.istartsWith("ASdf")
// .registered.after(new Date())
// .contacts.email.endsWith("@foo.com")
// .contacts.notes.id.greaterThan(123L)
// .orderBy().id.asc()
// .findList();
// //Customer customer3 =
// new QCustomer()
// .id.gt(12)
// .or()
// .id.lt(1234)
// .and()
// .name.like("one")
// .name.like("two")
// .endAnd()
// .endOr()
// .orderBy().id.asc()
// .findList();
//
// //where t0.id > ? and (t0.id < ? or (t0.name like ? and t0.name like ? ) ) order by t0.id; --bind(12,1234,one,two)
//
//// List<Customer> customers
//// = new QCustomer()
//// .name.like("asd")
//// .findList();
//
// Customer.find.where()
// .gt("id", 1234)
// .disjunction().eq("id", 1234).like("name", "asd")
// .endJunction().findList();
// QCustomer cust = QCustomer.I;
// ExpressionList<Customer> expr = new QCustomer().expr();
// expr.eq(cust.contacts.email, 123);
}
@Test
public void testFindSet() {
Set<Customer> customerSet = new QCustomer().findSet();
Assert.assertNotNull(customerSet);
}
@Test
public void testFindMap() {
Customer cust = new Customer();
cust.setName("banana");
cust.setStatus(Customer.Status.GOOD);
cust.save();
Map<String, Customer> map = new QCustomer()
.id.greaterOrEqualTo(1L)
.name.asMapKey()
.findMap();
assertThat(map.get("banana")).isNotNull();
}
@Test
public void testAsUpdate() {
int rows = new QContact()
.notes.note.startsWith("Make Inactive")
.email.endsWith("@foo.com")
.asUpdate()
.setRaw("email = lower(email)")
//.set("inactive", true)
.update();
assertThat(rows).isEqualTo(0);
}
@Test
public void testSelectFormula() {
Customer cust = new Customer();
cust.setName("junk junk");
cust.setStatus(Customer.Status.GOOD);
cust.setRegistered(new Date());
cust.save();
java.util.Date maxDate = new QCustomer()
.select("max(registered)")
.findSingleAttribute();
assertThat(maxDate).isNotNull();
}
@Test
public void testFetchByScalarValue() {
Customer cust = new Customer();
cust.setName(testName.getMethodName());
cust.setPhoneNumber(new PhoneNumber("+18005555555"));
cust.save();
assertThat(new QCustomer()
.name.eq(testName.getMethodName())
.phoneNumber.eq(new PhoneNumber("+18005555555"))
.findOne()).isNotNull();
}
@Test
public void testFetchByComparableScalarValue() {
Customer cust = new Customer();
cust.setName(testName.getMethodName());
cust.setEmail(new ValidEmail("foo2@example.org"));
cust.save();
assertThat(new QCustomer()
.name.eq(testName.getMethodName())
.email.eq(new ValidEmail("foo2@example.org"))
.findOne()).isNotNull();
assertThat(new QCustomer()
.name.eq(testName.getMethodName())
.email.gt(new ValidEmail("foo2@example.org"))
.findOne()).isNull();
assertThat(new QCustomer()
.name.eq(testName.getMethodName())
.email.gt(new ValidEmail("foo1@example.org"))
.findOne()).isNotNull();
assertThat(new QCustomer()
.name.eq(testName.getMethodName())
.email.greaterOrEqualTo(new ValidEmail("foo2@example.org"))
.findOne()).isNotNull();
}
@Test
public void testFetchFormula() {
Customer cust = new Customer();
cust.setName("junk junk");
cust.setStatus(Customer.Status.GOOD);
cust.setRegistered(new Date());
cust.save();
List<C1dto> dtos = new QCustomer()
.select("id, name")
.asDto(C1dto.class)
.findList();
assertThat(dtos).isNotEmpty();
}
public static class C1dto {
final long id;
final String name;
public C1dto(long id, String name) {
this.id = id;
this.name = name;
}
}
}
@@ -0,0 +1,44 @@
package org.querytest;
import io.ebean.FetchGroup;
import org.example.domain.Order;
import org.example.domain.query.QCustomer;
import org.example.domain.query.QOrder;
import org.junit.Test;
public class QOrderTest {
private static final QCustomer cu = QCustomer.alias();
private static final QOrder or = QOrder.alias();
private static final FetchGroup<Order> fg = QOrder.forFetchGroup()
.select(or.status, or.shipDate)
.customer.fetchCache(cu.name, cu.status, cu.registered, cu.comments)
.buildFetchGroup();
@Test
public void fetchCache() {
new QOrder()
.status.eq(Order.Status.NEW)
.customer.fetchCache(cu.name, cu.registered)
.findList();
new QOrder()
.status.eq(Order.Status.NEW)
.customer.fetchCache()
.findList();
}
@Test
public void viaFetchGraph() {
new QOrder()
.status.eq(Order.Status.NEW)
.select(fg)
.findList();
}
}