hibernate、spring、c3p0整合

12 篇文章 0 订阅
10 篇文章 0 订阅

jar包,就把hibernate、spring、c3p0的所有的jar包都导入,否则可能会报某些类找不到。

spring配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<property name="driverClass" value="oracle.jdbc.driver.OracleDriver">
		</property>
		<property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:ORCL"></property>
		<property name="user" value="HIBERNATE" />
		<property name="password" value="HIBERNATE" />

		<property name="minPoolSize" value="10" />
		<property name="maxPoolSize" value="100" />
		<property name="maxIdleTime" value="1800" />
		<property name="acquireIncrement" value="3" />
		<property name="maxStatements" value="1000" />
		<property name="initialPoolSize" value="10" />
		<property name="idleConnectionTestPeriod" value="60" />
		<property name="acquireRetryAttempts" value="30" />
		<property name="breakAfterAcquireFailure" value="true" />
		<property name="testConnectionOnCheckout" value="false" />
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.Oracle10gDialect
				</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
		<property name="mappingResources">
			<value>com/animal/pojo/Animal.hbm.xml</value>
		</property>
	</bean>

	<bean id="animalDao" class="com.animal.dao.AnimalDaoImpl">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

</beans>

SQL:

CREATE TABLE TB_ANIMAL
(
    ID INTEGER PRIMARY KEY,
    NAME VARCHAR2(20) NOT NULL
);

CREATE SEQUENCE SQ_ANIMAL
INCREMENT BY 1
START WITH 1
NOMAXVALUE
NOCYCLE
CACHE 10;

Animal.java:

package com.animal.pojo;

public class Animal {
	private int id;
	
	private String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

Animal.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.animal.pojo">

	<class name="Animal" table="tb_animal">
		<id name="id" column="id" type="integer">
			<generator class="sequence">  
                <param name="sequence">SQ_ANIMAL</param>  
            </generator>
		</id>
		<property name="name" column="name" type="string" />

	</class>

	<query name="getAnimalById">
		from Animal where id=?
	</query>

	<sql-query name="getAnimalByName">
		select * from tb_animal where name=?
	</sql-query>

</hibernate-mapping>

dao:

package com.animal.dao;

import com.animal.pojo.Animal;

public interface AnimalDao {
	public void save(Animal animal);
	public Animal selectById(int id);
}

package com.animal.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.animal.pojo.Animal;

public class AnimalDaoImpl extends HibernateDaoSupport implements AnimalDao {

	@Override
	public void save(Animal animal) {
		this.getHibernateTemplate().save(animal);
	}

	@Override
	public Animal selectById(int id) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Animal.class);
		criteria.add(Restrictions.eq("id", id));
		List<Animal> animalList = this.getHibernateTemplate().findByCriteria(criteria);
		if (animalList == null) {
			return null;
		}
		return animalList.get(0);
	}

}

测试代码:

package com.animal.test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.animal.dao.AnimalDao;
import com.animal.pojo.Animal;

import junit.framework.TestCase;

public class TestHibernateSpring extends TestCase {
	private static final BeanFactory factory = new ClassPathXmlApplicationContext("appcontext.xml");
	
	public void testSave() {
		AnimalDao animalDao = (AnimalDao)factory.getBean("animalDao");
		Animal animal = new Animal();
		animal.setName("animal_sh");
		animalDao.save(animal);
	}
	
	public void testSelectById() {
		AnimalDao animalDao = (AnimalDao)factory.getBean("animalDao");
		Animal animal = animalDao.selectById(50003);
		System.out.println(animal.getName());
	}
}

数据库中:

SQL> SELECT * FROM TB_ANIMAL;

        ID NAME
---------- --------------------
     50003 animal_sh

SQL>

所以上面java代码的id设置为50003。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
开始报错如下,需更换c3p0包 org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.connections.spi.ConnectionProvider] at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:261) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:225) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206) at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928) at test.UserTest01.save(UserTest01.java:20) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at org.junit.runners.ParentRunner.run(ParentRunner.java:300) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: org.hibernate.HibernateException: Could not instantiate connection provider [org.hibernate.connection.C3P0ConnectionProvider] at org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator.instantiateExplicitConnectionProvider(ConnectionProviderInitiator.java:197) at org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator.initiateService(ConnectionProviderInitiator.java:120) at org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator.initiateService(ConnectionProviderInitiator.java:55) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:105) at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:251) ... 34 more Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.connection.C3P0ConnectionProvider] as strategy [org.hibernate.engine.jdbc.connections.spi.ConnectionProvider] at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:128) at org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator.instantiateExplicitConnectionProvider(ConnectionProviderInitiator.java:194) ... 38 more

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值