spring+hibernate环境搭建

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring+hibernate环境搭建相关的知识,希望对你有一定的参考价值。


整体项目结构如图:

技术分享

技术分享

src各个包是按照springMVC建立包格式建立的,如下图:

技术分享

entity层的代码:有Book.java 和 Account.java

package com.elgin.spring.hibernate.entity;

public class Book {  
    
    private int id;  
    private String bookName;  
    private String isbn;  
    private float price;  
    private int stock;  
  
    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
    public String getBookName() {  
        return bookName;  
    }  
  
    public void setBookName(String bookName) {  
        this.bookName = bookName;  
    }  
  
    public String getIsbn() {  
        return isbn;  
    }  
  
    public void setIsbn(String isbn) {  
        this.isbn = isbn;  
    }  
  
    public float getPrice() {  
        return price;  
    }  
  
    public void setPrice(float price) {  
        this.price = price;  
    }  
  
    public int getStock() {  
        return stock;  
    }  
  
    public void setStock(int stock) {  
        this.stock = stock;  
    }  
      
}  



package com.elgin.spring.hibernate.entity;

public class Account {  
    
    private int id;  
    private String username;  
    private float balance;  
      
    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
    public String getUsername() {  
        return username;  
    }  
  
    public void setUsername(String username) {  
        this.username = username;  
    }  
  
    public float getBalance() {  
        return balance;  
    }  
  
    public void setBalance(float balance) {  
        this.balance = balance;  
    }  
          
}  

 

entity层的  

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2015-11-15 21:48:02 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.elgin.spring.hibernate.entity.Book" table="SH_BOOK">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="native" />
        </id>
        
        <property name="bookName" type="java.lang.String">
            <column name="BOOKNAME" />
        </property>
        
        <property name="isbn" type="java.lang.String">
            <column name="ISBN" />
        </property>
        
        <property name="price" type="float">
            <column name="PRICE" />
        </property>
        
        <property name="stock" type="int">
            <column name="STOCK" />
        </property>
        
    </class>
</hibernate-mapping>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2015-11-15 21:48:02 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.elgin.spring.hibernate.entity.Account" table="SH_ACCOUNT">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="native" />
        </id>
        
        <property name="username" type="java.lang.String">
            <column name="USERNAME" />
        </property>
        
        <property name="balance" type="float">
            <column name="BALANCE" />
        </property>
        
    </class>
</hibernate-mapping>

Dao层代码:BookShopDao.java

package com.elgin.spring.hibernate.dao;

import antlr.collections.List;

public interface BookShopDao {

    public Float findBookPriceByIsbn(float f);
}

DaoImpl层代码:BookShopDaoImpl.java

package com.elgin.spring.hibernate.dao.impl;


import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.elgin.spring.hibernate.dao.BookShopDao;
import com.elgin.spring.hibernate.entity.Account;
import com.elgin.spring.hibernate.entity.Book;
import com.elgin.spring.hibernate.exception.BalanceNotEnough;
import com.elgin.spring.hibernate.exception.BookStockNotEnoughException;

@Repository

public class BookShopDaoImpl implements BookShopDao {

    @Autowired

    private SessionFactory sessionFactory;

    public Session getSession() {

        return sessionFactory.getCurrentSession();

    }

    public Float findBookPriceByIsbn(float f) {
        String hql = "select  price from Book  where id=1";
        Query q = getSession().createQuery(hql);
        Book book=(Book) getSession().get(Book.class, 2);
        System.out.println("getSession获得的getBookName是:"+book.getBookName());
        return (Float) q.uniqueResult();
    }

}

 

service层代码:BookShopService.java

package com.elgin.spring.hibernate.service;

public interface BookShopService {

    public void purchase(float f);

}

serviceImpl层代码:BookShopServiceImpl.java

package com.elgin.spring.hibernate.service.impl;

import javax.sound.midi.MidiDevice.Info;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.elgin.spring.hibernate.dao.BookShopDao;
import com.elgin.spring.hibernate.service.BookShopService;

@Service

public class BookShopSeviceImpl implements BookShopService {

    @Autowired

    private BookShopDao bookShopDao;

