前段时间一直忙项目,而且一直在用 typescript 写动态查询,结果一看 java 版本已经一年没有更新了,感觉要加点东西了。
更新了两点:
默认来说,我们会把所有的字段全部返回,有些字段我们不想返回,比如 password
下面我们来看个例子:
@Table(name = "product") public class Product{ @Column(name = "product_id", insertable = false, updatable = false) private Integer productID; private String productName; private BigDecimal price; private Integer categoryID; ... }
public interface ProductDaoextends DynamicQueryMapper<Product>{ }
@Test public void testSelectFields(){ DynamicQuery<Product> dynamicQuery = DynamicQuery.createQuery(Product.class) .addSelectField(Product::getProductName) .addSelectField(Product::getPrice); List<Product> products = PageHelper.startPage(0, 3, false) .doSelectPage(() -> productDao.selectByDynamicQuery(dynamicQuery)); for (Product p : products) { // categoryID ignore to select assertEquals(null, p.getCategoryID()); assertEquals(true, StringUtils.isNotBlank(p.getProductName())); } }
==> Preparing: SELECT price AS price, product_name AS product_name FROM product LIMIT 3 ==> Parameters: <== Columns: PRICE, PRODUCT_NAME <== Row: 18.0000, Northwind Traders Chai <== Row: 7.5000, Northwind Traders Syrup <== Row: 16.5000, Northwind Traders Cajun Seasoning <== Total: 3
为了让代码写的比较舒服,不用再手动 new FilterDescritpor 了。
@Resource private ProductDao productDao; @Test public void testLinkOperation(){ DynamicQuery<Product> dynamicQuery = DynamicQuery.createQuery(Product.class) .addSelectField(Product::getProductID) .addSelectField(Product::getProductName) .addSelectField(Product::getPrice) .addFilterDescriptor(Product::getPrice, FilterOperator.GREATER_THAN, 16) .addSortDescriptor(Product::getPrice, SortDirection.DESC) .addSortDescriptor(Product::getProductID, SortDirection.DESC); List<Product> products = PageHelper.startPage(0, 100, false) .doSelectPage(() -> productDao.selectByDynamicQuery(dynamicQuery)); for (Product p : products) { // categoryID ignore to select assertEquals(null, p.getCategoryID()); assertEquals(true, StringUtils.isNotBlank(p.getProductName())); // price > 16 assertEquals(1, p.getPrice().compareTo(BigDecimal.valueOf(16))); } }
看一下输出结果和用 new FilterDescriptor,new SortDesciptor 效果是一样的, 并且在价格一样的时候,ID 是倒叙排列的。
==> Preparing: SELECT product_id AS product_id, price AS price, product_name AS product_name FROM product WHERE (price > ?) ORDER BY price DESC, product_id DESC LIMIT 100 ==> Parameters: 16(Integer) <== Columns: PRODUCT_ID, PRICE, PRODUCT_NAME <== Row: 1, 18.0000, Northwind Traders Chai <== Row: 4, 16.5000, Northwind Traders Olive Oil <== Row: 3, 16.5000, Northwind Traders Cajun Seasoning <== Total: 3
时隔一年已经在项目中一直使用,感觉还是蛮顺手的,希望大家能支持一下。