关闭

Spring 整合hibernate

标签: Spring整合Hibernate
313人阅读 评论(0) 收藏 举报
分类:
1、首先导入包
1springIOC
2)数据库驱动
3c3p0连接池
4hibernate核心包(10个)
5spring整合orm
2、然后创建实体类
package star.july.entity;
public class Student {
          private int id;
          private String name;
          private String gender;
          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;
          }
          public String getGender() {
                   return gender;
          }
          public void setGender(String gender) {
                   this.gender = gender;
          }
          @Override
          public String toString() {
                   return "Student [id=" + id + ", name=" + name + ", gender=" + gender
                                      + "]";
          }
          
}
3、编写对象的关系映射文件:Student.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
          <class name="star.july.entity.Student" table="t_student">
                   <id name="id">
                             <generator class="native"></generator>
                   </id>
                   <property name="name" column="sname"></property>
                   <property name="gender"></property>
          </class>
</hibernate-mapping>
4、创建dao
package star.july.dao;
import java.util.List;
import star.july.entity.Student;
public interface IStudentDao {
    public List<Student> queryAll();
    public Student findById(int id);
    public int findCount();
    //查询分页
    public List<Student> fingByPages(int curPage,int pageSize);
    //模糊查询
    public List<Student> query(String name);
}

StudentDaoImpl.java
package star.july.dao;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.HibernateTemplate;
import star.july.entity.Student;
public class StudentDaoImpl implements IStudentDao {
    //接收HibernateTemplate对象:用于完成hibernate的操作
    private HibernateTemplate hibernateTemplate;
    
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }
    //查找全部学生
    @Override
    public List<Student> queryAll() {
        return hibernateTemplate.loadAll(Student.class);
    }
    //添加学生
    public void save(Student s){
        hibernateTemplate.save(s);
    }
    @Override
    public Student findById(int id) {
        return hibernateTemplate.get(Student.class, id);
    }
    //查询分页
    public List<Student> fingByPages(final int curPage,final int pageSize){
        return hibernateTemplate.execute(new HibernateCallback<List<Student>>(){
            @Override
            public List<Student> doInHibernate(Session session)
                    throws HibernateException {
                Query query = session.createQuery("from Student");
                query.setFirstResult((curPage-1)*pageSize);
                query.setMaxResults(pageSize);
                return query.list();
            }
        });
    }
    //查找总数量
    @Override
    public int findCount() {
        return hibernateTemplate.execute(new HibernateCallback<Long>() {
            @Override
            public Long doInHibernate(Session session) throws HibernateException {
                Query query = session.createQuery("select count(s) from Student s");
                return (Long) query.uniqueResult();
            }
        }).intValue();
    }
    
    //模糊查询
    public List<Student> query(String name){
        return (List<Student>)hibernateTemplate.find("select s from Student s where name like ?", "%"+name+"%");
    }
}

5、配置applicationContext.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
          <context:property-placeholder location="classpath:db.properties"/>
          
          <!--  1、创建连接池对象 -->
          <bean id="dataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                   <!-- 注入参数 -->
                   <property name="jdbcUrl" value="${jdbcUrl}"></property>
                   <property name="driverClass" value="${driverClass}"></property>
                   <property name="user" value="${user}"></property>
                   <property name="password" value="${password}"></property>
          </bean>
          
          <!-- 2、创建SessionFactory(spring改造后的LocalSessionFactoryBean) -->
          <bean id="sessionFactoryID" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
                   <!-- 注入连接池 -->
                   <property name="dataSource" ref="dataSourceID"></property>
                   <!-- 注入hibernate环境配置:方言,是否显示sql,是否维护表 -->
                   <property name="hibernateProperties">
                             <props>
                                      <prop
                                                key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                                                <prop key="hibernate.show_sql">true</prop>
                                                <prop key="hibernate.hbm2ddl.auto">update</prop>
                             </props>
                   </property>
                   <!-- 注入映射文件的路径 -->
                   <property name="mappingLocations">
                             <array>
                                       <value>classpath:star/july/entity/Student.hbm.xml</value>
                             </array>
                   </property>
          </bean>
          
          <!-- 3、创建HibernateTemplate对象 -->
          <bean id="hibernateTemplateID"
          class="org.springframework.orm.hibernate4.HibernateTemplate">
                   <!-- 注入SessionFactory对象 -->
                   <property name="sessionFactory" ref="sessionFactoryID"/>
          </bean>
          
          <!-- 创建dao对象 -->
          <bean id="studentDaoID" class="star.july.dao.StudentDaoImpl">
                   <!-- 注入HibernateTemplate对象 -->
                   <property name="hibernateTemplate" ref="hibernateTemplateID"></property>
          </bean>
       
