QBE高级搜索 : 查询示例 « Hibernate « Java 教程

En
Java 教程
1. 语言基础
2. 数据类型
3. 操作符
4. 流程控制
5. 类定义
6. 开发相关
7. 反射
8. 正则表达式
9. 集合
10. 线
11. 文件
12. 泛型
13. 本土化
14. Swing
15. Swing事件
16. 二维图形
17. SWT
18. SWT 二维图形
19. 网络
20. 数据库
21. Hibernate
22. JPA
23. JSP
24. JSTL
25. Servlet
26. Web服务SOA
27. EJB3
28. Spring
29. PDF
30. 电子邮件
31. 基于J2ME
32. J2EE应用
33. XML
34. 设计模式
35. 日志
36. 安全
37. Apache工具
38. 蚂蚁编译
39. JUnit单元测试
Java
Java 教程 » Hibernate » 查询示例 
21. 16. 2. QBE高级搜索

File: Main.java

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Example;

public class Main {
  public static void main(String[] argsthrows Exception {
    HibernateUtil hibernateUtil = new HibernateUtil();
    hibernateUtil
        .executeSQLCommand("create table Product(id int, name varchar, description varchar, price decimal(6,2), supplierid int)");
     
    hibernateUtil
    .executeSQLCommand("create table Supplier (id int , name varchar)");

    hibernateUtil
    .executeSQLCommand("create table Software(id int, name varchar, description varchar, price decimal(6,2), supplierid int, version varchar)");

    
    Session session = hibernateUtil.getSession();

    Supplier superCorp = new Supplier();
    superCorp.setName("Supplier1");
    session.save(superCorp);
    
    Supplier megaInc = new Supplier();
    megaInc.setName("Supplier2");
    session.save(megaInc);        

    Product mouse = new Product("Product1","first product"20.0);
    mouse.setSupplier(superCorp);
    superCorp.getProducts().add(mouse);
    session.flush();
    Product mouse2 = new Product("Product2","second product"22.0);
    mouse2.setSupplier(superCorp);
    superCorp.getProducts().add(mouse2);        
    
    Product keyboard = new Product("Product3""third product"30.0);
    keyboard.setSupplier(megaInc);
    megaInc.getProducts().add(keyboard);

    Software webBrowser = new Software("Web Browser","new browser"75.0"2.0");
    webBrowser.setSupplier(superCorp);
    superCorp.getProducts().add(webBrowser);

    Software email = new Software("Email","email client"49.99"4.1 Edition");
    email.setSupplier(megaInc);
    megaInc.getProducts().add(email);    

    session.flush();
    
    
    Criteria prdCrit = session.createCriteria(Product.class);
    Product product = new Product();
    product.setName("P%");
    Example prdExample = Example.create(product);
    prdExample.excludeProperty("price");
    prdExample.enableLike();
    Criteria suppCrit = prdCrit.createCriteria("supplier");
    Supplier supplier = new Supplier();
    supplier.setName("Supplier2");
    suppCrit.add(Example.create(supplier));
    prdCrit.add(prdExample);
    List results = prdCrit.list();


    System.out.println(results);
    
    session.close();
    hibernateUtil.checkData("select * from Product");
    hibernateUtil.checkData("select * from Software");
    hibernateUtil.checkData("select * from Supplier");
  }
}

File: Product.hbm.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping
   PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
   <class name="Product">
      <id name="id" type="int">
         <generator class="increment"/>
      </id>

      <property name="name" type="string"/>
      <property name="description" type="string"/>
      <property name="price" type="double"/>
      <many-to-one name="supplier" class="Supplier" column="supplierId"/>

   </class>
   
   <query name="Product.HQLpricing">
     select product.price from Product product where product.price = 25.0
       </query>   
   <sql-query name="Product.SQLpricing">
   <return-scalar column="price" type="double"/>
     select product.price from Product as product where product.price = 25.0
  </sql-query>     
</hibernate-mapping>

File: Product.java

public class Product
{
    private int id;
    private Supplier supplier;
    
