一、hibernate的API
1.Configuration:hibernate的配置对象
作用:加载核心配置文件
(1)hibernate.proprieties
Configuration cfg = new Configuration();
(2)hibernate.cfg.xml
Configuration = new Configuration().configure();
加载映射文件:
手动加载:
configuration.addResource("路径名");
2.SessionFactory
内部维护了hibernate的连接池和hibernate的二级缓存。是线程安全的对象。一个项目创建一个对象即可。
配置连接池
<!-- 配置C3P0连接池 -->
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!--在连接池中可用的数据库连接的最少数目 -->
<property name="c3p0.min_size">5</property>
<!--在连接池中所有数据库连接的最大数目 -->
<property name="c3p0.max_size">20</property>
<!--设定数据库连接的过期时间,以秒为单位,
如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
<property name="c3p0.timeout">120</property>
<!--每3000秒检查所有连接池中的空闲连接 以秒为单位-->
<property name="c3p0.idle_test_period">3000</property>
抽取工具类:
public class HibernateUtils {
public static final Configuration cfg;
public static final SessionFactory sf;
static {
cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
}
public static Session opeSession() {
return sf.openSession();
}
}
编写测试类
@Test
public void demo1() {
Session session = HibernateUtils.opeSession();
Transaction transaction = session.beginTransaction();
Customer customer = new Customer();
customer.setCust_name("shawchen");
session.save(customer);
transaction.commit();
session.close();
}
Session对象:类似于jdbc的connection对象
Session代表的是hibernate与数据库的连接对象。不是线程安全的,与数据库交互桥梁。
session中的API
保存的方法:serializable save(Object obj);
查询的方法:
T get(Class c,Serializable id);
T load(Class c,Serializable id);
get方法和load方法的区别?
@Test
public void demo2() {
Session session = HibernateUtils.opeSession();
Transaction transaction = session.beginTransaction();
/**
*get方法
*采用的是立即加载,执行到这行代码的时候,就会马上发送sql语句去查询
*查询后返回真实对象本身
*查询不到返回null
*
*load方法
*采用的是延迟加载,执行到这行代码的时候,不会发动sql语句,当真正使用这个对象的时候才会发送sql语句
*查询后返回的是代理对象
*查询不到会报错
*/
//使用get方法查询
Customer customer = session.get(Customer.class,2l );
System.out.println(customer);
//使用load方法查询
Customer customer2 = session.load(Customer.class, 2l);
System.out.println(customer2);
transaction.commit();
session.close();
}
修改的方法
@Test
public void demo3() {
Session session = HibernateUtils.opeSession();
Transaction transaction = session.beginTransaction();
//直接创建对象,进行修改
// Customer customer = new Customer();
// customer.setCust_id(1l);
// customer.setCust_name("aaa");
// session.update(customer);
//先查询,在修改(推荐)
Customer customer2 = session.get(Customer.class, 1l);
customer2.setCust_mobile("11111");
session.update(customer2);
transaction.commit();
session.close();
}
删除的方法
@Test
public void demo4() {
Session session = HibernateUtils.opeSession();
Transaction transaction = session.beginTransaction();
//直接创建对象,删除
// Customer customer = new Customer();
// customer.setCust_id(1l);
// session.delete(customer);
//先查询再删除--级联删除
Customer customer2 = session.get(Customer.class, 2l);
session.delete(customer2);
transaction.commit();
session.close();
}
Transaction事务对象
Hibernate中管理事务的对象。
Commit();
Rollback();