1 高級查詢基礎版
操作步驟:
1.建立高級查詢表對象:XxxQuery/XxxQueryObject.(Xxx表示對象名稱);
ProductQueryObject(商品的高級查詢對象),封裝了商品高級查詢表單的數據
2.在IproductDAO中定義高級查詢方法:
List<Product> query(ProductQueryObject qo);
3.在ProductDAOImpl中提供高級查詢方法的實現
4.後臺測試。
建立高級查詢表對象
public class ProductQueryObject {
private String productName;//商品名稱
private BigDecimal minSalePrice;//最低商品零售價
private BigDecimal maxSalePrice;//最高商品零售價
//getter/setter
public String getProductName() {
return productName;
}
public BigDecimal getMinSalePrice() {
return minSalePrice;
}
public BigDecimal getMaxSalePrice() {
return maxSalePrice;
}
public void setProductName(String productName) {
this.productName = productName;
}
public void setMinSalePrice(BigDecimal minSalePrice) {
this.minSalePrice = minSalePrice;
}
public void setMaxSalePrice(BigDecimal maxSalePrice) {
this.maxSalePrice = maxSalePrice;
}
}
在IproductDAO中定義高級查詢方法
public interface IProductDAO {
List<Product> list();
//高級查詢的方法
List<Product> query (ProductQueryObject qo);
}
在ProductDAOImpl中提供高級查詢方法的實現
public class ProductDAOImpl implements IProductDAO {
public List<Product> query(ProductQueryObject qo) {
SqlSession session = MyBatisUtil.INSTANCE .openSession();
//-------------------------------------------------------
//拼接SQL
StringBuilder sql = new StringBuilder(" WHERE 1=1 ");
Map<String,Object> sqlMap = new HashMap<>();
//若輸入了商品名稱
if(StringUtil.hasLength(qo.getProductName())){//名字佔位符
sql.append(" AND productName LIKE CONCAT('%',#{name},'%')");
sqlMap.put("name", qo.getProductName());
}
//最低零售價
if(qo.getMinSalePrice()!=null){
sql.append(" AND salePrice >= #{minSalePrice}");
sqlMap.put("minSalePrice",qo.getMinSalePrice());
}
//最高零售價
if(qo.getMaxSalePrice()!=null){
sql.append(" AND salePrice <= #{maxSalePrice}");
sqlMap.put("maxSalePrice", qo.getMaxSalePrice());
}
//-------------------------------------------------------
try {
sqlMap.put("querySql", sql.toString());
return session.selectList("cn.itsource.shopping.mapper.ProductMapper.advanceQuery", sqlMap);
} finally {
session.close();
}
}
}
後臺測試
@Test
public void testQuery() {
ProductQueryObject qo = new ProductQueryObject();
qo.setProductName("iphone8s");
qo.setMinSalePrice(new BigDecimal("6000"));
qo.setMaxSalePrice(new BigDecimal("9000"));
//------------------------------------
List<Product> list = dao.query(null);
for (Product p : list) {
System.out.println(p);`
}
}
xml映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 映射Product對象和對應表關係的,操作該表/對象的SQL全部都寫在這裏 -->
<mapper namespace="cn.itsource.shopping.mapper.ProductMapper">
<!-- 查詢所有 -->
<select id="list" resultType="Product">
SELECT * FROM product
</select>
<!-- 高級查詢 -->
<select id="advanceQuery" parameterType="map" resultType="Product">
SELECT * FROM product ${querySql}
</select>
</mapper>
MyBatais的XML配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 引入db.properties文件 -->
<properties resource="db.properties" />
<!-- 爲類型起別名 -->
<typeAliases>
<typeAlias type="cn.itsource.shopping.domain.Product" alias="Product" />
</typeAliases>
<!-- 環境配置 -->
<environments default="development">
<!-- 連接數據的基本信息 -->
<environment id="development">
<!-- 事務管理器:JDBC的管理機制 -->
<transactionManager type="JDBC" />
<!-- 配置連接池(數據源) -->
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${usename}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<!-- 關聯映射文件 -->
<mappers>
<mapper resource="cn\itsource\shopping\domain\ProductMapper.xml" />
</mappers>
</configuration>
db.properties配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcdemo?useSSL=false
usename=root
password=111111
MyBatisUtil工具類
public enum MyBatisUtil {
INSTANCE;
private static SqlSessionFactory sessionFactory = null;
static {
try {
sessionFactory = new SqlSessionFactoryBuilder().build(Resources
.getResourceAsStream("MyBatis-config.xml"));
} catch (IOException e) {
e.printStackTrace();
}
}
public SqlSession openSession() {
return sessionFactory.openSession();
}
}
StringUtil工具類
public class StringUtil {
public static boolean hasLength(String str) {
return str != null && !"".equals(str.trim());
}
}
商品對象類
public class Product {
private Long id;
private String productName;
private String brand;
private String supplier;
private BigDecimal salePrice;
private BigDecimal costPrice;
private Double cutoff;
private Long dir_id;//分類編號
public Long getId() {
return id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getBrand() {
return brand;
}
public String getSupplier() {
return supplier;
}
public BigDecimal getSalePrice() {
return salePrice;
}
public BigDecimal getCostPrice() {
return costPrice;
}
public Double getCutoff() {
return cutoff;
}
public Long getDir_id() {
return dir_id;
}
public void setId(Long id) {
this.id = id;
}
public void setBrand(String brand) {
this.brand = brand;
}
public void setSupplier(String supplier) {
this.supplier = supplier;
}
public void setSalePrice(BigDecimal salePrice) {
this.salePrice = salePrice;
}
public void setCostPrice(BigDecimal costPrice) {
this.costPrice = costPrice;
}
public void setCutoff(Double cutoff) {
this.cutoff = cutoff;
}
public void setDir_id(Long dir_id) {
this.dir_id = dir_id;
}
public String toString() {
return "Product [id=" + id + ", productName=" + productName + ", brand=" + brand + ", suppliet=" + supplier
+ ", salePrice=" + salePrice + ", costPrice=" + costPrice + ", cutoff=" + cutoff + ", dir_id=" + dir_id
+ "]";
}
}