query database first!
mysql> select * from product; +----+--------+----------+ | id | name | qq | +----+--------+----------+ | 1 | apple | 20121212 | | 2 | orange | 20111111 | | 3 | banana | 20122222 | | 4 | apple | 20122222 | | 5 | apple | 20122222 | | 6 | apple | 201222qq | +----+--------+----------+ 6 rows in set (0.00 sec) mysql>
?
【1、 HQL查詢 】:
?
hibernate管理類!
?
package com.bubble.util; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; /** * @author bubble * */ public class HibernateUtil { // single private static final SessionFactory sessionFactory; static{ try{ //class AnnotationConfiguration:讀取關于Annotation的配置 sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory(); }catch (Throwable e) { // TODO: handle exception throw new ExceptionInInitializerError(e); } } // static method to get session public static Session getSession() throws HibernateException{ return sessionFactory.openSession(); } // close session factory public static void closeSessionFactory(){ sessionFactory.close(); } }
?
?
測試HQL查詢方式的代碼!
?
package com.bubble.test; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import com.bubble.entity.Product; import com.bubble.util.HibernateUtil; public class HqlTest { /** * @author bubble 11 / 12 / 07 * HQL具有跨數(shù)據(jù)庫的優(yōu)點。 * 適用情況:常用方法,比較傳統(tǒng),類似jdbc。 * 缺點:新的查詢語言,適用面有限,僅適用于Hibernate框架。 */ public static void main(String[] args) { // TODO Auto-generated method stub Session session=HibernateUtil.getSession();// get session //String hql="from Product as product where product.name= ? ";// hql // same to the ? method String hql="from Product as product where product.name=:name";// 命名參數(shù) Query query = session.createQuery(hql); // create query object // query.setString(0, "apple");// set the value of first ? query.setString("name","apple"); List<Product> list=query.list();// get product if product's name=apple for (Product product : list) { // print product's info System.out.println("name is:"+product.getName()+"\tQQ shenma is:"+product.getQq()); } // close session.close(); HibernateUtil.closeSessionFactory(); } }
查詢結(jié)果!
?
?
2011-12-7 1:46:54 org.hibernate.cfg.annotations.Version <clinit> 信息: Hibernate Annotations 3.3.0.GA 2011-12-7 1:46:54 org.hibernate.cfg.Environment <clinit> 信息: Hibernate 3.2.5 2011-12-7 1:46:54 org.hibernate.cfg.Environment <clinit> 信息: hibernate.properties not found 2011-12-7 1:46:54 org.hibernate.cfg.Environment buildBytecodeProvider 信息: Bytecode provider name : cglib 2011-12-7 1:46:54 org.hibernate.cfg.Environment <clinit> 信息: using JDK 1.4 java.sql.Timestamp handling 2011-12-7 1:46:54 org.hibernate.cfg.Configuration configure 信息: configuring from resource: /hibernate.cfg.xml 2011-12-7 1:46:54 org.hibernate.cfg.Configuration getConfigurationInputStream 信息: Configuration resource: /hibernate.cfg.xml 2011-12-7 1:46:54 org.hibernate.cfg.Configuration doConfigure 信息: Configured SessionFactory: null 2011-12-7 1:46:54 org.hibernate.cfg.AnnotationBinder bindClass 信息: Binding entity from annotated class: com.bubble.entity.Product 2011-12-7 1:46:54 org.hibernate.cfg.annotations.EntityBinder bindTable 信息: Bind entity com.bubble.entity.Product on table Product 2011-12-7 1:46:54 org.hibernate.validator.Version <clinit> 信息: Hibernate Validator 3.0.0.GA 2011-12-7 1:46:55 org.hibernate.connection.DriverManagerConnectionProvider configure 信息: Using Hibernate built-in connection pool (not for production use!) 2011-12-7 1:46:55 org.hibernate.connection.DriverManagerConnectionProvider configure 信息: Hibernate connection pool size: 20 2011-12-7 1:46:55 org.hibernate.connection.DriverManagerConnectionProvider configure 信息: autocommit mode: false 2011-12-7 1:46:55 org.hibernate.connection.DriverManagerConnectionProvider configure 信息: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/hiber001 2011-12-7 1:46:55 org.hibernate.connection.DriverManagerConnectionProvider configure 信息: connection properties: {user=root, password=****} 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: RDBMS: MySQL, version: 5.1.45-community-log 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.13 ( Revision: ${bzr.revision-id} ) 2011-12-7 1:46:55 org.hibernate.dialect.Dialect <init> 信息: Using dialect: org.hibernate.dialect.MySQLDialect 2011-12-7 1:46:55 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory 信息: Using default transaction strategy (direct JDBC transactions) 2011-12-7 1:46:55 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup 信息: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Automatic flush during beforeCompletion(): disabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Automatic session close at end of transaction: disabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: JDBC batch size: 15 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: JDBC batch updates for versioned data: disabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Scrollable result sets: enabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: JDBC3 getGeneratedKeys(): enabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Connection release mode: auto 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Maximum outer join fetch depth: 2 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Default batch fetch size: 1 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Generate SQL with comments: disabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Order SQL updates by primary key: disabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Order SQL inserts for batching: disabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory 信息: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory 2011-12-7 1:46:55 org.hibernate.hql.ast.ASTQueryTranslatorFactory <init> 信息: Using ASTQueryTranslatorFactory 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Query language substitutions: {} 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: JPA-QL strict compliance: disabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Second-level cache: enabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Query cache: disabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory createCacheProvider 信息: Cache provider: org.hibernate.cache.NoCacheProvider 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Optimize cache for minimal puts: disabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Structured second-level cache entries: disabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Echoing all SQL to stdout 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Statistics: disabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Deleted entity synthetic identifier rollback: disabled 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Default entity-mode: pojo 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings 信息: Named query checking : enabled 2011-12-7 1:46:55 org.hibernate.impl.SessionFactoryImpl <init> 信息: building session factory 2011-12-7 1:46:55 org.hibernate.impl.SessionFactoryObjectFactory addInstance 信息: Not binding factory to JNDI, no JNDI name configured Hibernate: select product0_.id as id0_, product0_.name as name0_, product0_.qq as qq0_ from Product product0_ where product0_.name=? name is:apple QQ shenma is:20121212 name is:apple QQ shenma is:20122222 name is:apple QQ shenma is:20122222 name is:apple QQ shenma is:201222qq 2011-12-7 1:46:55 org.hibernate.impl.SessionFactoryImpl close 信息: closing 2011-12-7 1:46:55 org.hibernate.connection.DriverManagerConnectionProvider close 信息: cleaning up connection pool: jdbc:mysql://localhost:3306/hiber001
-------------------------------------------------------------------------------------------------------------------------------
?
【2、對象化查詢Criteria方法】:
Criteria查詢代碼!
?
package com.bubble.test; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import com.bubble.entity.Product; import com.bubble.util.HibernateUtil; public class CriteriaTest { /** * @author bubble 11 / 12 / 07 * 適用情況:面向?qū)ο蟛僮鳎镄铝艘郧暗臄?shù)據(jù)庫操作方式,易讀。 * 缺點:適用面較HQL有限。 * */ public static void main(String[] args) { // TODO Auto-generated method stub Session session=HibernateUtil.getSession();// get session Criteria criteria = session.createCriteria(Product.class); criteria.add(Restrictions.eq("name", "apple"));// Restrictions:get product's name which eq apple ,like the where Restrictions in hql //eq是等于,gt是大于,lt是小于,or是或 criteria.add(Restrictions.gt("id", 3)); // when id > 3 List<Product> list=criteria.list();// get product if product's name=apple and id>3 for (Product product : list) { // print product's info System.out.println("name is:"+product.getName()+"\tQQ shenma is:"+product.getQq()); } // close session.close(); HibernateUtil.closeSessionFactory(); } }
查詢結(jié)果!
?
?
Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.qq as qq0_0_ from Product this_ where this_.name=? and this_.id>? name is:apple QQ shenma is:20122222 name is:apple QQ shenma is:20122222 name is:apple QQ shenma is:201222qq
?
?
-------------------------------------------------------------------------------------------
【3、
動態(tài)分離查詢DetachedCriteria
】
detachedcriteria查詢方式代碼!
?
package com.bubble.test; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions; import com.bubble.entity.Product; import com.bubble.util.HibernateUtil; /** * @author bubble 11 / 12 / 07 * 適用情況:面向?qū)ο蟛僮鳎蛛x業(yè)務與底層,不需要字段屬性攝入到Dao實現(xiàn)層。 * 缺點:適用面較HQL有限。 */ public class DetachedCriteriaTest { // get result from database ,return list public static List dc(DetachedCriteria dc) { Session session = HibernateUtil.getSession(); Criteria c = dc.getExecutableCriteria(session); List<Criteria> list = c.list(); session.close(); return list; } // main method public static void main(String[] args) { DetachedCriteria dc = DetachedCriteria.forClass(Product.class); int id = 1; String name = "apple"; if (id != 0) dc.add(Restrictions.gt("id", id)); if (name != null) dc.add(Restrictions.eq("name", name)); List<Product> list = dc(dc); System.out.println("離線查詢返回結(jié)果:--------------------"); for (Product product : list) { // print product's info System.out.println("name is:" + product.getName() + "\tQQ shenma is:" + product.getQq()); } } }
結(jié)果!
?
?
Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.qq as qq0_0_ from Product this_ where this_.id>? and this_.name=? 離線查詢返回結(jié)果:-------------------- name is:apple QQ shenma is:20122222 name is:apple QQ shenma is:20122222 name is:apple QQ shenma is:201222qq
?
?
----------------------------------------------------------
-------------------------------
-------------------------------
-------------------------------
【4、
例子查詢
】
例子查詢代碼!
?
package com.bubble.test; import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Example; import com.bubble.entity.Product; import com.bubble.util.HibernateUtil; /** * @author bubble 11 / 12 / 07 * 適用情況:面向?qū)ο蟛僮鳌? * 缺點:適用面較HQL有限,不推薦。 */ public class ExampleTest { public static void main(String[] args) { // TODO Auto-generated method stub Session session=HibernateUtil.getSession();// get session List<Product> products = session.createCriteria(Product.class).add(Example.create(new Product())).list(); for (Product product : products) { // print product's info System.out.println("name is:" + product.getName() + "\tQQ shenma is:" + product.getQq()); } // close session.close(); HibernateUtil.closeSessionFactory(); } }
查詢結(jié)果!
?
?
Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.qq as qq0_0_ from Product this_ where (1=1) name is:apple QQ shenma is:20121212 name is:orange QQ shenma is:20111111 name is:banana QQ shenma is:20122222 name is:apple QQ shenma is:20122222 name is:apple QQ shenma is:20122222 name is:apple QQ shenma is:201222qq
【5、
sql查詢
】
?
sql查詢代碼!
?
package com.bubble.test; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import com.bubble.entity.Product; import com.bubble.util.HibernateUtil; /** * @author bubble 11 / 12 / 07 * 適用情況:不熟悉HQL的朋友,又不打算轉(zhuǎn)數(shù)據(jù)庫平臺的朋友,萬能方法 * 缺點:破壞跨平臺,不易維護,不面向?qū)ο蟆? */ public class SqlTest { public static void main(String[] args) { // TODO Auto-generated method stub Session session=HibernateUtil.getSession();// get session Query query = session.createSQLQuery("select * from product").addEntity(Product.class);// create sql statement List<Product> list=query.list();// get all products for (Product product : list) { // print product's info System.out.println("name is:"+product.getName()+"\tid is:"+product.getId()); } // close session.close(); HibernateUtil.closeSessionFactory(); } }
結(jié)果!
?
?
Hibernate: select * from product name is:apple id is:1 name is:orange id is:2 name is:banana id is:3 name is:apple id is:4 name is:apple id is:5 name is:apple id is:6
-----------------------------------------------------------------------------------------------------------
?
【6、命名查詢】
之前是使用hibernate注解來進行映射的,現(xiàn)在注釋掉注解映射
hibernate.cfg.xml
?
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="connection.url"> jdbc:mysql://localhost:3306/hiber001 </property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="myeclipse.connection.profile">mysql5</property> <property name="show_sql">true</property> <!-- annotation part --> <!-- <mapping class="com.bubble.entity.Product" /> --> <mapping resource="com/bubble/entity/Product.hbm.xml" /> </session-factory> </hibernate-configuration>
命名查詢代碼!
?
?
package com.bubble.test; /** * @author bubble 11 / 12 / 07 * 適用情況:萬能方法,有點像ibatis輕量級框架的操作,方便維護。 * 缺點:不面向?qū)ο蟆;趆ql和sql,有一定缺陷 */ import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import com.bubble.entity.Product; import com.bubble.util.HibernateUtil; public class NamedTest { public static void main(String[] args) { // TODO Auto-generated method stub Session session=HibernateUtil.getSession();// get session Query query = session.getNamedQuery("getProductByName"); query.setString("name","apple"); List<Product> list=query.list();// get all products named apple for (Product product : list) { // print product's info System.out.println("name is:"+product.getName()+"\tid is:"+product.getId()); } // close session.close(); HibernateUtil.closeSessionFactory(); } }
查詢結(jié)果!
?
?
Hibernate: select product0_.id as id0_, product0_.name as name0_, product0_.qq as qq0_ from hiber001.product product0_ where product0_.name=? name is:apple id is:1 name is:apple id is:4 name is:apple id is:5 name is:apple id is:6
okay!that's all!
?
----------------------------------------------------------------------------------------------------------------------------------------------------
謝謝~~歡迎交流!
?
?
更多文章、技術交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
