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
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/test
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
11111
</property>
<property name="show_sql">true</property>
<!-- List of XML mapping files -->
<mapping resource="Employee.hbm.xml"/>
<mapping resource="Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Employee.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernate.Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/><!-- 生成策略 -->
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
注释形式:@Entity @Table @Id @Column
@Entity
@Table(name = "tb_employee")
public class Employee {
@Id
private int id;
private String firstName, lastName;
@Column(name = "DEPT_ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
注释对应映射文件配置:
<mapping class="com.yiibai.Employee"/>
操作类:
private static SessionFactory factory;
public static void main(String[] args) {
Transaction tx = null;
Session session = null;
try {
Configuration configuration=new Configuration().configure();
factory=configuration.buildSessionFactory();
System.out.println(factory);
session=factory.openSession();
tx=session.beginTransaction();
//保存
Employee employee=new Employee("A","B",100);
session.save(employee);
//查询
//1
/*String wherestr = " FROM EMPLOYEE ";
List list = session.createQuery(wherestr).list();
Iterator it=list.iterator();
while(it.hasNext()) {
Employee e1 = (Employee) it.next();
System.out.println(e1.getId());
}
//2
Employee e2 = (Employee)session.get(Employee.class, 1);
//更新
e2.setSalary(10000);
session.update(e2);
//删除
session.delete(e2);*/
tx.commit();
}catch (Exception e) {
// TODO: handle exception
tx.rollback();
}finally {
session.close();
}
}
生成器:
-
assigned
-
increment
-
sequence
-
hilo
-
native 默认
-
identity
-
seqhilo
-
uuid
-
guid mysql,sqlserver
-
select
-
foreign
-
sequence-identity
在表配置文件中ID的生成策略可以通过配置实现不同要求
举例:guid
<id name="id" column="id">
<generator class="guid">
</generator>
</id>
首先id应为字符串类型
二级缓存:
1,hibernate.cfg.xml文件配置
添加
<!-- -->
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
2,Employee.hbm.xml文件配置
添加
<cache usage="read-only" />
在class内
3,添加ehcache.xml文件
路径与hibernate.cfg.xml相同
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect" dynamicConfig="true">
<diskStore path="java.io.tmpdir/ehcache" />
<defaultCache maxEntriesLocalHeap="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" statistics="true">
<persistence strategy="localTempSwap" />
</defaultCache>
<cache name="org.hibernate.cache.internal.StandardQueryCache"
maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
<persistence strategy="localTempSwap" />
</cache>
<cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
maxEntriesLocalHeap="5000" eternal="true">
<persistence strategy="localTempSwap" />
</cache>
<cache name="hibernate.Employee" maxElementsInMemory="100"
eternal="false" timeToIdleSeconds="5" timeToLiveSeconds="200" />
</ehcache>
代码:
String wherestr = " FROM Employee ";
List list = session.createQuery(wherestr).list();
Iterator it=list.iterator();
while(it.hasNext()) {
Employee e1 = (Employee) it.next();
System.out.println(e1.getId());
}
session2 = factory.openSession();
List list2 = session2.createQuery(wherestr).list();
Iterator it2=list.iterator();
while(it2.hasNext()) {
Employee e1 = (Employee) it2.next();
System.out.println(e1.getId());
}
Session session3=factory.openSession();
Employee e3 = (Employee)session3.load(Employee.class, "2383a369-a398-11e8-a100-00ff7734b451");
System.out.println(e3.getId());
session3.close();
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yiibai</groupId>
<artifactId>HibernateQuickStart</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>HibernateQuickStart</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Hibernate Core -->
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.2.Final</version>
</dependency>
<!-- MySQL JDBC driver -->
<!-- http://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- SQLServer JDBC driver (JTDS) -->
<!-- http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds -->
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies></project>
继承映射:
package com.yiibai;public class Employee {
private int id;
private String name;
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;
}
}
package com.yiibai;public class Regular_Employee extends Employee {
private float salary;
private int bonus;
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public int getBonus() {
return bonus;
}
public void setBonus(int bonus) {
this.bonus = bonus;
}}
package com.yiibai;public class Contract_Employee extends Employee {
private float pay_per_hour;
private String contract_duration;
public float getPay_per_hour() {
return pay_per_hour;
}
public void setPay_per_hour(float payPerHour) {
pay_per_hour = payPerHour;
}
public String getContract_duration() {
return contract_duration;
}
public void setContract_duration(String contractDuration) {
contract_duration = contractDuration;
}}
继承类的表的区别
1,
<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>
<class name="com.yiibai.Employee" table="emp121"
discriminator-value="emp">
<id name="id">
<generator class="increment"></generator>
</id>
<discriminator column="type" type="string"></discriminator>
<property name="name"></property>
<subclass name="com.yiibai.Regular_Employee"
discriminator-value="reg_emp">
<property name="salary"></property>
<property name="bonus"></property>
</subclass>
<subclass name="com.yiibai.Contract_Employee"
discriminator-value="con_emp">
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</subclass>
</class></hibernate-mapping>
public class StoreData {
public static void main(String[] args) {
// Session session = new
// AnnotationConfiguration().configure().buildSessionFactory().openSession();
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml").build();
// 2. 根据服务注册类创建一个元数据资源集,同时构建元数据并生成应用一般唯一的的session工厂
SessionFactory sessionFactory = new MetadataSources(registry)
.buildMetadata().buildSessionFactory();
/**** 上面是配置准备,下面开始我们的数据库操作 ******/
Session session = sessionFactory.openSession();// 从会话工厂获取一个session
Transaction t = session.beginTransaction();
Employee e1 = new Employee();
e1.setName("Yiibai");
Regular_Employee e2 = new Regular_Employee();
e2.setName("Max su");
e2.setSalary(50000);
e2.setBonus(5);
Contract_Employee e3 = new Contract_Employee();
e3.setName("Hippo su");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}}
2,分表
Employee类的表结构 -
CREATE TABLE `emp122` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;SQL
Regular_Employee类的表结构 -
CREATE TABLE `regemp122` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`salary` float DEFAULT NULL,
`bonus` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;SQL
Contract_Employee类的表结构 -
CREATE TABLE `contemp122` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`pay_per_hour` float DEFAULT NULL,
`contract_duration` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>
<class name="com.yiibai.Employee" table="emp122">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<union-subclass name="com.yiibai.Regular_Employee"
table="regemp122">
<property name="salary"></property>
<property name="bonus"></property>
</union-subclass>
<union-subclass name="com.yiibai.Contract_Employee"
table="contemp122">
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</union-subclass>
</class></hibernate-mapping>
Employee e1 = new Employee();
e1.setName("Yiibai");
Regular_Employee e2 = new Regular_Employee();
e2.setName("Max su");
e2.setSalary(50000);
e2.setBonus(5);
Contract_Employee e3 = new Contract_Employee();
e3.setName("Hippo su");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");
session.persist(e1);
session.persist(e2);
session.persist(e3);
3,注释......
集合映射:
一对多,多对多
例如:list
package com.yiibai;
import java.util.List;
public class Question {
private int id;
private String qname;
private List<Answer> answers;
//getters and setters
}
package com.yiibai; public class Answer {
private int id;
private String answername;
private String postedBy;
//getters and setters
}
}
<class name="com.yiibai.Question" table="q501">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="qname"></property>
<list name="answers" cascade="all">
<key column="qid"></key>
<index column="type"></index>
<one-to-many class="com.yiibai.Answer" />
</list>
</class>
<class name="com.yiibai.Answer" table="ans501">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="answername"></property>
<property name="postedBy"></property>
</class>
String
<class name="com.yiibai.Question" table="q100">
...
<list name="answers" table="ans100">
<key column="qid"></key>
<index column="type"></index>
<element column="answer" type="string"></element>
</list>
...
</class>
插入
Answer ans1 = new Answer();
ans1.setAnswername("java is a programming language");
ans1.setPostedBy("Ravi Su");
Answer ans2 = new Answer();
ans2.setAnswername("java is a platform");
ans2.setPostedBy("Sudhir Wong");
Answer ans3 = new Answer();
ans3.setAnswername("Servlet is an Interface");
ans3.setPostedBy("Jai Li");
Answer ans4 = new Answer();
ans4.setAnswername("Servlet is an API");
ans4.setPostedBy("Arun");
ArrayList<Answer> list1 = new ArrayList<Answer>();
list1.add(ans1);
list1.add(ans2);
ArrayList<Answer> list2 = new ArrayList<Answer>();
list2.add(ans3);
list2.add(ans4);
Question question1 = new Question();
question1.setQname("What is Java?");
question1.setAnswers(list1);
Question question2 = new Question();
question2.setQname("What is Servlet?");
question2.setAnswers(list2);
session.persist(question1);
session.persist(question2);
查询
Query query=session.createQuery("from Question");
List<Question> list=query.list();
Iterator<Question> itr=list.iterator();
while(itr.hasNext()){
Question q=itr.next();
System.out.println("Question Name: "+q.getQname());
//printing answers
List<Answer> list2=q.getAnswers();
Iterator<Answer> itr2=list2.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
例如:bag包内
<bag name="answers" cascade="all">
<key column="type"></key>
<one-to-many class="com.yiibai.Answer" />
</bag>
例如:set
<set name="answers" table="ans102">
<key column="qid"></key>
<element column="answer" type="string"></element>
</set>
<set name="answers" table="a1002"
inverse="true" lazy="true" fetch="select">
<key>
<column name="qid" not-null="true" />
</key>
<one-to-many class="com.yiibai.Answer" />
</set>
反其道而行
<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>
<class name="com.yiibai.Answer" table="a1002">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="answername"></property>
<property name="postedBy"></property>
<many-to-one name="question" class="com.yiibai.Question" fetch="select">
<column name="qid" not-null="true" />
</many-to-one>
</class></hibernate-mapping>
例如:map
<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>
<class name="com.yiibai.Question" table="question_736">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<property name="username"></property>
<map name="answers" table="answer736" cascade="all">
<key column="questionid"></key>
<index column="answer" type="string"></index>
<element column="username" type="string"></element>
</map>
</class></hibernate-mapping>
多对多
<hibernate-mapping>
<class name="com.yiibai.Question" table="question_m2m">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<map name="answers" table="answer_m2m" cascade="all">
<key column="questionid"></key>
<index column="answer" type="string"></index>
<many-to-many class="com.yiibai.User" column="userid"></many-to-many>
</map>
</class></hibernate-mapping>
例如:表结构
高级部分:
组件映射:
例如:
public class Employee {
private int id;
private String name;
private Address address;
<hibernate-mapping>
<class name="com.yiibai.Employee" table="emp_cpmap">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<component name="address" class="com.yiibai.Address">
<property name="city"></property>
<property name="country"></property>
<property name="pincode"></property>
</component>
</class></hibernate-mapping>
多对一
例如:
public class Employee {
private int employeeId;
private String name, email;
private Address address;
public class Address {
private int addressId;
private String addressLine1, city, state, country;
private int pincode;
private Employee employee;
<hibernate-mapping>
<class name="com.yiibai.Employee" table="emp_2110">
<id name="employeeId">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<property name="email"></property>
<many-to-one name="address" unique="true" cascade="all"></many-to-one>
</class>
</hibernate-mapping>
一对一
例如:
public class Employee {
private int employeeId;
private String name, email;
private Address address;
public class Address {
private int addressId;
private String addressLine1, city, state, country;
private int pincode;
private Employee employee;
<hibernate-mapping>
<class name="com.yiibai.Employee" table="emp_2120">
<id name="employeeId">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<property name="email"></property>
<one-to-one name="address" cascade="all"></one-to-one>
</class></hibernate-mapping>
事务管理
例如:
Transaction接口的方法如下:
-
void begin() 开始一个新的事务。
-
void commit() 结束工作单位,在FlushMode.NEVER中除外。
-
void rollback() 强制此事务回滚。
-
void setTimeout(int seconds) 它为由此实例开始的后续调用启动的任何事务设置事务超时。
-
boolean isAlive() 检查交易是否仍然存在。
-
void registerSynchronization(Synchronization s) 为此事务注册用户同步回调。
-
boolean wasCommited() 检查事务是否成功提交。
-
boolean wasRolledBack() 检查事务是否成功回滚。
查询
例如:
HQL获取所有记录的示例
Query query=session.createQuery("from Emp");
//here persistent class name is Emp
List list=query.list();Java
HQL获取分页记录的示例
Query query=session.createQuery("from Emp");
query.setFirstResult(5);
query.setMaxResult(10);
List list=query.list();
//will return the records from 5 to 10th numberJava
HQL更新查询示例
Transaction tx=session.beginTransaction();
Query q=session.createQuery("update User set name=:n where id=:i");
q.setParameter("n","Udit Kumar");
q.setParameter("i",111);
int status=q.executeUpdate();
System.out.println(status);
tx.commit();
HQL删除查询示例
Query query=session.createQuery("delete from Emp where id=100");
//specifying class name (Emp) not tablename
query.executeUpdate();
HQL与聚合函数
可以通过HQL调用avg()
,min()
,max()
等聚合函数。 我们来看一些常见的例子:
获得所有员工总薪酬的例子
Query q=session.createQuery("select sum(salary) from Emp");
List<Integer> list=q.list();
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");