</beans>


properties文件:db.properties
jdbcUrl=jdbc:mysql://localhost:3306/day36
driverClass=com.mysql.jdbc.Driver
user=root
password=root


6、测试
package star.july.test;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import star.july.dao.IStudentDao;
import star.july.entity.Student;
public class Demo {
          public static void main(String[] args) {
                   ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext.xml");
               IStudentDao stuDao = (IStudentDao)ac.getBean("studentDaoID");
               System.out.println(stuDao.queryAll());
          }
          
          //根据id查找学生
          @Test
          public void test(){
                   ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext.xml");
               IStudentDao stuDao = (IStudentDao)ac.getBean("studentDaoID");
               Student s = stuDao.findById(2);
               System.out.println(s);
          }
          
          //分页查找
          @Test
          public void test2(){
                   ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext.xml");
                   IStudentDao stuDao = (IStudentDao)ac.getBean("studentDaoID");
                   List<Student> list = stuDao.fingByPages(2, 2);
                   for(Student s : list){
                             System.out.println(s);
                   }
          }
          
          //查找总数
          @Test
          public void test3(){
                   ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext.xml");
                   IStudentDao stuDao = (IStudentDao)ac.getBean("studentDaoID");
                   int count = stuDao.findCount();
                   System.out.println(count);
          }
          
          //模糊查询
          @Test
          public void test4(){
                   ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext.xml");
                   IStudentDao stuDao = (IStudentDao)ac.getBean("studentDaoID");
                   List<Student> list = stuDao.query("莫");
                   for(Student s : list){
                             System.out.println(s);
                   }
          }
}
1、首先导入包
1springIOC
graphic
2)数据库驱动
graphic
3c3p0连接池
graphic
4hibernate核心包(10个)
graphic
5spring整合orm
graphic
2、然后创建实体类
package star.july.entity;
public class Student {
          private int id;
          private String name;
          private String gender;
          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;
          }
          public String getGender() {
                   return gender;
          }
          public void setGender(String gender) {
                   this.gender = gender;
          }
          @Override
          public String toString() {
                   return "Student [id=" + id + ", name=" + name + ", gender=" + gender
                                      + "]";
          }
          
}
3、编写对象的关系映射文件:Student.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
          <class name="star.july.entity.Student" table="t_student">
                   <id name="id">
                             <generator class="native"></generator>
                   </id>
                   <property name="name" column="sname"></property>
                   <property name="gender"></property>
          </class>
</hibernate-mapping>
4、创建dao
package star.july.dao;
import java.util.List;
import star.july.entity.Student;
public interface IStudentDao {
    public List<Student> queryAll();
    public Student findById(int id);
    public int findCount();
    //查询分页
    public List<Student> fingByPages(int curPage,int pageSize);
    //模糊查询
    public List<Student> query(String name);
}

StudentDaoImpl.java
package star.july.dao;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.HibernateTemplate;
import star.july.entity.Student;
public class StudentDaoImpl implements IStudentDao {
    //接收HibernateTemplate对象:用于完成hibernate的操作
    private HibernateTemplate hibernateTemplate;
    
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }
    //查找全部学生
    @Override
    public List<Student> queryAll() {
        return hibernateTemplate.loadAll(Student.class);
    }
    //添加学生
    public void save(Student s){
        hibernateTemplate.save(s);
    }
    @Override
    public Student findById(int id) {
        return hibernateTemplate.get(Student.class, id);
    }
    //查询分页
    public List<Student> fingByPages(final int curPage,final int pageSize){
        return hibernateTemplate.execute(new HibernateCallback<List<Student>>(){
            @Override
            public List<Student> doInHibernate(Session session)
                    throws HibernateException {
                Query query = session.createQuery("from Student");
                query.setFirstResult((curPage-1)*pageSize);
                query.setMaxResults(pageSize);
                return query.list();
            }
        });
    }
    //查找总数量
    @Override
    public int findCount() {
        return hibernateTemplate.execute(new HibernateCallback<Long>() {
            @Override
            public Long doInHibernate(Session session) throws HibernateException {
                Query query = session.createQuery("select count(s) from Student s");
                return (Long) query.uniqueResult();
            }
        }).intValue();
    }
    
    //模糊查询
    public List<Student> query(String name){
        return (List<Student>)hibernateTemplate.find("select s from Student s where name like ?", "%"+name+"%");
    }
}

