Hibernate SessionFactory与Session
来源:互联网 发布:js输入框 input span 编辑:程序博客网 时间:2024/04/26 08:02
1、Hibernate中创建SessionFactory
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder() // 默认情况下Hibernate会去classPath下加载hibernate.cfg.xml文件 // 通过在configurate()方法里面添加配置文件名,指定新的配置文件,注意路径 .configure().build(); public void setHibernateSessionFactory() { try { sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory(); } catch (Exception e) { StandardServiceRegistryBuilder.destroy(registry); } }
2、SpringMVC+Hibernate中创建SessionFactory
@Repository // 定义为数据访问组件public class UserDaoImpl { @Resource // 自动装配,默认根据字段段名自动装配 private SessionFactory sessionFactory;}
<!-- 对应需要填写相应的配置信息 --> <!-- 使用这个时候需要引入 AspectJ包 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan"> <list> <!-- 可以添加多个包 --> <value>com.learndemo.entity</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop> </props> </property> </bean>
3、单元测试的时候创建SessionFactory
// 方法一:@RunWith(SpringJUnit4ClassRunner.class)public class UserTest { @Test @Transactional public void getAllUserTest2() { // 使用此方法获取并初始化我们的spring容器,注意pring-datasource.xml必须存放在类路径的根目录下。 ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring-hibernate.xml"); // 从spring容器中获取我们的会话工厂实例,里面已完成好各个属性的配置工作 SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory"); }}
// 方法二:@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath:spring-hibernate.xml" })public class UserTest { @Resource private SessionFactory sessionFactory = null;}
4、openSession与getCurrentSession的区别
public void getSession(){ Session session1 = sessionFactory.getCurrentSession(); Session session1 = sessionFactory.openSession(); }
(1)openSession每次打开都是新的Session,所以多次获取的Session实例是不同的,并且需要人为的调用close方法进行Session关闭。
(2)getCurrentSession是从当前上下文中获取Session并且会绑定到当前线程,第一次调用时会创建一个Session实例,如果该Session未关闭,后续多次获取的是同一个Session实例;事务提交或者回滚时会自动关闭Sesison,无需人工关闭。
使用getCurrentSession时,需要在配置文件中添加如下:
注:在使用spring 管理hibernate的时候不需要添加下列配置,否则会报错。原因参考:http://blog.csdn.net/yinjian520/article/details/8666695
<!-- 本地事务(JDBC事务) --><property name="current_session_context_class">thread</property><!-- 全局事务(JTA事务) --><property name="current_session_context_class">jta</property>
5、Session常用操作数据库操作
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath:spring-hibernate.xml" })@Transactionalpublic class sessionOperationTest { @Resource private SessionFactory sessionFactory = null; @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void test() { /* * 持久化对象的状态: * 1、临时对象:数据库和session缓存中都不存在对应的记录,且OID为NULL。 * 2、持久化对象(托管):OID为null并位于Session缓存中。 * 若在数据库中已经有和其对应的记录,持久化对象和数据库中的相关记录对; * Session在flush缓存时,会根据持久化对象的属性变化,来同步更新数据库; * 在同一个Session实例的缓存中,数据库表中的每条记录只对应唯一的持久化对象; * 3、删除对象(Removed):在数据库中没有和其OID对应的记录,不再处于Session缓存中。 * 一般情况下,应用程序不该再使用被删除的对象。 * 4、游离对象(脱管)(Detached):OID不为null,不再处于Session缓存中。 * 一般情况下,游离对象是由持久化对象转变过来的,因此在数据库中可能还存在与它对应的记录。 */ Session session = sessionFactory.getCurrentSession(); UserInfo userInfo = new UserInfo(); /* * get:根据给定的OID从数据库加载一个持久化对象。get每次执行都会执行sql语句。 * load:等同于get。load只是会在我们对拿到的实体进行操作的时候才去执行查询,拿到相应的实体信息。 * 无论是get还是load首先都会查一级缓存(session)中有没有相应的对应值,如果没有,再去数据库进行查找。 */ userInfo = session.get(UserInfo.class, 2); userInfo = session.load(UserInfo.class, 2); /* clear方法 清理session缓存 */ session.clear(); /* * save:使一个临时对象转变为持久化对象,并立即转换成insert语句执行并返回标示属性值即ID。 * persist:等同于save。persist保证当它在一个事物外部被调用时,并不立即转换成insert语句。 */ session.save(userInfo); session.persist(userInfo); /* update:使一个游离对象转变为持久化对象,并且计划执行一条update语句 */ session.update(userInfo); /* saveOrUpdate:包含save和update的功能。系统会自动进行选择 */ session.saveOrUpdate(userInfo); /* flush:将session缓存同步到数据库中,并刷新数据库 */ for (int i = 0; i < 1000; i++) { userInfo = new UserInfo(); session.save(userInfo); if (i % 20 == 0 && i != 0) { session.flush(); session.clear(); // 防止session缓存泄露 } } /* delete:把对象从Session的缓存中删除,该对象进入删除状态。并不立即执行。在commit中的flush时执行delete */ session.delete(userInfo); System.out.println(userInfo.getUsername()); /* Session 执行原始sql语句 */ List<UserInfo> userList = new ArrayList<UserInfo>(); String sql = ""; Query query = session.createQuery(sql); /* 返回查询的结果集 */ userList = query.getResultList(); // 未完待续。。。 }}
0 0
- Hibernate SessionFactory与Session
- Hibernate SessionFactory与Session
- [Hibernate系列—] 2. 创建SessionFactory 与 Session
- [Hibernate系列—] 2. 创建SessionFactory 与 Session
- Session 与SessionFactory
- sessionFactory与session
- Hibernate之Configuration,SessionFactory,Session
- Hibernate之Configuration,SessionFactory,Session
- Hibernate之SessionFactory和Session
- Hibernate之Configuration,SessionFactory,Session
- Hibernate之Configuration,SessionFactory,Session
- Hibernate之Configuration,SessionFactory,Session
- Hibernate的SessionFactory、Session介绍
- hibernate之SessionFactory和Session
- hibernate中的sessionfactory和session
- hibernate的sessionFactory和session
- Hibernate学习---Configuration,Session,SessionFactory
- Hibernate的SessionFactory和Session
- java数据类型的转换
- Scala数组
- nodejs excel导入导出
- Xcode 中的编译过程以及编译器
- 关于android studio闪退的问题
- Hibernate SessionFactory与Session
- Redis使用详细教程
- JSP小结-Cookie与Session
- Java开发环境问题
- CircleProgressBar 带载入动画的环形进度条
- Java compiler level does not match the version
- 【整理】不熟悉的git命令
- spring 事务 @Transactional注解参数 tx:annotation-driven
- MyBatis入门配置