    private String name;
    private String description;
    private double price;
    
    public Product()
    {
        super();
    }
    
    public Product(String name, String description, double price)
    {
        super();
        this.name = name;
        this.description = description;
        this.price = price;
    }
    
    public String getDescription()
    {
        return description;
    }
    public void setDescription(String description)
    {
        this.description = description;
    }
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
 
    public Supplier getSupplier()
    {
        return supplier;
    }
    public void setSupplier(Supplier supplier)
    {
        this.supplier = supplier;
    }
    
    public double getPrice()
    {
        return price;
    }
    public void setPrice(double price)
    {
        this.price = price;
    }
}

File: Software.hbm.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping
   PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
   <joined-subclass name="Software" extends="Product">
      <key column="Id"/>
      <property name="version" type="string"/>
   </joined-subclass>
</hibernate-mapping>

File: Software.java

public class Software extends Product
{
    private String version;
    
    public Software()
    {
        super();
    }
    
    public Software(String name, String description, double price, String version)
    {
        super(name, description, price);
        this.setVersion(version);
    }

    public String getVersion()
    {
        return version;
    }
    public void setVersion(String version)
    {
        this.version = version;
    }
}

File: Supplier.hbm.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping
   PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
   <class name="Supplier" >
      <id name="id" type="int">
         <generator class="increment"/>
      </id>

      <property name="name" type="string"/>
      <bag name="products" inverse="true" cascade="all,delete-orphan">
        <key column="supplierId"/>
        <one-to-many class="Product"/>
      </bag>


   </class>
</hibernate-mapping>

File: Supplier.java

import java.util.ArrayList;
import java.util.List;

public class Supplier
{
    private int id;
    private String name;
    private List products = new ArrayList();
    
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public List getProducts()
    {
        return products;
    }
    public void setProducts(List products)
    {
        this.products = products;
    }
}

File: hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
        <property name="connection.url">jdbc:hsqldb:data/tutorial</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in-->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
        <!-- Enable Hibernate's current session context -->
        <property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>

        <property name="hibernate.cache.use_second_level_cache">false</property>
        <property name="hibernate.cache.use_query_cache">false</property>
        
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>        
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        
        <!-- Mapping files -->
        <mapping resource="Product.hbm.xml"/>
        <mapping resource="Software.hbm.xml"/>
        <mapping resource="Supplier.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

File: HibernateUtil.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
  Session session;
  Statement st;
  public HibernateUtil() throws Exception{
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    session = sessionFactory.openSession();

    // Load the JDBC driver.
    Class.forName("org.hsqldb.jdbcDriver");
    System.out.println("Driver Loaded.");
    // Establish the connection to the database.
    String url = "jdbc:hsqldb:data/tutorial";

    Connection conn = DriverManager.getConnection(url, "sa""");
    System.out.println("Got Connection.");
    st = conn.createStatement();
  }
  public Session getSession(){
    return session;
  }
  public void executeSQLCommand(String sqlthrows Exception {
    st.executeUpdate(sql);
  }

  public void checkData(String sqlthrows Exception {
    ResultSet rs = st.executeQuery(sql);
    ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 0; i < metadata.getColumnCount(); i++) {
      System.out.print("\t"+ metadata.getColumnLabel(i + 1))
    }
    System.out.println("\n----------------------------------");

    while (rs.next()) {
      for (int i = 0; i < metadata.getColumnCount(); i++) {
        Object value = rs.getObject(i + 1);
        if (value == null) {
          System.out.print("\t       ");
        else {
          System.out.print("\t"+value.toString().trim());
        }
      }
      System.out.println("");
    }
  }
}
  Download:  HibernateQBEAdvancedCriteria.zip( 4,866 k)
21. 16. 查询示例
21. 16. 1. 查询的范例
21. 16. 2. QBE高级搜索
21. 16. 3. QBE条件:非空或零
www.java2java.com | Contact Us
Copyright 2010 - 2030 Java Source and Support. All rights reserved.
All other trademarks are property of their respective owners.