5、配置applicationContext.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
          <context:property-placeholder location="classpath:db.properties"/>
          
          <!--  1、创建连接池对象 -->
          <bean id="dataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                   <!-- 注入参数 -->
                   <property name="jdbcUrl" value="${jdbcUrl}"></property>
                   <property name="driverClass" value="${driverClass}"></property>
                   <property name="user" value="${user}"></property>
                   <property name="password" value="${password}"></property>
          </bean>
          
          <!-- 2、创建SessionFactory(spring改造后的LocalSessionFactoryBean) -->
          <bean id="sessionFactoryID" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
                   <!-- 注入连接池 -->
                   <property name="dataSource" ref="dataSourceID"></property>
                   <!-- 注入hibernate环境配置:方言,是否显示sql,是否维护表 -->
                   <property name="hibernateProperties">
                             <props>
                                      <prop
                                                key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                                                <prop key="hibernate.show_sql">true</prop>
                                                <prop key="hibernate.hbm2ddl.auto">update</prop>
                             </props>
                   </property>
                   <!-- 注入映射文件的路径 -->
                   <property name="mappingLocations">
                             <array>
                                       <value>classpath:star/july/entity/Student.hbm.xml</value>
                             </array>
                   </property>
          </bean>
          
          <!-- 3、创建HibernateTemplate对象 -->
          <bean id="hibernateTemplateID"
          class="org.springframework.orm.hibernate4.HibernateTemplate">
                   <!-- 注入SessionFactory对象 -->
                   <property name="sessionFactory" ref="sessionFactoryID"/>
          </bean>
          
          <!-- 创建dao对象 -->
          <bean id="studentDaoID" class="star.july.dao.StudentDaoImpl">
                   <!-- 注入HibernateTemplate对象 -->
                   <property name="hibernateTemplate" ref="hibernateTemplateID"></property>
          </bean>
       
</beans>


properties文件:db.properties
jdbcUrl=jdbc:mysql://localhost:3306/day36
driverClass=com.mysql.jdbc.Driver
user=root
password=root


6、测试
package star.july.test;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import star.july.dao.IStudentDao;
import star.july.entity.Student;
public class Demo {
          public static void main(String[] args) {
                   ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext.xml");
               IStudentDao stuDao = (IStudentDao)ac.getBean("studentDaoID");
               System.out.println(stuDao.queryAll());
          }
          
          //根据id查找学生
          @Test
          public void test(){
                   ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext.xml");
               IStudentDao stuDao = (IStudentDao)ac.getBean("studentDaoID");
               Student s = stuDao.findById(2);
               System.out.println(s);
          }
          
          //分页查找
          @Test
          public void test2(){
                   ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext.xml");
                   IStudentDao stuDao = (IStudentDao)ac.getBean("studentDaoID");
                   List<Student> list = stuDao.fingByPages(2, 2);
                   for(Student s : list){
                             System.out.println(s);
                   }
          }
          
          //查找总数
          @Test
          public void test3(){
                   ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext.xml");
                   IStudentDao stuDao = (IStudentDao)ac.getBean("studentDaoID");
                   int count = stuDao.findCount();
                   System.out.println(count);
          }
          
          //模糊查询
          @Test
          public void test4(){
                   ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext.xml");
                   IStudentDao stuDao = (IStudentDao)ac.getBean("studentDaoID");
                   List<Student> list = stuDao.query("莫");
                   for(Student s : list){
                             System.out.println(s);
                   }
          }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:69776次
    • 积分:1931
    • 等级:
    • 排名:千里之外
    • 原创:120篇
    • 转载:1篇
    • 译文:0篇
    • 评论:27条
    文章分类
    最新评论