Spring3 + Hibernate3.6 实现简单 CRUD

jopen 12年前

本来是想拿Spring整合Hibernate4的,事实证明我道行尚浅 未遂……

 

看到这个异常,且在用Hibernate4的同学就要考虑Hibernate的版本问题了

(解决完这个问题发现4里边把HibernateTemplate取消掉了,所以就没再死扣)。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ' XXXXX ': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplate' defined in class path resource [applicationContext-common.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;

 

 

 

 

原来弄过spring+ibatis的整合,其实道理差不多

都是spring帮忙注入,OR框架去数据库中CRUD,仅有的一点区别就是ibatis的SQL是手动的,Hibernate的HQL是自动的,所以Hibernate要实体Student用Annotation声明一下

Spring3 + Hibernate3.6 实现简单 CRUD

 

 

 

 

一:model

用Hibernate的方式,声明实体、表名、主键等。

工程里不再需要 hibernate.cfg.xml 了,在spring配置文件的:hibernateProperties标签里配置就行了

@Entity//测试程序里唯一一个实体  @Table(name="t_student")//指定表名t_student  public class Student   {   private int studentid;   private String name;   private int age;      public String toString()   {    return " id=>"+studentid+" name=>"+name+" age=>"+age;   }      //setter&getter   @Id//主键   @GeneratedValue//自增长   public int getStudentid() {    return studentid;   }


 

 

二:具体service

业务调用具体service时候,就需要其中聚合的DaoImpl,通过setter靠spring注入

@Resource(name="StudentDAOImpl01")指定注入的名字

@Component("StudentService")//组件  public class StudentService {      //下边的setter定义了将要注入的实例   private IStudentDAO studentDAO;        public void add(Student stu) {//test调用这个add方法    studentDAO.addStudent(stu);   }   public List<Student> getAll() {    return studentDAO.selectAll();   }     public void delById(int id) {    studentDAO.delStudentById(id);   }      public void updateStudent(Student stu) {    studentDAO.updateStudent(stu);   }      public List<Student> selectByName(String name) {    return studentDAO.selectStudentByName(name);   }            //setter&getter   public IStudentDAO getStudentDAO() {    return studentDAO;   }   @Resource(name="StudentDAOImpl01")//等StudentDAOImpl的注入   public void setStudentDAO(IStudentDAO studentDAO) {    this.studentDAO = studentDAO;   }   /*其他注入方式*/   }


 

 

 

三:DaoImpl

(IDao就几个接口就不说了)

要把自己通过@Component("StudentDAOImpl01")准备好,等spring注入到上边的具体service里,靠名字识别

ibatis这里还要找到实体的配置文件,这里直接用HQL就行了,Hibernate会帮忙生成SQL语句

这用到:

hibernateTemplate.save(stu);

hibernateTemplate.delete(stu);

hibernateTemplate.update(stu);

(Student)hibernateTemplate.get(Student.class,new Integer(id)); 

hibernateTemplate.find(hql,name);

其中find里边直接写HQL就行了,需要传参的话可以第一参数是带占位符的String,后一个传值

@Component("StudentDAOImpl01")//会作为组件,注入到servise里  public class StudentDAOImpl implements IStudentDAO  {    private HibernateTemplate hibernateTemplate;   public HibernateTemplate getHibernateTemplate() {    return hibernateTemplate;   }   @Resource//等待spring配置文件里配的hibernateTemplate注入   public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {    this.hibernateTemplate = hibernateTemplate;   }     //下边是HQL的具体实现   @Override   public void addStudent(Student stu) {//不指定id就能自动BySequence    hibernateTemplate.save(stu);    System.out.println("插入时返回的对象=》"+stu.getStudentid());//打印返回的值    }     @Override   public void delStudentById(int id) {    //应该先select检查一下    Student stu = hibernateTemplate.load(Student.class,new Integer(id));      hibernateTemplate.delete(stu);   }     @Override   public void updateStudent(Student stu) {    hibernateTemplate.update(stu);   }     @Override   public Student selectStudentById(int id) {    Student stu = new Student();    stu = (Student)hibernateTemplate.get(Student.class,new Integer(id));     return stu;   }     @Override   public List<Student> selectStudentByName(String name) {    String hql = "from Student t where t.name IN ?";    List<Student> stus = new ArrayList<Student>();    stus = (List<Student>)hibernateTemplate.find(hql,name);     return stus;   }     @Override   public List<Student> selectAll() {    List<Student> stus = new ArrayList<Student>();    stus = (List<Student>)hibernateTemplate.find("from Student");    return stus;   }       }


 

