Spring,SpringMVC和hibernate整合小demo

来源:互联网 发布:c语言入门自学书 编辑:程序博客网 时间:2024/06/07 00:31

DeptController

@Controllerpublic class DeptController {    //植入service    @Resource    private IDeptService deptService;    @RequestMapping("/addDept")   public String add(Dept dept){         deptService.addDept(dept);         return "index";   }}

IDeptDAO

public interface IDeptDAO {    //添加部门的方法    public int addDept(Dept dept, Session session);}

DeptDAOImpl

public class DeptDAOImpl implements IDeptDAO{    public int addDept(Dept dept,Session session) {        Serializable count = session.save(dept);        return (Integer) count;    }}
Dept持久类

public class Dept {    private Integer deptno;    private String deptname;    public Integer getDeptno() {        return deptno;    }    public void setDeptno(Integer deptno) {        this.deptno = deptno;    }    public String getDeptname() {        return deptname;    }    public void setDeptname(String deptname) {        this.deptname = deptname;    }}
Dept.hbm.xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.happy.entity">    <class name="Dept" table="Dept">        <id name="deptno" column="deptno">            <generator class="native"></generator>        </id>        <property name="deptname" />    </class></hibernate-mapping>
IDeptService

public interface IDeptService {    public int addDept(Dept dept);}

DeptServiceImpl

public interface IDeptService {    public int addDept(Dept dept);}
HibernateUtil工具类
public class HibernateUtil {    private static ThreadLocal<Session> tl;    private static Configuration cfg;    private static SessionFactory factory;    static {        tl=new ThreadLocal<Session>();        cfg=new Configuration().configure();        factory=cfg.buildSessionFactory();    }    //获取和当前线程绑定的session    public static Session getSession(){        //尝试着从线程中看看有没有线程变量        Session session = tl.get();        if (session==null){            //线程中没有session对象,创建一个            session = factory.openSession();            tl.set(session);        }        return session; //没有和当前线程绑定    }    public static void closeSession(){        Session session = tl.get();        tl.set(null);        session.close();    }}
applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:context="http://www.springframework.org/schema/context"       xmlns:aop="http://www.springframework.org/schema/aop"       xmlns:tx="http://www.springframework.org/schema/tx"       xmlns:mvc="http://www.springframework.org/schema/mvc"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       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     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">    <!--包扫描器-->    <context:component-scan base-package="cn.happy.controller"/>    <!--mvc注解驱动-->    <mvc:annotation-driven></mvc:annotation-driven>    <!--视图解析器-->    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/jsp/"/>        <property name="suffix" value=".jsp"/>    </bean>    <!--数据源-->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="driverClass" value="${jdbc.driverClassName}"/>        <property name="user" value="${jdbc.username}"/>        <property name="password" value="${jdbc.password}"/>        <property name="jdbcUrl" value="${jdbc.url}"/>    </bean>    <context:property-placeholder location="classpath:jdbc.properties"/>    <!--2.SessionFactory         类:Local-->    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">        <property name="dataSource" ref="dataSource"></property>        <property name="hibernateProperties">            <props>                <!--hibernate.xxxxxx必须以hibernate-->                <prop key="hibernate.show_sql">true</prop>                <prop key="hibernate.format_sql">true</prop>                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>                <prop key="hibernate.hbm2ddl.auto">create</prop>                <!--with current thread bind session-->                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>            </props>        </property>        <property name="mappingDirectoryLocations" value="classpath:cn/happy/entity"></property>    </bean>    <!--dao-->    <bean id="deptDAO" class="cn.happy.dao.DeptDAOImpl"/>    <!--service-->    <bean id="deptService"  class="cn.happy.service.DeptServiceImpl">        <property name="sessionFactory" ref="sessionFactory"></property>        <property name="dao" ref="deptDAO"></property>    </bean>    <!--  5.事务管理器-->    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">        <property name="sessionFactory" ref="sessionFactory"></property>    </bean>    <!--6.事务-->    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven></beans>
jdbc.properties

jdbc.driverClassName=oracle.jdbc.OracleDriverjdbc.url=jdbc:oracle:thin:@localhost:1521:orcljdbc.username=wcjjdbc.password=cj663300
log4j.properties

zlog4j.rootLogger=info,Console,Rlog4j.appender.Console=org.apache.log4j.ConsoleAppenderlog4j.appender.Console.layout=org.apache.log4j.PatternLayout#log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p %c - %m%nlog4j.appender.Console.layout.ConversionPattern=%d{yy-MM-dd HH:mm:ss} %5p %c{1}:%L - %m%nlog4j.appender.R=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.R.File=${catalina.home}/logs/tomcat.loglog4j.appender.R.layout=org.apache.log4j.PatternLayoutlog4j.appender.R.layout.ConversionPattern=%d{yyyy.MM.dd HH:mm:ss} %5p %c{1}(%L):? %m%nlog4j.logger.org.apache=info,Rlog4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost]=DEBUG, Rlog4j.logger.org.apache.catalina.core=info,Rlog4j.logger.org.apache.catalina.session=info,R  
add.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>添加部门</title></head><body>   <form method="post" action="/addDept">      部门名称: <input name="deptname"/>       <input type="submit" value="添加"/>   </form></body></html>








原创粉丝点击