码迷,mamicode.com
首页 > 数据库 > 详细

spring保存一条数据库记录

时间:2015-12-16 19:45:46      阅读:372      评论:0      收藏:0      [点我收藏+]

标签:sessionfactory保存记录

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();
	}
	//保存一条记录
	@Test
	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();

	}

}

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&amp;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:
*/


spring保存一条数据库记录

标签:sessionfactory保存记录

原文地址:http://yjm199.blog.51cto.com/4408395/1725340

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!