四:spring的配置文件

1.JDBC配置

2.sessionFactory ,这里边要配上Hibernate.cfg.xml的内容

3.hibernateTemplate

<?xml version="1.0" encoding="UTF-8"?>  <beans xmlns="http://www.springframework.org/schema/beans"         xmlns:tx="http://www.springframework.org/schema/tx"         xmlns:aop="http://www.springframework.org/schema/aop"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xmlns:context="http://www.springframework.org/schema/context"         xsi:schemaLocation="http://www.springframework.org/schema/beans              http://www.springframework.org/schema/beans/spring-beans-2.5.xsd              http://www.springframework.org/schema/tx          http://www.springframework.org/schema/tx/spring-tx-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/context              http://www.springframework.org/schema/context/spring-context-2.5.xsd">     <context:annotation-config />   <context:component-scan base-package="com.rt" />            <!-- 1.JDBC配置:dataSource -->   <bean    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">    <property name="locations">     <value>classpath:jdbc.properties</value>    </property>   </bean>   <bean id="dataSource" destroy-method="close"    class="org.apache.commons.dbcp.BasicDataSource">    <property name="driverClassName"     value="${jdbc.driverClassName}" />    <property name="url" value="${jdbc.url}" />    <property name="username" value="${jdbc.username}" />    <property name="password" value="${jdbc.password}" />   </bean>    <!-- 2.sessionFactory -->   <bean id="sessionFactory"    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">    <!-- hibernate具体配置,分项写在下边 -->    <property name="hibernateProperties">     <props>      <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>      <prop key="hibernate.show_sql">true</prop>      <prop key="hibernate.hbm2ddl.auto">update</prop>     </props>    </property>    <!-- 注入dataSource对象 -->    <property name="dataSource" ref="dataSource" />      <!-- 搜索带Annotation的实体 -->    <property name="packagesToScan">     <list>      <value>com.rt.sidemo.model</value>      <!--<value>com.rt.sidemo....</value> -->     </list>    </property>     </bean>  <!-- Template -->   <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">    <property name="sessionFactory" ref="sessionFactory"></property>   </bean>         </beans>

JDBC的配置

jdbc.driverClassName=oracle.jdbc.driver.OracleDriver  jdbc.url=jdbc:oracle:thin:@localhost:1521:ORCL  jdbc.username=scott  jdbc.password=890307


 

 

 

五:test

public class StudentServiceTest   {   @Test   public void testAdd() throws Exception {        //Spring读取spring配置信息    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-common.xml");    //相当于从代理类得到具体实例,由xml决定怎么选择类实例化     StudentService service01 = (StudentService)ctx.getBean("StudentService");         Student stu = new Student();//手动组装User实例 u    //stu.setStudentid(???); 用自动增长序列    stu.setName("Spring+Hibernate");    stu.setAge(777);    service01.add(stu);//把组装好的u传给xml实例化的service         ctx.destroy();   }      @Test   public void testDelById() throws Exception {     ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-common.xml");    StudentService service01 = (StudentService)ctx.getBean("StudentService");         service01.delById(23);//只需要把id传给实例化的service        ctx.destroy();   }      @Test   public void testGetAll() throws Exception {     ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-common.xml");    StudentService service01 = (StudentService)ctx.getBean("StudentService");         System.out.println("查询全部:");    List<Student> stusAll = (List<Student>)service01.getAll();    for(int i=0;i<stusAll.size();i++)    {     System.out.println(stusAll.get(i));    }    ctx.destroy();   }      @Test   public void testUpdateStudent() throws Exception {    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-common.xml");     StudentService service01 = (StudentService)ctx.getBean("StudentService");         Student stu = new Student();//手动组装User实例 u    stu.setStudentid(25);    stu.setName("SH");    stu.setAge(777);    service01.updateStudent(stu);//把组装好的u传给spring实例化的service         ctx.destroy();   }      @Test   public void testSelectByName() throws Exception {     ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-common.xml");    StudentService service01 = (StudentService)ctx.getBean("StudentService");         System.out.println("查询全部:");    String name = "SH";    List<Student> stusAll = (List<Student>)service01.selectByName(name);    for(int i=0;i<stusAll.size();i++)    {     System.out.println(stusAll.get(i));    }    ctx.destroy();   }     }

来自: http://blog.csdn.net/ruantao1989/article/details/8170108