zoukankan      html  css  js  c++  java
  • 笔记58 Spring+Hibernate整合(一)

    Spring+Hibernate整合

    一、整合思路

      使DAO继承HibernateTemplate这个类 HibernateTemplate这个类提供了setSessionFactory()方法用于注入SessionFactory 通过spring获取DAO的时候,注入SessionFactory.

    二、编写基本POJO

    Category.java

     1 package com.pojo;
     2 
     3 public class Category {
     4     private int id;
     5     private String name;
     6 
     7     public int getId() {
     8         return id;
     9     }
    10 
    11     public void setId(int id) {
    12         this.id = id;
    13     }
    14 
    15     public String getName() {
    16         return name;
    17     }
    18 
    19     public void setName(String name) {
    20         this.name = name;
    21     }
    22 
    23     public String toString() {
    24         return "Category [id=" + id + ", name=" + name + "]";
    25     }
    26 }

    三、Hibernate映射

    在POJO的包下,创建hibernate映射文件Category.hbm.xml

     1 <?xml version="1.0"?>
     2  
     3 <!DOCTYPE hibernate-mapping PUBLIC
     4         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     5         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     6 <hibernate-mapping package="com.pojo">
     7     <class name="Category" table="category">
     8         <!-- <cache usage="read-only"/> -->
     9         <id name="id" column="id">
    10             <generator class="native">
    11             </generator>
    12         </id>
    13         <property name="name" />
    14     </class>
    15 
    16 </hibernate-mapping>

    四、DAO层

    DAO继承HibernateTemplete,而HibernateTemplete类里有一个setSessionFactory用于接收sessionFactory的注入。

    1 package com.DAO;
    2 
    3 import org.springframework.orm.hibernate3.HibernateTemplate;
    4 
    5 public class CategoryDAO extends HibernateTemplate {
    6 
    7 }

    五、Service层

    主要是对数据库的抽插。。。。。。

    CategoryService.java

     1 package com.Service;
     2 
     3 import java.util.List;
     4 
     5 import com.pojo.Category;
     6 
     7 public interface CategoryService {
     8     // 1.增加
     9     public void saveCategory(Category category);
    10 
    11     // 2.根据id查询单个条目
    12     public Category getSingleCategory(int id);
    13 
    14     // 3.查询所有条目
    15     public List<Category> getAllCategories();
    16 
    17     // 4.修改
    18     public void updateCategory(Category category);
    19 
    20     // 5.删除
    21     public void deleteCategory(Category category);
    22 
    23     // 6.分页查询
    24     public List<Category> getCategoryByPaging(int start, int count);
    25 
    26     // 7.获取条目总数
    27     public Long getSum();
    28 
    29     // 8.模糊查询
    30     public List<Category> getCategories(String field, String param);
    31 
    32 }

    CategoryServiceImpl.java

     1 package com.Service;
     2 
     3 import java.util.List;
     4 
     5 import org.hibernate.criterion.DetachedCriteria;
     6 import org.hibernate.criterion.Restrictions;
     7 
     8 import com.DAO.CategoryDAO;
     9 import com.pojo.Category;
    10 
    11 public class CategoryServiceImpl implements CategoryService {
    12 
    13     private CategoryDAO categoryDao;
    14 
    15     public CategoryServiceImpl(CategoryDAO categoryDao) {
    16         // TODO Auto-generated constructor stub
    17         this.categoryDao = categoryDao;
    18     }
    19 
    20     @Override
    21     public void saveCategory(Category category) {
    22         // TODO Auto-generated method stub
    23         categoryDao.save(category);
    24     }
    25 
    26     @Override
    27     public Category getSingleCategory(int id) {
    28         // TODO Auto-generated method stub
    29         Category category = categoryDao.get(Category.class, id);
    30         return category;
    31     }
    32 
    33     @Override
    34     public List<Category> getAllCategories() {
    35         // TODO Auto-generated method stub
    36         String queryString = "from Category c";
    37         @SuppressWarnings("unchecked")
    38         List<Category> categories = categoryDao.find(queryString);
    39         return categories;
    40     }
    41 
    42     @Override
    43     public void updateCategory(Category category) {
    44         // TODO Auto-generated method stub
    45         categoryDao.update(category);
    46     }
    47 
    48     @Override
    49     public void deleteCategory(Category category) {
    50         // TODO Auto-generated method stub
    51         categoryDao.delete(category);
    52     }
    53 
    54     @Override
    55     public List<Category> getCategoryByPaging(int start, int count) {
    56         // TODO Auto-generated method stub
    57         DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Category.class);
    58         @SuppressWarnings("unchecked")
    59         List<Category> categories = categoryDao.findByCriteria(detachedCriteria, start, count);
    60         return categories;
    61     }
    62 
    63     @Override
    64     public Long getSum() {
    65         // TODO Auto-generated method stub
    66         String queryString = "select count(*) from Category";
    67         @SuppressWarnings("unchecked")
    68         List<Long> longs = categoryDao.find(queryString);
    69         return longs.get(0);
    70     }
    71 
    72     @Override
    73     public List<Category> getCategories(String field, String param) {
    74         // TODO Auto-generated method stub
    75         DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Category.class);
    76         detachedCriteria.add(Restrictions.like(field, param));
    77         @SuppressWarnings("unchecked")
    78         List<Category> categories = categoryDao.findByCriteria(detachedCriteria);
    79         return categories;
    80     }
    81 
    82 }

    五、配置Spring

    创建DAO的时候,会注入sessionfactory
    创建sessionFactory的时候会注入数据源dataSource

    创建CategoryService的时候会注入DAO

    applicationContext.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
     4     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
     5     xsi:schemaLocation="
     6    http://www.springframework.org/schema/beans
     7    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     8    http://www.springframework.org/schema/aop
     9    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    10    http://www.springframework.org/schema/tx
    11    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    12    http://www.springframework.org/schema/context     
    13    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    14 
    15     <!-- 基础bean -->
    16     <bean name="Category" class="com.pojo.Category">
    17     </bean>
    18 
    19     <bean name="DAO" class="com.DAO.CategoryDAO">
    20         <property name="sessionFactory" ref="sessionFactory"></property>
    21     </bean>
    22 
    23     <bean name="CategoryService" class="com.Service.CategoryServiceImpl">
    24         <constructor-arg ref="DAO"></constructor-arg>
    25     </bean>
    26 
    27     <!-- 加载hibernate的sessionFactory -->
    28     <bean name="sessionFactory"
    29         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    30         <property name="dataSource" ref="dataSource">
    31         </property>
    32 
    33         <property name="mappingResources">
    34             <list>
    35                 <value>com/pojo/Category.hbm.xml</value>
    36             </list>
    37         </property>
    38 
    39         <property name="hibernateProperties">
    40             <value>
    41                 hibernate.dialect=org.hibernate.dialect.MySQLDialect
    42                 hibernate.show_sql=true
    43                 hbm2ddl.auto=update
    44             </value>
    45         </property>
    46     </bean>
    47     <!-- 配置数据源 -->
    48     <bean name="dataSource"
    49         class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    50         <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    51         <property name="url"
    52             value="jdbc:mysql://localhost:3306/sh?characterEncoding=UTF-8"></property>
    53         <property name="username" value="root"></property>
    54         <property name="password" value="123456"></property>
    55     </bean>
    56 </beans>

    六、测试CRUD

    Test.java

     1 package com.test;
     2 
     3 import java.util.List;
     4 
     5 import javax.sql.DataSource;
     6 
     7 import org.springframework.context.ApplicationContext;
     8 import org.springframework.context.support.ClassPathXmlApplicationContext;
     9 
    10 import com.Service.CategoryService;
    11 import com.pojo.Category;
    12 
    13 public class Test {
    14     private ApplicationContext context;
    15     private CategoryService categoryService;
    16 
    17     {
    18         context = new ClassPathXmlApplicationContext("applicationContext.xml");
    19         categoryService = context.getBean(CategoryService.class);
    20     }
    21 
    22     @org.junit.Test
    23     public void test() {
    24         // 测试数据源
    25         DataSource dataSource = (DataSource) context.getBean(DataSource.class);
    26         System.out.println(dataSource);
    27     }
    28 
    29     @org.junit.Test
    30     public void test1() {
    31         // 查询所有条目
    32         List<Category> categories = categoryService.getAllCategories();
    33         for (Category category : categories) {
    34             System.out.println(category);
    35         }
    36     }
    37 
    38     @org.junit.Test
    39     public void test2() {
    40         // 根据Id查询
    41         System.out.println(categoryService.getSingleCategory(1));
    42     }
    43 
    44     @org.junit.Test
    45     public void test3() {
    46         // 增加一条记录
    47         Category category = new Category();
    48         category.setName("新增的Category");
    49         categoryService.saveCategory(category);
    50     }
    51 
    52     @org.junit.Test
    53     public void test4() {
    54         // 删除一条记录
    55         Category category = categoryService.getSingleCategory(3);
    56         categoryService.deleteCategory(category);
    57     }
    58 
    59     @org.junit.Test
    60     public void test5() {
    61         // 分页查询
    62         List<Category> categories = categoryService.getCategoryByPaging(2, 3);
    63         for (Category category : categories) {
    64             System.out.println(category);
    65         }
    66     }
    67 
    68     @org.junit.Test
    69     public void test6() {
    70         // 模糊查询
    71         List<Category> categories = categoryService.getCategories("name", "%1%");
    72         for (Category category : categories) {
    73             System.out.println(category);
    74         }
    75     }
    76 
    77 }

    补充知识

    一、HibernateTemplate

      HibernateTemplate是spring对hibernate使用的一个简单封装,本例中获取的方式通过DAO直接继承HibernateTemplate,也可以通过HibernateTemplate hibernateTemplate=HibernateTemplate()获取,总之获取方法很多。

    二、HibernateTemplate常用的方法

    1、find(String queryString);  

    示例:hibernateTemplate.find("from bean.User");        

    返回所有User对象  

    2、find(String queryString , Object value);  

    示例:hibernateTemplate.find("from bean.User u where u.name=?", "test");  

    或模糊查询:hibernateTemplate.find("from bean.User u where u.name like ?", "%test%");  

    返回name属性值为test的对象(模糊查询,返回name属性值包含test的对象)

    3、find(String queryString, Object[] values);   

    示例:String hql= "from bean.User u where u.name=? and u.password=?";                 

         hibernateTemplate.find(hql, new String[]{"test", "123"});  

    返回用户名为test并且密码为123的所有User对象

    4、findByExample(Object exampleEntity)

    示例:User u=new  User();      

         u.setPassword("123" );

         u.setName("bb" );      //必须符合的条件但是这两个条件时并列的(象当于sql中的and)                        

             list=hibernateTemplate.findByExample(u);    

    返回:用户名为bb密码为123的对象

    5、findByExample(Object exampleEntity, int firstResult, int  maxResults)

    示例:User u=new  User();      

         u.setPassword("123" );

            u.setName("bb" );      //必须 符合的条件但是这两个条件时并列的(象当于sql中的and)

         list=hibernateTemplate.findByExample(u,start,max);      

    返回:满足用户名为bb密码为123,自start起共max个User对象。(对象从0开始计数)

    6、findByNamedParam(String queryString , String paramName , Object value)  

    示例:String queryString = "select count(*) from bean.User u where u.name=:myName" ;  

       String paramName= "myName";

       String value= "abc";  

       list=hibernateTemplate.findByNamedParam(queryString, paramName, value);

       System.out.println(list.get(0 ));        

    返回:name为abc的User对象的条数

    7、 findByNamedParam(String queryString , String[] paramName , Object[] value)        

    示例:String queryString = "select count(*) from bean.User u where u.name=:myName and u.password=:myPassword";

       String[] paramName= new String[]{"myName", "myPassword"};

       String[] value= new String[]{"abc", "123"};  

       hibernateTemplate.findByNamedParam(queryString, paramName, value); 

    返回:用户名为abc密码为123的User对象

    三、hibernatetemplate使用总结 

    1、固定条件查询 

    可以使用常规的方法,如 Java代码 

    hibernateTemplate.find(),hibernateTemplate.createQuery()等   

    hibernateTemplate.find(),hibernateTemplate.createQuery()等

    2、动态多条件查询 

    由于查询条件的不确定性,使用参数拼接。

    *hibernate模板

     

     1 public void save(User u) {
     2         Session s=null;
     3         try {
     4             s=sessionFactory.getCurrentSession();
     5             s.beginTransaction();
     6             s.save(u);
     7             s.getTransaction().commit();
     8         } catch (Exception e) {
     9             e.printStackTrace();
    10             s.getTransaction().rollback();
    11         }finally{
    12             if(s!=null){
    13                 s.close();
    14                 s=null;
    15             }
    16         }
    17         System.out.println("add success!!");        
    18     }

     

  • 相关阅读:
    JAVA JDK配置
    jsoncpp的使用
    VS2015 +Qt5 串口工具
    Unable to convert MySQL date/time value to System.DateTime问题解决方案
    datagridview的一些设置
    C# 如何使用长度来切分字符串
    (备忘)打开office2010总是在配置进度
    (备忘)卸载微软自带输入法
    (备忘)怎么去除WinRAR弹窗广告?
    winfrom弹出窗口用timer控件控制倒计时20秒后关闭
  • 原文地址:https://www.cnblogs.com/lyj-gyq/p/9253691.html
Copyright © 2011-2022 走看看