1.使用hibernate框架流程
1>.加入必要的jar文件;
2>.hibernate.cfg.xml(hibernate基本的配置(链接数据库属性));
3>.hebernateSessionFactory类(读取hibernate.cfg.xml文件,根据读取文件的内容构建sessionFactory(构建session)类似于DBManager);
4>.xxx.hbm.xml文件(做ORM);
5>.创建DAO(得到session,通过session操作)DAO
6>.没有SQL 自动生成SQL
* 对象 数据库 session管理两者之间的关系
2.三种状态
(自由)瞬时状态 book存在内存 session没有关系→保存,删除时的对象
(管理)持久状态 book存在内存,数据库,session没有关系(纳入到session管理范围)→提交之后
(脱管)游离状态 book存在内存,数据库,session没有关系
3.初级总结
生成表的时候在hibernate.cfg.xml加入属性hibernate.hbmzddl.auto 值为update
query(接口)→一堆方法(懂语法的时候,可以使用query)
criteria(接口)→可以包含query,也可以解决query不能识别的问题,比如limit
load or get→load使用延时加载,在数据库使用之前不能关闭session,get可以关闭
批量加载的时候(在类的配置文件中lazy="true" batch-size="5" 推荐默认加载5条)
延时加载:lazy sql在使用时发送
批量加载:lazy=true batch="5" sql批量发送
及时加载:关联对象 lazy="false" fetch="select" sql一次全部发送(多条)
预先加载:关联对象 lazy="false" fetch="join" sql一条就解决
删除的时候:
如果是瞬时对象→解除关系
如果是持久对象→cascade=delete(删除两端的记录) cascade=save-update(解除关系)
sessionFactory:
构建sessionFactory非常耗时,只创建一次
映射整个数据库 线程不安全 重量级对象
session:
操作实体对象 轻量级对象 线程安全
4.缓存机制
一级缓存基于session 清楚缓存三种方法:
clear()
close()
evict()→剔除指定的缓存对象
二级缓存基于sessionFactory,二级缓存可以被多个session共享,是根据ID获得的实体对象:
开启:
在hibernate.cfg.xml中开启
ehrache.xml配置
实体的hbm文件中配置cache元素
5.测试代码
工程网络
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/mytest3</property>
<property name="connection.username">root</property>
<property name="connection.password">1111</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="com/hellojava/hibernate/entity/Product.hbm.xml"></mapping>
<mapping resource="com/hellojava/hibernate/entity/OrderTable.hbm.xml"></mapping>
</session-factory>
sessionFactory创建public class HibernateSessionFactory {
private static SessionFactory sessionFactory;
private static String cfgFilePath="/hibernate.cfg.xml";
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void setSessionFactory(SessionFactory sessionFactory) {
HibernateSessionFactory.sessionFactory = sessionFactory;
}
public static String getCfgFilePath() {
return cfgFilePath;
}
public static void setCfgFilePath(String cfgFilePath) {
HibernateSessionFactory.cfgFilePath = cfgFilePath;
}
private static Configuration configuration=new Configuration();
private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
static{
configuration.configure(cfgFilePath);
ServiceRegistryBuilder builder=new ServiceRegistryBuilder().applySettings(configuration.getProperties());
ServiceRegistry registry=builder.buildServiceRegistry();
sessionFactory=configuration.buildSessionFactory(registry);
}
private static void rebuilderSessionFactory(){
configuration.configure(cfgFilePath);
ServiceRegistryBuilder builder=new ServiceRegistryBuilder().applySettings(configuration.getProperties());
ServiceRegistry registry=builder.buildServiceRegistry();
sessionFactory=configuration.buildSessionFactory(registry);
}
public static Session openSession(){
Session session=threadLocal.get();
if(session==null){
if(sessionFactory==null){
rebuilderSessionFactory();
}
session=sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
public static void closeSession(){
Session session=threadLocal.get();
if(session!=null){
session.close();
threadLocal.set(null);
}
}
}
dao层测试(增删改查)public class ProductDao {
public static void main(String[] args) {
Session session=HibernateSessionFactory.openSession();
Transaction t = session.beginTransaction();
// 像数据表里面添加数据
/*Product p=new Product();
p.setProductName("小米手机");
for (int i = 0; i < 3; i++) {
OrderTable order=new OrderTable();
order.setOrderNumber("10000"+(i+1));
p.getOrders().add(order);
}
session.save(p);
t.commit(); */
// 修改数据
/*Product p=(Product) session.load(Product.class,1);
p.setProductName("荣耀X6");
session.update(p);
t.commit();*/
// 删除数据 只能删除product 和order_product表里面的数据(删除数据,删除)
/*Product p=new Product();
p.setProductId(3);
session.delete(p);
t.commit();*/
// 查询数据
List<Product> ps=session.createCriteria(Product.class).list();
ps.forEach((p)->{
System.out.println(p.getProductId()+"--"+p.getProductName());
p.getOrders().forEach((o)->{
System.out.println(o.getOrderNumber());
});
});
}
}
Dao测试(缓存)public class BookDao {
public static void main(String[] args) {
Session session=HibernateSessionFactory.openSession();
Book book=(Book) session.load(Book.class, 1);
System.out.println(book.getBookName()+"--"+book.getBookAuthor());
// 清楚缓存
// session.clear();
// 从session的缓存 中剔除book对象(指定)
// session.evict(book);
session.close();
Session session1=HibernateSessionFactory.openSession();
Book book1=(Book) session1.load(Book.class, 1);
System.out.println(book1.getBookName()+"--"+book1.getBookAuthor());
}
}
三大状态public void save(Book book){
Session session=HibernateSessionFactory.openSession();
Transaction t=session.beginTransaction();
try{
//book存在内存,与session没有关系 瞬时状态(自由状态)
session.save(book);
//book 存在内存,数据库,session有关系 持久状态(管理状态)
t.commit();
//book 存在内存,数据库,session不存在 游离状态(脱管)
session.close();
}catch(Exception e){
t.rollback();
e.printStackTrace();
}
}
query和criteria接口public class StudentDao {
public static void main(String[] args) {
Session session=HibernateSessionFactory.openSession();
/*Transaction t=session.beginTransaction();
Students s=new Students();
s.setStuName("张三");
s.setStuSex("男");
s.setStuAge(25);
session.save(s);
t.commit();*/
/*
* 使用get出来的数据在没有使用之前,session可以关闭
* get不使用延时加载
* load当前找不到指定的对象是报异常*/
/*Students s=(Students) session.get(Students.class, 4);
System.out.println(s.getStuName());
session.close();*/
/*
* 使用load出来的数据在没有使用之前,session不可以关闭
* load使用延时加载,在xml文件里面可以更改是否使用延时加载,lazy="false",关闭延时加载
* 数据在没有真正使用的时候hibernate其实没有加载数据
* 返回一个当前对象的代理对象(空的)
* get 找不到当前对象返回null*/
/*Students s=(Students) session.load(Students.class, 1);
session.close();
System.out.println(s.getStuName());*/
/*
* Query查询
* 查询students表的全部记录
* HQL(hibernate query language) sql 表HQL对象*/
//查询全部数据
/*String hql="from Students";
Query q=session.createQuery(hql);
((List<Students>)q.list()).forEach((s)->{
System.out.println(s.getStuName());
});*/
//根据条件查询数据
// String hql="from Students where stuId=1";
// String hql="from Students where stuId between 2 and 3";
// String hql="from Students where stuName like '%林%'";
// 查找分组时候,返回值为string
// String hql="select stuSex from Students group by stuSex";
// String hql="select new Students(stuId,stuSex) from Students group by stuSex";
String hql="select stuSex,stuId from Students group by stuSex";
// String hql="from Students order by stuId desc";
// String hql="from Students where stuName=? and stuId=?";
// Query q=session.createQuery(hql);
// q.setString(0, "林师兄");
// q.setInteger(1, 4);
//
// String hql="insert into Students(stuName,stuSex,stuAge) values(?,?,?)";
// String hql="delete from Students where stuId=4";
/*String hql="update Students set stuName=? where stuId=?";
Query q=session.createQuery(hql);
q.setString(0, "马航飞");
q.setInteger(1, 1);*/
/*q.setString(0, "关雎儿");
q.setString(1, "女");
q.setInteger(2, 22);*/
// q.executeUpdate();
// session.beginTransaction().commit();
//返回值为Students对象
Query q=session.createQuery(hql);
// List<Students> ss=q.list();
// ss.forEach((s)->{
// System.out.println(s.getStuId()+"--"+s.getStuSex());
// });
//返回值为String类型
/*List<String> ss=q.list();
ss.forEach((s)->{
System.out.println(s);
});*/
//返回值为Object[]数组
List<Object[]> ss=q.list();
ss.forEach((s)->{
System.out.println(s[0]+"--"+s[1]);
});
// criteria
Criteria c=session.createCriteria(Students.class);
// List<Students> students=c.list();
// students.forEach((s)->{
// System.out.println(s.getStuName());
// });
//大于,大于等于,小于,小于等于
//大于等于
// c.add(Restrictions.ge("stuId", 2));
//小于等于
// c.add(Restrictions.le("stuId", 3));
//不等于
// c.add(Restrictions.ne("stuId", 5));
// c.add(Restrictions.between("stuId",1,8));
// c.add(Restrictions.not(Restrictions.between("stuId", 1, 3)));
// c.add(Restrictions.in("stuId", new Object[]{1,3}));
// c.add(Restrictions.not(Restrictions.in("stuId", new Object[]{1,3})));
// c.add(Restrictions.isNull("stuName"));
// c.add(Restrictions.isNotNull("stuName"));
// c.addOrder(Order.asc("stuId"));
// c.addOrder(Order.desc("stuId"));
// c.add(Restrictions.like("stuName", "%林%"));
//过滤重复项
// c.setProjection(Projections.distinct(Projections.property("stuName")));
//分组
// c.setProjection(Projections.groupProperty("stuSex"));
// c.setProjection(Projections.avg("stuId"));
// c.setProjection(Projections.sum("stuId"));
// c.setProjection(Projections.count("stuId"));
// c.setProjection(Projections.max("stuId"));
// c.setProjection(Projections.min("stuId"));
//设置分页的时候可以使用此方法
// c.setFirstResult(0);
// c.setMaxResults(3);
/*Integer avg=(Integer) c.uniqueResult();
System.out.println(avg);*/
/*List<Students> students=c.list();
students.forEach((s)->{
System.out.println(s.getStuName());
});*/
/* Students s1=(Students) session.load(Students.class, 1);
Students s2=(Students) session.load(Students.class, 2);
Students s5=(Students) session.load(Students.class, 5);
Students s6=(Students) session.load(Students.class, 6);
Students s7=(Students) session.load(Students.class, 7);
Students s8=(Students) session.load(Students.class, 8);
Students s9=(Students) session.load(Students.class, 9);
System.out.println(s1.getStuName());
System.out.println(s2.getStuName());
System.out.println(s5.getStuName());
System.out.println(s6.getStuName());
System.out.println(s7.getStuName());
System.out.println(s8.getStuName());
System.out.println(s9.getStuName());*/
}
}