问答详情
源自:2-6 session详解(下)

程序运行结果与视频不一致,采用getCurrentSession()获得的connection为何不一致

使用GetCurrentSession(),打印出来的connection对象的hashcode是不同的,这是为什么

提问者:幕粉guosha 2016-11-23 16:26

个回答

  • zqdip
    2017-09-22 23:20:25

    @Test
    	public void testSaveStudentWithGetCurrentSession(){
    		Configuration config = new Configuration().configure();
    		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
    		SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
    		
    		Session session1 = sessionFactory.getCurrentSession();
    		
    		Transaction t = session1.beginTransaction();
    		
    		Student s = new Student(1,"张三","男",new Date(),"北京");
    		session1.doWork(new Work(){
    			@Override
    			public void execute(Connection conn) throws SQLException {
    				System.out.println("connection hasCode:"+conn.hashCode());
    			}
    		});
    		
    		session1.save(s);
    		t.commit();
    		
    		
    		Session session2 = sessionFactory.getCurrentSession();
    		t = session2.beginTransaction();
    		s = new Student(2,"李四","男",new Date(),"上海");
    		session2.doWork(new Work(){
    			@Override
    			public void execute(Connection conn) throws SQLException {
    				System.out.println("connection hasCode:"+conn.hashCode());
    			}
    		});
    		
    		session2.save(s);
    		t.commit();
    		
    	}

    配置文件

    <hibernate-configuration>
        <session-factory>
        	<property name="connection.username">root</property>
        	<property name="connection.password">12721931</property>
        	<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        	<property name="connection.url">jdbc:mysql:///hibernate?useUnicode=true&amp;characterEncoding=UTF-8</property>
        	<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
       
       
       		<property name="show_sql">true</property>
       		<property name="format_sql">true</property>
       		<property name="hibernate.default_schema">hibernate</property>
       		<property name="hbm2ddl.auto">create</property>
       		<property name="hibernate.current_session_context_class">thread</property>
       
       		<mapping resource="Student.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>

    运行结果

    connection hasCode:737077247
    Hibernate: 
        insert 
        into
            hibernate.STUDENT
            (NAME, GENDER, BIRTHDAY, ADDRESS, SID) 
        values
            (?, ?, ?, ?, ?)
    connection hasCode:335359181
    Hibernate: 
        insert 
        into
            hibernate.STUDENT
            (NAME, GENDER, BIRTHDAY, ADDRESS, SID) 
        values
            (?, ?, ?, ?, ?)


  • 慕粉4059636
    2017-08-28 17:41:51

    我也是,使用的是getCurrentSession获得的hashcode不一致

  • SkyFreecss
    2016-11-24 22:08:47

    把你的測試代碼放上來,要不然你這問題無解(⊙o⊙)…