hibernate、spring、c3p0整合

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

spring配置文件:





	
		
		
		
		
		

		
		
		
		
		
		
		
		
		
		
	

	
		
			
		
		
			
				
					org.hibernate.dialect.Oracle10gDialect
				
				true
			
		
		
			com/animal/pojo/Animal.hbm.xml
		
	

	
		
	


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:






	
		
			  
                SQ_ANIMAL  
            
		
		

	

	
		from Animal where id=?
	

	
		select * from tb_animal where name=?
	



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 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。

你可能感兴趣的:(hibernate,c3p0,spring,java)