Generating Criteria
- Open CriteriaTest.vpp in Visual Paradigm.
- Select Tools > Hibernate > Generate Code... from the application toolbar.
- The Database Code Generation window appear. Keep the option Generate Criteria selected. Click OK to start generating ORM code.
- If you don't have any default database chosen, you are now asked to select one. Select the DBMS you use and fill in the connection settings in the Database Configuration window, and then confirm.
Criteria classes are generated for each ORM persistable class.
Using Criteria
- Execute the Java class CreateOrmDatabaseSchema in the generated ormsamples package to create database tables.
- Download the sample java code Create.java. You can also find this file at the bottom of this tutorial.
- Execute the Java class Create to create sample data.
-
Create a class with the following code to retrieve all open order, sort by descending order data:
OrderCriteria orderCriteria = new OrderCriteria(); orderCriteria.status.eq(Order.STATUS_OPEN); orderCriteria.orderDate.order(false); Order[] listOrder = orderCriteria.listOrder(); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); for (int i = 0; i < listOrder.length; i++) { System.out.println(listOrder[i].getCustomer().getAccountNo() + ", " + dateFormat.format(listOrder[i].getOrderDate()) + ", " + (listOrder[i].getStatus() == Order.STATUS_OPEN)); }
More Examples on Criteria
-
Join multiple tables with conditions:
OrderLineCriteria orderLineCriteria = new OrderLineCriteria(); // quantity less than 5 orderLineCriteria.quantity.lt(5); // join order table OrderCriteria orderCriteria = orderLineCriteria.createOrderCriteria(); orderCriteria.status.eq(Order.STATUS_OPEN); // join customer table CustomerCriteria customerCriteria = orderCriteria.createCustomerCriteria(); customerCriteria.accountNo.eq("C1232122"); OrderLine[] listOrderLine = orderLineCriteria.listOrderLine(); for (int i = 0; i < listOrderLine.length; i++) { System.out.println(listOrderLine[i].getItemNo() + ", " + listOrderLine[i].getQuantity()); }
-
Calculate the total quantity of all open orders:
OrderLineCriteria orderLineCriteria = new OrderLineCriteria(); // join order table OrderCriteria orderCriteria = orderLineCriteria.createOrderCriteria(); orderCriteria.status.eq(Order.STATUS_OPEN); orderLineCriteria.setProjection(Projections.sum(OrderLine.PROP_QUANTITY)); System.out.println(orderLineCriteria.uniqueResult());
-
Controlling the first and number of results, useful for pagination:
OrderCriteria orderCriteria = new OrderCriteria(); orderCriteria.setFirstResult(11); orderCriteria.setMaxResults(10); Order[] listOrder = orderCriteria.listOrder(); for (int i = 0; i < listOrder.length; i++) { System.out.println(listOrder[i].getID()); }