package com.yjm.pojo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestH { //保存一条记录 public void test1() { Configuration conf = new Configuration().configure(); SessionFactory sessionFactory = conf.buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction().begin(); UserInfo u = new UserInfo(); u.setPassword("password"); u.setUsername("username"); session.save(u); session.getTransaction().commit(); } //保存一条记录 public void test2() { ApplicationContext ac = new ClassPathXmlApplicationContext( "spring_dao.xml"); System.out.println(ac.getBean("sessionfactory")); System.out.println(ac.getBean("sessionfactory")); Session session = ((SessionFactory) ac.getBean("sessionfactory")) .openSession(); UserInfo u = new UserInfo(); u.setPassword("password"); u.setUsername("username"); session.beginTransaction().begin(); session.save(u); session.getTransaction().commit(); } //保存一条记录 public void test3() { ApplicationContext ac = new ClassPathXmlApplicationContext( "spring_dao.xml"); System.out.println(ac.getBean("sessionfactory")); System.out.println(ac.getBean("sessionfactory")); Session session = ((SessionFactory) ac.getBean("sessionfactory")) .getCurrentSession(); Session session1 = ((SessionFactory) ac.getBean("sessionfactory")) .getCurrentSession(); // 输出值 // org.hibernate.impl.SessionFactoryImpl@128edf2 // org.hibernate.impl.SessionFactoryImpl@128edf2 System.out.println(session); System.out.println(session1); UserInfo u = new UserInfo(); u.setPassword("password"); u.setUsername("username"); session.beginTransaction().begin(); session.save(u); session.getTransaction().commit(); } //保存一条记录 public void test4() { ApplicationContext ac = new ClassPathXmlApplicationContext( "spring_dao.xml"); // org.hibernate.impl.SessionFactoryImpl@128edf2 // org.hibernate.impl.SessionFactoryImpl@128edf2 System.out.println(ac.getBean("sessionfactory")); System.out.println(ac.getBean("sessionfactory")); UserInfo u = new UserInfo(); u.setPassword("password"); u.setUsername("username"); ((SessionFactory) ac.getBean("sessionfactory")).getCurrentSession() .beginTransaction().begin(); ((SessionFactory) ac.getBean("sessionfactory")).getCurrentSession() .save(u); ((SessionFactory) ac.getBean("sessionfactory")).getCurrentSession() .getTransaction().commit(); } @Test public void test5() { ApplicationContext ac = new ClassPathXmlApplicationContext( "spring_dao.xml"); SessionFactory sessionFactory = (SessionFactory) ac .getBean("sessionfactory"); Session session = sessionFactory.openSession(); session.beginTransaction().begin(); UserInfo u = (UserInfo) session.get(UserInfo.class, 5l); System.out.println("get:" + u.getId()); List<UserInfo> userinfos = session.createCriteria(UserInfo.class).add( Restrictions.eq("password", "password")).add( Restrictions.eq("username", "username")).list(); int userinfos1 = ((Integer) (session.createCriteria(UserInfo.class) .add(Restrictions.eq("password", "password")).add( Restrictions.eq("username", "username")).setProjection( Projections.rowCount()).uniqueResult())).intValue(); System.out.println("获取的总数数目:" + userinfos1); System.out.println("总数:" + userinfos.size()); for (UserInfo userInfo : userinfos) { System.out.println(userInfo.getPassword()); System.out.println(userInfo.getId()); } session.getTransaction().commit(); } }
getCurrentSession() 有就用当前的,没有就创建。openSession()创建
spring配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="sessionfactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> </bean> </beans>
hibernate配置
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- MySql数据库 --> <property name="connection.url"> jdbc:mysql://localhost:3306/mdmtest?useUnicode=true&characterEncoding=UTF-8 </property> <property name="connection.username">root</property> <property name="connection.password">1234</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <property name="connection.autocommit">true</property> <property name="hibernate.current_session_context_class">thread</property> <!-- configuration pool c3p0--> <property name="hibernate.connection.provider_class"> org.hibernate.connection.C3P0ConnectionProvider </property> <property name="c3p0.min_size">10</property> <property name="c3p0.max_size">50</property> <property name="c3p0.maxIdleTime">180</property> <property name="c3p0.time_out">1800</property> <property name="c3p0.max_statement">0</property> <property name="c3p0.acquire_increment">1</property> <property name="c3p0.idle_test_period">120</property> <property name="c3p0.validate">true</property> <mapping resource="com/yjm/pojo/userinfo.hbm.xml" /> </session-factory> </hibernate-configuration>
spring HibernateDaoSupport 是一个抽象类,
private HibernateTemplate hibernateTemplate;
用hibernate sessionFactory setSessionFactory 初始化 hiberntateTemplate方法
private HibernateTemplate hibernateTemplate;
/*jadclipse*/// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) radix(10) lradix(10) // Source File Name: HibernateDaoSupport.java package org.springframework.orm.hibernate3.support; import org.hibernate.*; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.support.DaoSupport; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.orm.hibernate3.SessionFactoryUtils; public abstract class HibernateDaoSupport extends DaoSupport { public HibernateDaoSupport() { } public final void setSessionFactory(SessionFactory sessionFactory) { if (hibernateTemplate == null || sessionFactory != hibernateTemplate.getSessionFactory()) hibernateTemplate = createHibernateTemplate(sessionFactory); } protected HibernateTemplate createHibernateTemplate( SessionFactory sessionFactory) { return new HibernateTemplate(sessionFactory); } public final SessionFactory getSessionFactory() { return hibernateTemplate == null ? null : hibernateTemplate .getSessionFactory(); } public final void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } public final HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } protected final void checkDaoConfig() { if (hibernateTemplate == null) throw new IllegalArgumentException( "'sessionFactory' or 'hibernateTemplate' is required"); else return; } protected final Session getSession() throws DataAccessResourceFailureException, IllegalStateException { return getSession(hibernateTemplate.isAllowCreate()); } protected final Session getSession(boolean allowCreate) throws DataAccessResourceFailureException, IllegalStateException { return allowCreate ? SessionFactoryUtils.getSession( getSessionFactory(), hibernateTemplate.getEntityInterceptor(), hibernateTemplate.getJdbcExceptionTranslator()) : SessionFactoryUtils.getSession(getSessionFactory(), false); } protected final DataAccessException convertHibernateAccessException( HibernateException ex) { return hibernateTemplate.convertHibernateAccessException(ex); } protected final void releaseSession(Session session) { SessionFactoryUtils.releaseSession(session, getSessionFactory()); } private HibernateTemplate hibernateTemplate; } /* DECOMPILATION REPORT Decompiled from: C:\Users\yjm18\Workspaces\MyEclipse 8.6\BaseCKS\WebRoot\WEB-INF\lib\org.springframework.orm-3.1.0.RELEASE.jar Total time: 48 ms Jad reported messages/errors: Exit status: 0 Caught exceptions: */
Hibernate: select userinfo0_.t_id as t1_0_0_, userinfo0_.t_username as t2_0_0_, userinfo0_.t_password as t3_0_0_ from t_userinfo userinfo0_ where userinfo0_.t_id=?
get:5
Hibernate: select this_.t_id as t1_0_0_, this_.t_username as t2_0_0_, this_.t_password as t3_0_0_ from t_userinfo this_ where this_.t_password=? and this_.t_username=?
Hibernate: select count(*) as y0_ from t_userinfo this_ where this_.t_password=? and this_.t_username=?
获取的总数数目:7
总数:7
password
2
password
3
password
4
password
5
password
6
password
7
password
8