1.搭建环境
1.1导入jar包(数据库为sqlserver)
1.2配置文件:名称统一为hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- 配置session工厂 -->
<session-factory>
<!-- 用户名和密码 -->
<property name="hibernate.connection.password">****</property>
<property name="hibernate.connection.username">sa</property>
<!-- 配置数据库驱动 -->
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<!-- 数据库的连接 -->
<property name="connection.url">jdbc:sqlserver://localhost:1433;databaseName=heimashop</property>
<!-- 方言 (连接的是哪一个数据库产品-->
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<!-- 后 台输出sql语句-->
<property name="hibernate.show_sql">true</property>
<!-- 格式化sql -->
<property name="hibernate.format_sql">true</property>
<!-- hibernate 隔离级别 -->
<property name="hibernate.connection.isolation">4</property>
指定session与当前线程绑定
<property name="hibernate.current_session_context_class">thread</property>
<!-- 生成数据表的方式-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 添加orm文件:映射类对象 -->
<mapping resource="cn/itheima/domain/Customer.hbm.xml"/>
</session-factory>
1.3创建实体类
public class Customer {
private Long cust_id;
private String cust_name;
private String cust_source;
public Long getCust_id() {
return cust_id;
}
public void setCust_id(Long cust_id) {
this.cust_id = cust_id;
}
public String getCust_name() {
return cust_name;
}
public void setCust_name(String cust_name) {
this.cust_name = cust_name;
}
public String getCust_source() {
return cust_source;
}
public void setCust_source(String cust_source) {
this.cust_source = cust_source;
}
public String getCust_industry() {
return cust_industry;
}
public void setCust_industry(String cust_industry) {
this.cust_industry = cust_industry;
}
public String getCust_level() {
return cust_level;
}
public void setCust_level(String cust_level) {
this.cust_level = cust_level;
}
public String getCust_phone() {
return cust_phone;
}
public void setCust_phone(String cust_phone) {
this.cust_phone = cust_phone;
}
public String getCust_mobile() {
return cust_mobile;
}
public void setCust_mobile(String cust_mobile) {
this.cust_mobile = cust_mobile;
}
private String cust_industry;
private String cust_level;
private String cust_phone;
private String cust_mobile;
1.4创建orm映射文件<文件名称与Customer类对应:Customer.hbm.xml>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 配置表与实体对象的关系 -->
<!-- package属性:填写一个包名.在元素内部凡是需要书写完整类名的属性,可以直接写简答类名了. -->
<hibernate-mapping package="cn.itheima.domain">
<!--
class元素: 配置实体与表的对应关系的
name: 完整类名
table:数据库表名
-->
<class name="Customer" table="cus_customer">
<!-- id元素:配置主键映射的属性
name: 填写主键对应属性名
column(可选): 填写表中的主键列名.默认值:列名会默认使用属性名
type(可选):填写列(属性)的类型.hibernate会自动检测实体的属性类型.
每个类型有三种填法: java类型|hibernate类型|数据库类型
not-null(可选):配置该属性(列)是否不能为空. 默认值:false
length(可选):配置数据库中列的长度. 默认值:使用数据库类型的最大长度
-->
<id name="cust_id">
<!-- generator:主键生成策略 -->
<generator class="native"></generator>
</id>
<!-- property元素:除id之外的普通属性映射
name: 填写属性名
column(可选): 填写列名
type(可选):填写列(属性)的类型.hibernate会自动检测实体的属性类型.
每个类型有三种填法: java类型|hibernate类型|数据库类型
not-null(可选):配置该属性(列)是否不能为空. 默认值:false
length(可选):配置数据库中列的长度. 默认值:使用数据库类型的最大长度
-->
<property name="cust_name" column="cust_name"></property>
<property name="cust_source" column="cust_source"></property>
<property name="cust_industry" column="cust_industry"></property>
<property name="cust_level" column="cust_level"></property>
<property name="cust_phone" column="cust_phone"></property>
<property name="cust_mobile" column="cust_mobile"></property>
</class>
</hibernate-mapping>
1.5创建工具类
public class HibernateUtils {
//创建配置对象,用于读取hibernate配置文件
private static SessionFactory sf=null;
//1.使用Configuration读取配置文件,默认读取的是src下一个叫做hibernate.cfg.xml的文件
static{
Configuration conf=new Configuration().configure();
//2.创建SessionFactory
sf = conf.buildSessionFactory();
}
/**
* 提供获取session方法,重新生成一个session
*/
public static Session openSession(){
Session session = sf.openSession();
return session;
};
/**
* 获取当前线程的session,
*/
public static Session getCurrentSession(){
Session session = sf.getCurrentSession();
return session;
};
2.基本操作
1.save
public static void main(String[] args) {
//获得session,,打开一个新的session对象
//session用于hibernate操作数据库核心对象
Session session = HibernateUtils.openSession();
//.session获得操作事务的Transaction对象,此为获得一个事务对象并开启事务
Transaction ts=session.beginTransaction();
Customer cus=new Customer();//没有id,没有与session有关联=》瞬时状态
cus.setCust_name("旺达");瞬时状态
session.save(cus);//保存
ts.commit();//提交事务
//ts.rollback();//回滚事务
session.close();//释放资源--游离状态
}
2.get方法和load方法
/**
* 查询 -- 根据主键查询 get load
* 1.get方法
* 作用:
* 根据主键查询数据
* 用法:
* 两个参数
* 第一个参数是class类型,要查询哪一个表,就写哪一个表对应的实体类的class类型
* 第二个参数是一个实现了序列化接口的对象,可以传递一数字
* 2.load方法
* 作用:
* 根据主键查询数据
* 用法:与get一模一样
* get是即时加载
* load是延迟加载 -- 动态代理,生成了实体类的代理对象(javassist-3.20.0-GA.jar)
*/
@Test
public void test(){
Session session = HibernateUtils.openSession();
Transaction ts=session.beginTransaction();
//Customer customer = session.get(Customer.class, 1l);
//System.out.println(customer);
Customer customer=session.load(Customer.class, 1l);
System.out.println(customer);
ts.commit();//提交事务
//ts.rollback();//回滚事务
session.close();//释放资源--游离状态
}
3.delete
public void test(){
Session session = HibernateUtils.openSession();
Transaction ts=session.beginTransaction();
//Customer customer = session.get(Customer.class, 1l);
//System.out.println(customer);
Customer customer=session.get(Customer.class, 1l);
session.delete(customer);
//System.out.println(customer);
ts.commit();//提交事务
//ts.rollback();//回滚事务
session.close();//释放资源--游离状态
}
3.Hql基本语法
3.1查询所有
/**
*HQL Hibernate Query 语言
* 1.HQL操作的都是java类,而不是表
*2.在HQL中查询所有,直接写 from 实体类的名,不写select *
*
*/
@Test
public void test(){
Session session = HibernateUtils.openSession();
Transaction ts=session.beginTransaction();
String sql="from Customer";
Query c = session.createQuery(sql);
List<Customer> list = c.list();
System.out.println(list);
ts.commit();//提交事务
//ts.rollback();//回滚事务
session.close();//释放资源--游离状态
}
3.2带条件查询
/**
*HQL Hibernate Query 语言
* c.setParameter()第一个问号是从0开始算起
*
*/
@Test
public void test(){
Session session = HibernateUtils.openSession();
Transaction ts=session.beginTransaction();
String sql="from Customer where cust_name=?";
Query c = session.createQuery(sql);
c.setParameter(0, "百度");
List<Customer> list=c.list();
System.out.println(list);
ts.commit();//提交事务
//ts.rollback();//回滚事务
session.close();//释放资源--游离状态
}
3.3分页查询
@Test
public void test(){
Session session = HibernateUtils.openSession();
Transaction ts=session.beginTransaction();
String sql="from Customer ";
Query c = session.createQuery(sql);
c.setFirstResult(1);//设置开始查询位置
c.setMaxResults(2);//一次查询多少条数据
List<Customer> list=c.list();
System.out.println(list);
ts.commit();//提交事务
//ts.rollback();//回滚事务
session.close();//释放资源--游离状态
}
3.4聚合函数
/**
* 聚合函数
* 统计年龄大于18岁的有多少人
* 如果能够保证查询结果只有一条数据的话,那么可以使用uniqueResult方法,查询结果如果多于1条记录,那么就会报错
* 可以使用uniqueResult根据主键进行查询
* 如果查询某几个列,那么返回的是一个Object数组,数组中保存的是每个列的值
*/
@Test
public void test(){
Session session = HibernateUtils.openSession();
Transaction ts=session.beginTransaction();
String sql="select count(cust_id) from Customer ";
Query c = session.createQuery(sql);
Object[] result =(Object[]) c.uniqueResult();
//List<Object[]> list=c.list();
System.out.println(result[0]);
ts.commit();//提交事务
//ts.rollback();//回滚事务
session.close();//释放资源--游离状态
}
4.Critetia查询
/**
* Criteria -- 只能用于查询
* 添加查询条件
* 使用criteria.add
* 括号中Restrictions.方法来进行条件查询条件
* 如:Restrictions.eq(propertyName, value)
* 第一个参数:根据哪个字段进行查询(实体类中的属性名)
* 第二个参数:查询时的参数值
* select * from employee where emp_name = '张三'
* 常用:
* eq 代表相等 =
* lt 代表小于 <
* le 代表小于等于 <=
* gt 代表大于 >
* ge 代表大于等于 >=
* ne 代表了不等于 != , <>
* between 代表了区间
* like 代表模糊查询
*
*/
@Test
public void test(){
Session session = HibernateUtils.openSession();
Transaction ts=session.beginTransaction();
Criteria c = session.createCriteria(Customer.class);
c.add(Restrictions.eq("cust_id",1l));
c.add(Restrictions.lt("cust_age", 15));
List<Customer> list=c.list();
System.out.println(list);
ts.commit();//提交事务
//ts.rollback();//回滚事务
session.close();//释放资源--游离状态
}
5.原生sql查询,(复杂多表查询推荐使用)
@Test
public void test(){
Session session = HibernateUtils.openSession();
Transaction ts=session.beginTransaction();
String sql="select * from cus_customer";
SQLQuery c = session.createSQLQuery(sql);
//如果需要将查询结果进行映射
c.addEntity(Customer.class);
List<Customer> list=c.list();
System.out.println(list);
ts.commit();//提交事务
//ts.rollback();//回滚事务
session.close();//释放资源--游离状态
}