hibernate的對象查詢與sql語句的對應(yīng)

字號:

1:
    SELECT * FROM ORDER
    對應(yīng)的hibernate對象查詢:
    List orders= session.createCriteria(Order.class).list();
    2:
    SELECT NAME,ID FROM PRODUCT
    對應(yīng)的hibernate對象查詢:
    List products =session.createCriteria(Product.class).setProjection(
    Projections.propertyList()
    .add(Projections.property(\"name\"))
    .add(Projections.property(\"id\"))
    ).list();
    3:
    SELECT O.*, P.* FROM ORDERS O, PRODUCT P WHERE O.ORDER_ID=P.ORDER_ID;
    對應(yīng)的hibernate對象查詢:
    List orders = session.createCriteria(Order.class)
    .setFetchMode(“products”,FetchMode.JOIN)
    .list();
    4:
    SELECT * FROM ORDERS WHERE ORDER_ID=’1092’;
    對應(yīng)的hibernate對象查詢:
    List orders= session.createCriteria(Order.class)
    .add(Restrictions.eq(“orderId”,”1092”))
    .list();
    5:
    SELECT O.*, P.* FROM ORDERS O, PRODUCT P WHERE
    O.ORDER_ID=P.ORDER_ID AND P.ID=’1111’;
    對應(yīng)的hibernate對象查詢:
    List orders = session.createCriteria(Order.class)
    .setFetchMode(“products”,FetchMode.JOIN)
    .add(Restrictions.eq(“id”,”1111”))
    .list();
    6:
    SELECT COUNT(ID) FROM ORDER HAVING PRICETOTAL>2000 GROUP BY ID
    對應(yīng)的hibernate對象查詢:
    List orders = session.createCriteria(Order.class)
    .setProjection( Projections.projectionList()
    .add( Projections.count(“id”) )
    .add( Projections.groupProperty(“id”) )
    )
    .list();
    考試大整理:查詢總結(jié):
    (1)如何得到session:
    Configuration cfg = new Configuration()
    .addClass(Order.class);
    SessionFactory sf = cfg.buildSessionFactory();
    // open session
    Session sess = sf.openSession();
    (2)HQL方法
    String query = "select o from o "
    + "Order as o join o.products as p "
    + "where o.priceTotal > :priceTotalLower "
    + "and o.priceTotal < :priceTotalUpper";
    Query q = sess.createQuery(query);
    q.setDouble("priceTotalLower",
    Double.parseDouble(lower));
    q.setDouble("priceTotalUpper",
    Double.parseDouble(upper))
    q.list();
    (3)Criteria
    List list = sess.createCriteria(Order.class)
    .add(Restrictions.between(lower,upper)
    . list();
    Order o=(Order)list.iterator.next();