当前位置:   article > 正文

hibernate5_org.hibernate.dialect.sqlserver2012dialect jar包

org.hibernate.dialect.sqlserver2012dialect jar包

1,下载hibernate相关jar包

更改为hibernate5.2.17

2,配置文件

 hibernate.cfg.xml文件,位置:(未配置路径)内容:

类映射文件,举例:Employee.hbm.xml,位置:内容:

Oracle方言:

  • org.hibernate.dialect.Oracle10gDialect(Dùngcho 10g&11g)

  • org.hibernate.dialect.Oracle12cDialect

SQL Server方言:

  • org.hibernate.dialect.SQLServerDialect并

  • org.hibernate.dialect.SQLServer2012Dialect

  • org.hibernate.dialect.SQLServer2008Dialect

MySQL方言

  • org.hibernate.dialect.MySQLDialect

  • org.hibernate.dialect.MySQL5Dialect

hibernate.cfg.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-configuration SYSTEM 
  3. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  4. <hibernate-configuration>
  5.    <session-factory>
  6.    <property name="hibernate.dialect">
  7.       org.hibernate.dialect.MySQLDialect
  8.    </property>
  9.    <property name="hibernate.connection.driver_class">
  10.       com.mysql.jdbc.Driver
  11.    </property>
  12.    <!-- Assume test is the database name -->
  13.    <property name="hibernate.connection.url">
  14.       jdbc:mysql://localhost:3306/test
  15.    </property>
  16.    <property name="hibernate.connection.username">
  17.       root
  18.    </property>
  19.    <property name="hibernate.connection.password">
  20.       11111
  21.    </property>
  22. <property name="show_sql">true</property>
  23.    <!-- List of XML mapping files -->
  24.    <mapping resource="Employee.hbm.xml"/>
  25.    <mapping resource="Student.hbm.xml"/>
  26. </session-factory>
  27. </hibernate-configuration>

Employee.hbm.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC 
  3.  "-//Hibernate/Hibernate Mapping DTD//EN"
  4.  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"
  5. <hibernate-mapping>
  6.    <class name="hibernate.Employee" table="EMPLOYEE">
  7.       <meta attribute="class-description">
  8.          This class contains the employee detail. 
  9.       </meta>
  10.       <id name="id" type="int" column="id">
  11.          <generator class="native"/><!-- 生成策略 -->
  12.       </id>
  13.       <property name="firstName" column="first_name" type="string"/>
  14.       <property name="lastName" column="last_name" type="string"/>
  15.       <property name="salary" column="salary" type="int"/>
  16.    </class>
  17. </hibernate-mapping>

注释形式:@Entity @Table @Id @Column

  1. @Entity
  2. @Table(name = "tb_employee")
  3. public class Employee {
  4.     @Id
  5.     private int id;
  6.     private String firstName, lastName;
  7.         @Column(name = "DEPT_ID")
  8.     public int getId() {
  9.         return id;
  10.     }
  11.     public void setId(int id) {
  12.         this.id = id;
  13.     }
  14. }

注释对应映射文件配置:

<mapping class="com.yiibai.Employee"/>

操作类:

  1.     private static SessionFactory factory;
  2. public static void main(String[] args) {
  3. Transaction tx = null;
  4. Session session = null;
  5. try {
  6. Configuration configuration=new Configuration().configure();
  7. factory=configuration.buildSessionFactory();
  8. System.out.println(factory);
  9. session=factory.openSession();
  10. tx=session.beginTransaction();
  11. //保存
  12. Employee employee=new Employee("A","B",100);
  13. session.save(employee);
  14. //查询
  15. //1
  16. /*String wherestr = " FROM EMPLOYEE ";
  17. List list = session.createQuery(wherestr).list();
  18. Iterator it=list.iterator();
  19. while(it.hasNext()) {
  20. Employee e1 = (Employee) it.next();
  21. System.out.println(e1.getId());
  22. }
  23. //2
  24. Employee e2 = (Employee)session.get(Employee.class, 1);
  25. //更新
  26. e2.setSalary(10000);
  27. session.update(e2);
  28. //删除
  29. session.delete(e2);*/
  30. tx.commit();
  31. }catch (Exception e) {
  32. // TODO: handle exception
  33. tx.rollback();
  34. }finally {
  35. session.close();
  36. }
  37. }