    public void purchase(float f) {
        // TODO Auto-generated method stub
        bookShopDao.findBookPriceByIsbn(f);
    }

}

test类代码:SpringHibernateTest.java

package com.elgin.spring.hibernate.test;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.elgin.spring.hibernate.entity.Account;
import com.elgin.spring.hibernate.service.BookShopService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringHibernateTest {
    

    @Autowired
    private BookShopService bookShopService;

    @Test
    public void testPurchaseBook() {
        bookShopService.purchase(1f);
    }

}

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"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
   
   <!-- 配置注解自动扫描的包 -->
   <context:component-scan base-package="com.elgin.spring.hibernate"/> <!-- 表示 com.elgin.spring.hibernate包及其子包中,
         如果某个类上带有特定的注解@Component,@Repository,@Service,@Controller,就会将这个对象作为Bean注入进容器-->
   
   
   
   
   <!-- 配置数据源 -->
   <!-- 导入资源文件 -->
   <context:property-placeholder location="classpath:db.properties"/>
   
   <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <property name="user" value="${jdbc.user}"></property>
       <property name="password" value="${jdbc.password}"></property>
       <property name="driverClass" value="${jdbc.driverClass}"></property>
       <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
       
       <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
       <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
   </bean>
   
   <!-- 配置Hibernate的SessionFactory,通过spring提供的 LocalSessionFactoryBean配置-->
   <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
       <!-- 配置依赖的数据源属性 -->
       <property name="dataSource" ref="dataSource"></property>
       <!-- hibernate 配置文件的路径 -->
       <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
       <!-- 配置hibernate映射文件的路径,可以使用通配符 -->
       <property name="mappingLocations" value="classpath:com/elgin/spring/hibernate/entity/*.hbm.xml"></property>
   </bean>
   
   <!-- 配置 Spring 的声明式事物 -->
   <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
       <property name="sessionFactory" ref="sessionFactory"></property>
   </bean>
   
   <!-- 配置事物属性 ,需要事物管理器-->
   <tx:advice id="txAdvice" transaction-manager="transactionManager">
       <tx:attributes>
           <tx:method name="get*" read-only="true"/>
          <tx:method name="purchase" propagation="REQUIRES_NEW"/>
          <tx:method name="*"/>
       </tx:attributes>
   </tx:advice>
   
   <!-- 配置事物切点,并把事物属性和切点关联起来 -->
   <aop:config>
      <aop:pointcut expression="execution(* com.elgin.spring.hibernate.service.*.*(..))" id="txPointcut"/>
      <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
   </aop:config>
   
</beans>

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>
      <!-- 配置hibernate基本信息 -->
      <!-- 1.数据源配置在IOC容器中,此处不需要额外配置 -->
      <!-- 2.关联的.hbm.xml文件也在IOC容器配置SessionFactory时配置 -->
      <!-- 3.此处配置hibernate的基本信息:数据库方言、SQL显示及格式化,及生成数据表的策略,二级缓存等 -->
      <property name="hibernate.dialect">org.hibernate.dialect.mysql5InnoDBDialect</property>
      
      <property name="hibernate.show_sql">true</property>
      <property name="hibernate.format_sql">true</property>
      
      <property name="hibernate.hbm2ddl.auto">update</property>
      
    </session-factory>
</hibernate-configuration>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
  
      <!-- Spring MVC配置 -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>&nbsp; 默认
        </init-param>
        -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <!-- Spring配置 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:config/applicationContext.xml</param-value>
    </context-param>
</web-app>

基本配置已经搭建好


下面是项目运行的截图如下:

技术分享

 

技术分享

 

技术分享

技术分享

 

















以上是关于spring+hibernate环境搭建的主要内容,如果未能解决你的问题,请参考以下文章

Spring+Spring+Hibernate环境搭建

Spring+Springmvc+Hibernate环境搭建与配置

struts2+Hibernate4+spring3+EasyUI环境搭建之一

spring mvc4.1.6 + spring4.1.6 + hibernate4.3.11 + mysql5.5.25 开发环境搭建及相关说明

struts2.3.24 + spring4.1.6 + hibernate4.3.11 + mysql5.5.25开发环境搭建及相关说明

如何在CentOS上搭建 Struts2+Spring+Hibernate的运行环境