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>

基本配置已经搭建好

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

时间: 2024-10-09 09:56:17

spring+hibernate环境搭建的相关文章

Struts2+Spring+Hibernate环境搭建

struts-2.3.20 spring-4.1.4 hibernate-4.3.8 slf4j-1.7.10 1.在MySQL中建立数据库 mysql> create database myoa default character set utf8 2.在MyEclipse中建立Web Project 在项目上右键-Properties,设置编码为UTF-8. 3.配置Struts2 拷贝jar包(依照示例,另aopalliance.jar). 在web.xml中写入Struts Filter

Spring+Spring+Hibernate环境搭建

一.引入lib包 pom.xml,引入需要的jar包 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://mav

Maven搭建struts2+spring+hibernate环境

Maven搭建struts2+spring+hibernate环境(一) 本文简单的使用STS的自带的maven插件工具搭建ssh(struts2+spring+hibernate)开发环境,图文并茂,简单上手,适合新手. 关于STS的介绍,请参考另一篇文章<Java IDE介绍:Spring开发利器-spring-tool-suite>地址:http://blog.csdn.net/sgl731524380/article/details/8831540 首先,STS自带的maven的插件已

SSH(Struts2+Spring+Hibernate)框架搭建流程&lt;注解的方式创建Bean&gt;

此篇讲的是MyEclipse9工具提供的支持搭建自加包有代码也是相同:用户登录与注册的例子,表字段只有name,password. SSH,xml方式搭建文章链接地址:http://www.cnblogs.com/wkrbky/p/5912810.html 一.Hibernate(数据层)的搭建: 实现流程 二.Spring(注入实例)的使用: 实现流程 三.Struts2(MVC)的搭建: 实现流程 这里注意一点问题: Struts2与Hibernate在一起搭建,antlr包,有冲突.MyE

Hibernate学习之——Hibernate环境搭建

之前在写关于安卓闹钟的教程,写了一半就没后一半了,其实自己也没做好,在校外实习,校内毕业实习又有任务,只能先放放了,等毕业实习结束之后,在继续安卓闹钟开发之旅,相信这个时间不会很久的.现在毕业实习用到的SSH框架(Struts+Spring+Hibernate),自己没有多少时间去好好学习,但是还是想把学到的东西记录下来. 一.Hibernate简介 1.什么是Hibernate? Hibernate是数据持久层的一个轻量级框架.数据持久层的框架有很多比如:iBATIS,myBatis,Nhib

spring MVC环境搭建

1.新建web项目,并在web.xml加入spring mvc的servlet <!-- spring mvc容器和servlet的定义 --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 这里的参数如果不

【原】Spring activiti 环境搭建之数据库创建

由于在开发工作流的时候,避免不了要保存一些数据和流程走向;所以在搭建Spring activiti开发环境的时候需要把官方提供的23张表创建到我们的DB,后续的流程都会在这些表中记录. 1.创建代码如下: @Test public void createactivityTable(){ ProcessEngineConfiguration p = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration(

Spring MVC 环境搭建

作为java领域不可或缺的一员猛将,今天我开始正式接触它.与所有框架一样,我们第一步要做的就是搭建环境. 首先我们需要准备的材料: Eclipse tomcat(我用的是7.0) spring mvc jar包(我用的是3.2的) 有了这些工具,下面我们开始吧! 1.新建一个项目 Eclipse新建 Dynamic Web project 选择相应的服务器容器(我用的是Tomcat7.0),一路下一步到完成. 2.引入jar包 SpringMVC使用的jar包基本和Spring是相同的,我们可以

hibernate环境搭建及配置文件

首先要下载好hibernate文件包 然后新建项目: 1.导入jar包(打开下载好的文件包,找到lib文件下的required文件包,里面有jar包) 注意:初学者可以暂时copy一下代码. 2.新建一个class文件,内容如下: public class Person { //类的属性 private Integer id; private String name; private String password; private Date birthday; //无参构造函数 public