生成器:

  1. assigned

  2. increment

  3. sequence

  4. hilo

  5. native    默认

  6. identity

  7. seqhilo

  8. uuid

  9. guid    mysql,sqlserver

  10. select

  11. foreign

  12. sequence-identity

在表配置文件中ID的生成策略可以通过配置实现不同要求

举例:guid

  1.     <id name="id" column="id">
  2.      <generator class="guid">
  3.      </generator>
  4.   </id>

 

首先id应为字符串类型

 

二级缓存:

1,hibernate.cfg.xml文件配置

添加

  1.         <!--  -->
  2. <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>  
  3. <property name="hibernate.cache.use_second_level_cache">true</property>

2,Employee.hbm.xml文件配置

添加

  1. <cache usage="read-only" />
  2. 在class内

3,添加ehcache.xml文件

路径与hibernate.cfg.xml相同

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.     xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
  4.     monitoring="autodetect" dynamicConfig="true">
  5.     <diskStore path="java.io.tmpdir/ehcache" />
  6.     <defaultCache maxEntriesLocalHeap="10000" eternal="false"
  7.         timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
  8.         maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
  9.         memoryStoreEvictionPolicy="LRU" statistics="true">
  10.         <persistence strategy="localTempSwap" />
  11.     </defaultCache>
  12.     <cache name="org.hibernate.cache.internal.StandardQueryCache"
  13.         maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
  14.         <persistence strategy="localTempSwap" />
  15.     </cache>
  16.     <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
  17.         maxEntriesLocalHeap="5000" eternal="true">
  18.         <persistence strategy="localTempSwap" />
  19.     </cache>
  20.     <cache name="hibernate.Employee" maxElementsInMemory="100"
  21.         eternal="false" timeToIdleSeconds="5" timeToLiveSeconds="200" />
  22. </ehcache>

代码:

  1.                         String wherestr = " FROM Employee ";
  2. List list = session.createQuery(wherestr).list();
  3. Iterator it=list.iterator();
  4. while(it.hasNext()) {
  5. Employee e1 = (Employee) it.next();
  6. System.out.println(e1.getId());
  7. }
  8. session2 = factory.openSession();
  9. List list2 = session2.createQuery(wherestr).list();
  10. Iterator it2=list.iterator();
  11. while(it2.hasNext()) {
  12. Employee e1 = (Employee) it2.next();
  13. System.out.println(e1.getId());
  14. }
  15. Session session3=factory.openSession();
  16. Employee e3 = (Employee)session3.load(Employee.class, "2383a369-a398-11e8-a100-00ff7734b451");
  17. System.out.println(e3.getId());
  18. session3.close();

pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3.     <modelVersion>4.0.0</modelVersion>
  4.     <groupId>com.yiibai</groupId>
  5.     <artifactId>HibernateQuickStart</artifactId>
  6.     <version>0.0.1-SNAPSHOT</version>
  7.     <packaging>jar</packaging>
  8.     <name>HibernateQuickStart</name>
  9.     <url>http://maven.apache.org</url>
  10.     <properties>
  11.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  12.     </properties>
  13.     <dependencies>
  14.         <dependency>
  15.             <groupId>junit</groupId>
  16.             <artifactId>junit</artifactId>
  17.             <version>3.8.1</version>
  18.             <scope>test</scope>
  19.         </dependency>
  20.         <!-- Hibernate Core -->
  21.         <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
  22.         <dependency>
  23.             <groupId>org.hibernate</groupId>
  24.             <artifactId>hibernate-core</artifactId>
  25.             <version>5.2.2.Final</version>
  26.         </dependency>
  27.         <!-- MySQL JDBC driver -->
  28.         <!-- http://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  29.         <dependency>
  30.             <groupId>mysql</groupId>
  31.             <artifactId>mysql-connector-java</artifactId>
  32.             <version>5.1.34</version>
  33.         </dependency>
  34.         <!-- SQLServer JDBC driver (JTDS) -->
  35.         <!-- http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds -->
  36.         <dependency>
  37.             <groupId>net.sourceforge.jtds</groupId>
  38.             <artifactId>jtds</artifactId>
  39.             <version>1.3.1</version>
  40.         </dependency>
  41.     </dependencies></project>

 

