hibernate和spring的整合

本文介绍了一个结合使用Spring和Hibernate框架的实例,详细展示了从环境搭建到实现学生信息增删改查功能的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.导入spring和hibernate必备的jar包文件

2.新建一个源文件config

3.项目分包和建类


4.hibernate.cfg.xml的总配置文件
<?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>
         <!-- 配置方言 -->
         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        
        <!-- 自动创建表 -->
         <property name="hbm2ddl.auto">update</property>
         
         <!-- 在控制台打印sql -->
         <property name="show_sql">true</property>
         <!-- 格式化sql -->
         <property name="format_sql">true</property>
    </session-factory>
</hibernate-configuration>

5.spring中的bean.xml总配置文件;

<?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:util="http://www.springframework.org/schema/util"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
     <!-- 开启注解扫描 -->
<context:component-scan 
base-package="com.eduask" />
  <mvc:annotation-driven />
     <!-- 引入外部资源 数据库配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>
     <!-- 配置dbcp连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="url" value="${url}" />
<property name="username" value="${user}" />
<property name="password" value="${pwd}" />
<property name="driverClassName" value="${driver}" />
    </bean>
   
    <!-- 配置sessionfactory hibernate总的配置文件--> 
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="configLocation" value="classpath:hibernate/hibernate.cfg.xml"></property>
       <!-- 设置数据源 -->
       <property name="dataSource" ref="dataSource"/>
         <!-- 配置扫描 com/eduask/pojo/mapper路径下的 mapper.xml文件-->
       <property name="mappingLocations" value="classpath:com/eduask/pojo/mapper/*.hbm.xml"></property>
     </bean>
     <!-- 配置声明式事务  -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
         <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 启用事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
     <!-- hibernateTemplate-->
     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
       <property name="sessionFactory" ref="sessionFactory"></property>
    </bean> 
 </beans>

6.StudentDao类

package com.eduask.dao;
import java.util.List;
import com.eduask.pojo.Student;
//定义一个StudentDao的接口;
public interface StudentDao {
  //根据id查询;
Student getStudentById(int id) throws Exception  ;
 //查询所有;
List<Student> getStudents() throws Exception;
 //添加;
void insertStudent(Student student) throws Exception;
 //删除;
void deleteStudent(int id) throws Exception;
 //修改;
    void updateStudent(Student student) throws Exception;
}

7.StudentDaoImpl类;

package com.eduask.dao.impl;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
import com.eduask.dao.StudentDao;
import com.eduask.pojo.Student;
@Repository
public class StudentDaoImpl implements StudentDao {
    private Session session=null;
    @Resource(name="sessionFactory")
    public void setSessionFactory(SessionFactory sessionFactory){
    this.session=sessionFactory.openSession();
    }
public Student getStudentById(int id) throws Exception {
// TODO Auto-generated method stub
return (Student) session.get(Student.class, id);
}
public List<Student> getStudents() throws Exception {
        //Student为大写;
String hql="from Student";
         Query query=session.createQuery(hql);
        return query.list();
}
public void insertStudent(Student student) throws Exception {
         Transaction tr=session.beginTransaction();
         session.save(student);
         tr.commit();
         session.close();
}
public void deleteStudent(int id) throws Exception {
// TODO Auto-generated method stub
Student student=getStudentById(id);
Transaction tr=session.beginTransaction();
         session.delete(student);
tr.commit();
         session.close();
}
public void updateStudent(Student student) throws Exception {
// TODO Auto-generated method stub
Transaction tr=session.beginTransaction();
         session.update(student);
tr.commit();
         session.close();
}
}

8.StudentTest类

package com.eduask.test;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.eduask.dao.StudentDao;
import com.eduask.dao.impl.StudentDaoImpl;
import com.eduask.pojo.Student;
public class StudentTest {
//引入spring中的bean.xml配置文件;
  private ClassPathXmlApplicationContext cx=null;
  @Before
  public void setUp(){
 cx=new ClassPathXmlApplicationContext("spring/bean.xml");
  }
  //增加;
  @Test
  public void testInsertStudent() throws Exception{
 StudentDao studentDao=cx.getBean(StudentDaoImpl.class);
 Student student=new Student();
 student.setName("link");
 student.setPwd("123456");
 studentDao.insertStudent(student);
   }
  //删除 
  //删除需要获得id,在StudentDaoImpl类中删除方法中调用获得id的方法;
  @Test
  public void testDeleteStudent() throws Exception{
 StudentDao studentDao=cx.getBean(StudentDaoImpl.class);
 studentDao.deleteStudent(1);
  }
  //修改;
  //修改需要获得id;
  @Test
  public void testUpdateStudent() throws Exception{
 StudentDao studentDao=cx.getBean(StudentDaoImpl.class);
 Student student=new Student();
 student=studentDao.getStudentById(2);
 student.setPwd("12345678");
 studentDao.updateStudent(student);
  }
  //查询通过id;
  @Test
  public void testSelectStudent() throws Exception{
 StudentDao studentDao=cx.getBean(StudentDaoImpl.class);
 System.out.println(studentDao.getStudentById(2));
  }
  //查询所有;
  @Test
  public void testSelectAllStudent() throws Exception{
 StudentDao studentDao=cx.getBean(StudentDaoImpl.class);
 List<Student> students=studentDao.getStudents();
       for (Student student : students) {
          System.out.println(student);
      }     
 
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值