继承映射:

  1. package com.yiibai;public class Employee {
  2.     private int id;
  3.     private String name;
  4.     public int getId() {
  5.         return id;
  6.     }
  7.     public void setId(int id) {
  8.         this.id = id;
  9.     }
  10.     public String getName() {
  11.         return name;
  12.     }
  13.     public void setName(String name) {
  14.         this.name = name;
  15.     }
  16. }
  1. package com.yiibai;public class Regular_Employee extends Employee {
  2.     private float salary;
  3.     private int bonus;
  4.     public float getSalary() {
  5.         return salary;
  6.     }
  7.     public void setSalary(float salary) {
  8.         this.salary = salary;
  9.     }
  10.     public int getBonus() {
  11.         return bonus;
  12.     }
  13.     public void setBonus(int bonus) {
  14.         this.bonus = bonus;
  15.     }}
  1. package com.yiibai;public class Contract_Employee extends Employee {
  2.     private float pay_per_hour;
  3.     private String contract_duration;
  4.     public float getPay_per_hour() {
  5.         return pay_per_hour;
  6.     }
  7.     public void setPay_per_hour(float payPerHour) {
  8.         pay_per_hour = payPerHour;
  9.     }
  10.     public String getContract_duration() {
  11.         return contract_duration;
  12.     }
  13.     public void setContract_duration(String contractDuration) {
  14.         contract_duration = contractDuration;
  15.     }}

继承类的表的区别

1,

  1. <?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-mapping PUBLIC
  2.           "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  3.           "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>
  4.     <class name="com.yiibai.Employee" table="emp121"
  5.         discriminator-value="emp">
  6.         <id name="id">
  7.             <generator class="increment"></generator>
  8.         </id>
  9.         <discriminator column="type" type="string"></discriminator>
  10.         <property name="name"></property>
  11.         <subclass name="com.yiibai.Regular_Employee"
  12.             discriminator-value="reg_emp">
  13.             <property name="salary"></property>
  14.             <property name="bonus"></property>
  15.         </subclass>
  16.         <subclass name="com.yiibai.Contract_Employee"
  17.             discriminator-value="con_emp">
  18.             <property name="pay_per_hour"></property>
  19.             <property name="contract_duration"></property>
  20.         </subclass>
  21.     </class></hibernate-mapping>
  1. public class StoreData {
  2.     public static void main(String[] args) {
  3.         // Session session = new
  4.         // AnnotationConfiguration().configure().buildSessionFactory().openSession();
  5.         final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
  6.                 .configure("hibernate.cfg.xml").build();
  7.         // 2. 根据服务注册类创建一个元数据资源集,同时构建元数据并生成应用一般唯一的的session工厂
  8.         SessionFactory sessionFactory = new MetadataSources(registry)
  9.                 .buildMetadata().buildSessionFactory();
  10.         /**** 上面是配置准备,下面开始我们的数据库操作 ******/
  11.         Session session = sessionFactory.openSession();// 从会话工厂获取一个session
  12.         Transaction t = session.beginTransaction();
  13.         Employee e1 = new Employee();
  14.         e1.setName("Yiibai");
  15.         Regular_Employee e2 = new Regular_Employee();
  16.         e2.setName("Max su");
  17.         e2.setSalary(50000);
  18.         e2.setBonus(5);
  19.         Contract_Employee e3 = new Contract_Employee();
  20.         e3.setName("Hippo su");
  21.         e3.setPay_per_hour(1000);
  22.         e3.setContract_duration("15 hours");
  23.         session.persist(e1);
  24.         session.persist(e2);
  25.         session.persist(e3);
  26.         t.commit();
  27.         session.close();
  28.         System.out.println("success");
  29.     }}

2,分表

  1. Employee类的表结构 -
  2. CREATE TABLE `emp122` (
  3.   `id` int(11) NOT NULL,
  4.   `name` varchar(255) DEFAULT NULL,
  5.   PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;SQL
  6. Regular_Employee类的表结构 -
  7. CREATE TABLE `regemp122` (
  8.   `id` int(11) NOT NULL,
  9.   `name` varchar(255) DEFAULT NULL,
  10.   `salary` float DEFAULT NULL,
  11.   `bonus` int(11) DEFAULT NULL,
  12.   PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;SQL
  13. Contract_Employee类的表结构 -
  14. CREATE TABLE `contemp122` (
  15.   `id` int(11) NOT NULL,
  16.   `name` varchar(255) DEFAULT NULL,
  17.   `pay_per_hour` float DEFAULT NULL,
  18.   `contract_duration` varchar(255) DEFAULT NULL,
  19.   PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  1. <?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-mapping PUBLIC
  2.           "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  3.           "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>
  4.     <class name="com.yiibai.Employee" table="emp122">
  5.         <id name="id">
  6.             <generator class="increment"></generator>
  7.         </id>
  8.         <property name="name"></property>
  9.         <union-subclass name="com.yiibai.Regular_Employee"
  10.             table="regemp122">
  11.             <property name="salary"></property>
  12.             <property name="bonus"></property>
  13.         </union-subclass>
  14.         <union-subclass name="com.yiibai.Contract_Employee"
  15.             table="contemp122">
  16.             <property name="pay_per_hour"></property>
  17.             <property name="contract_duration"></property>
  18.         </union-subclass>
  19.     </class></hibernate-mapping>

 

  1.         Employee e1 = new Employee();
  2.         e1.setName("Yiibai");
  3.         Regular_Employee e2 = new Regular_Employee();
  4.         e2.setName("Max su");
  5.         e2.setSalary(50000);
  6.         e2.setBonus(5);
  7.         Contract_Employee e3 = new Contract_Employee();
  8.         e3.setName("Hippo su");
  9.         e3.setPay_per_hour(1000);
  10.         e3.setContract_duration("15 hours");
  11.         session.persist(e1);
  12.         session.persist(e2);
  13.         session.persist(e3);

3,注释......

集合映射:

一对多,多对多

例如:list

  1. package com.yiibai;  
  2. import java.util.List;  
  3. public class Question {  
  4.     private int id;  
  5.     private String qname;  
  6.     private List<Answer> answers;  
  7.     //getters and setters  
  8. }
  1. package com.yiibai;  public class Answer {  
  2.     private int id;  
  3.     private String answername;  
  4.     private String postedBy;  
  5.     //getters and setters  
  6.     }  
  7. }
  1.     <class name="com.yiibai.Question" table="q501">
  2.         <id name="id">
  3.             <generator class="increment"></generator>
  4.         </id>
  5.         <property name="qname"></property>
  6.         <list name="answers" cascade="all">
  7.             <key column="qid"></key>
  8.             <index column="type"></index>
  9.             <one-to-many class="com.yiibai.Answer" />
  10.         </list>
  11.     </class>
  12.     <class name="com.yiibai.Answer" table="ans501">
  13.         <id name="id">
  14.             <generator class="increment"></generator>
  15.         </id>
  16.         <property name="answername"></property>
  17.         <property name="postedBy"></property>
  18.     </class>

String

  1. <class name="com.yiibai.Question" table="q100">  
  2.        ...        
  3.           <list name="answers" table="ans100">  
  4.           <key column="qid"></key>  
  5.           <index column="type"></index>  
  6.           <element column="answer" type="string"></element>  
  7.           </list>  
  8.        ...  
  9. </class>

插入

  1.         Answer ans1 = new Answer();
  2.         ans1.setAnswername("java is a programming language");
  3.         ans1.setPostedBy("Ravi Su");
  4.         Answer ans2 = new Answer();
  5.         ans2.setAnswername("java is a platform");
  6.         ans2.setPostedBy("Sudhir Wong");
  7.         Answer ans3 = new Answer();
  8.         ans3.setAnswername("Servlet is an Interface");
  9.         ans3.setPostedBy("Jai Li");
  10.         Answer ans4 = new Answer();
  11.         ans4.setAnswername("Servlet is an API");
  12.         ans4.setPostedBy("Arun");
  13.         ArrayList<Answer> list1 = new ArrayList<Answer>();
  14.         list1.add(ans1);
  15.         list1.add(ans2);
  16.         ArrayList<Answer> list2 = new ArrayList<Answer>();
  17.         list2.add(ans3);
  18.         list2.add(ans4);
  19.         Question question1 = new Question();
  20.         question1.setQname("What is Java?");
  21.         question1.setAnswers(list1);
  22.         Question question2 = new Question();
  23.         question2.setQname("What is Servlet?");
  24.         question2.setAnswers(list2);
  25.         session.persist(question1);
  26.         session.persist(question2);

查询

  1.     Query query=session.createQuery("from Question");  
  2.     List<Question> list=query.list();  
  3.     Iterator<Question> itr=list.iterator();  
  4.     while(itr.hasNext()){  
  5.         Question q=itr.next();  
  6.         System.out.println("Question Name: "+q.getQname());  
  7.         //printing answers  
  8.         List<Answer> list2=q.getAnswers();  
  9.         Iterator<Answer> itr2=list2.iterator();  
  10.         while(itr2.hasNext()){  
  11.             System.out.println(itr2.next());  
  12.         }  
  13.     }

例如:bag包内

  1.         <bag name="answers" cascade="all">
  2.             <key column="type"></key>
  3.             <one-to-many class="com.yiibai.Answer" />
  4.         </bag>

例如:set

  1.         <set name="answers" table="ans102">
  2.             <key column="qid"></key>
  3.             <element column="answer" type="string"></element>
  4.         </set>
  5.         <set name="answers" table="a1002"
  6.             inverse="true" lazy="true" fetch="select">
  7.         <key>
  8.             <column name="qid" not-null="true" />
  9.         </key>
  10.             <one-to-many class="com.yiibai.Answer" />
  11.         </set>

反其道而行

  1. <?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-mapping PUBLIC
  2.           "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  3.           "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>
  4.     <class name="com.yiibai.Answer" table="a1002">
  5.         <id name="id">
  6.             <generator class="increment"></generator>
  7.         </id>
  8.         <property name="answername"></property>
  9.         <property name="postedBy"></property>
  10.         <many-to-one name="question" class="com.yiibai.Question" fetch="select">
  11.             <column name="qid" not-null="true" />
  12.         </many-to-one>
  13.     </class></hibernate-mapping>

例如:map

  1. <?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-mapping PUBLIC
  2.           "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  3.           "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>
  4.     <class name="com.yiibai.Question" table="question_736">
  5.         <id name="id">
  6.             <generator class="native"></generator>
  7.         </id>
  8.         <property name="name"></property>
  9.         <property name="username"></property>
  10.         <map name="answers" table="answer736" cascade="all">
  11.             <key column="questionid"></key>
  12.             <index column="answer" type="string"></index>
  13.             <element column="username" type="string"></element>
  14.         </map>
  15.     </class></hibernate-mapping>

多对多  

  1. <hibernate-mapping>
  2.     <class name="com.yiibai.Question" table="question_m2m">
  3.         <id name="id">
  4.             <generator class="native"></generator>
  5.         </id>
  6.         <property name="name"></property>
  7.         <map name="answers" table="answer_m2m" cascade="all">
  8.             <key column="questionid"></key>
  9.             <index column="answer" type="string"></index>
  10.             <many-to-many class="com.yiibai.User" column="userid"></many-to-many>
  11.         </map>
  12.     </class></hibernate-mapping>

例如:表结构

高级部分:

组件映射:

例如:

  1. public class Employee {
  2.     private int id;
  3.     private String name;
  4.     private Address address;
  1. <hibernate-mapping>
  2.     <class name="com.yiibai.Employee" table="emp_cpmap">
  3.         <id name="id">
  4.             <generator class="increment"></generator>
  5.         </id>
  6.         <property name="name"></property>
  7.         <component name="address" class="com.yiibai.Address">
  8.             <property name="city"></property>
  9.             <property name="country"></property>
  10.             <property name="pincode"></property>
  11.         </component>
  12.     </class></hibernate-mapping>

多对一

例如:

  1. public class Employee {
  2.     private int employeeId;
  3.     private String name, email;
  4.     private Address address;
  1. public class Address {
  2.     private int addressId;
  3.     private String addressLine1, city, state, country;
  4.     private int pincode;
  5.     private Employee employee;
  1. <hibernate-mapping>
  2.     <class name="com.yiibai.Employee" table="emp_2110">
  3.         <id name="employeeId">
  4.             <generator class="increment"></generator>
  5.         </id>
  6.         <property name="name"></property>
  7.         <property name="email"></property>
  8.         <many-to-one name="address" unique="true" cascade="all"></many-to-one>
  9.     </class>
  10. </hibernate-mapping>

一对一

例如:

  1. public class Employee {
  2.     private int employeeId;
  3.     private String name, email;
  4.     private Address address;
  1. public class Address {
  2.     private int addressId;
  3.     private String addressLine1, city, state, country;
  4.     private int pincode;
  5.     private Employee employee;

 

  1. <hibernate-mapping>
  2.     <class name="com.yiibai.Employee" table="emp_2120">
  3.         <id name="employeeId">
  4.             <generator class="increment"></generator>
  5.         </id>
  6.         <property name="name"></property>
  7.         <property name="email"></property>
  8.         <one-to-one name="address" cascade="all"></one-to-one>
  9.     </class></hibernate-mapping>

事务管理

例如:

Transaction接口的方法如下:

  1. void begin() 开始一个新的事务。

  2. void commit() 结束工作单位,在FlushMode.NEVER中除外。

  3. void rollback() 强制此事务回滚。

  4. void setTimeout(int seconds) 它为由此实例开始的后续调用启动的任何事务设置事务超时。

  5. boolean isAlive() 检查交易是否仍然存在。

  6. void registerSynchronization(Synchronization s) 为此事务注册用户同步回调。

  7. boolean wasCommited() 检查事务是否成功提交。

  8. boolean wasRolledBack() 检查事务是否成功回滚。

查询

例如:

HQL获取所有记录的示例

  1. Query query=session.createQuery("from Emp");
  2. //here persistent class name is Emp  
  3. List list=query.list();Java

HQL获取分页记录的示例

  1. Query query=session.createQuery("from Emp");  
  2. query.setFirstResult(5);  
  3. query.setMaxResult(10);  
  4. List list=query.list();
  5. //will return the records from 5 to 10th numberJava

HQL更新查询示例

  1. Transaction tx=session.beginTransaction();  
  2. Query q=session.createQuery("update User set name=:n where id=:i");  
  3. q.setParameter("n","Udit Kumar");  
  4. q.setParameter("i",111);  
  5. int status=q.executeUpdate();  
  6. System.out.println(status);  
  7. tx.commit();

HQL删除查询示例

  1. Query query=session.createQuery("delete from Emp where id=100");  
  2. //specifying class name (Emp) not tablename  
  3. query.executeUpdate();

HQL与聚合函数

可以通过HQL调用avg()min()max()等聚合函数。 我们来看一些常见的例子:

获得所有员工总薪酬的例子

  1. Query q=session.createQuery("select sum(salary) from Emp");  
  2. List<Integer> list=q.list();  
  3. System.out.println(list.get(0));Java

获得员工最高工资的例子

Query q=session.createQuery("select max(salary) from Emp");

获得员工最低工资的例子

Query q=session.createQuery("select min(salary) from Emp");

计算雇员ID总数的示例

Query q=session.createQuery("select count(id) from Emp");

获得员工的平均工资的例子

Query q=session.createQuery("select avg(salary) from Emp");

 


 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/369901
推荐阅读
相关标签
  

闽ICP备14008679号