Spring和Hibernate的注解整合 hibernate3和hibernate4/5的区别

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring和Hibernate的注解整合 hibernate3和hibernate4/5的区别相关的知识,希望对你有一定的参考价值。

现在,ssh框架中注解的使用已经非常普遍了,在此我介绍一下spring整合hibernate注解时的配置:

hibernate和spring的注解方式请网上搜索。

当你分别把spring和hibernate注解配好之后。打开spring的基础配置文件中的

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

的配置。

一、当你hibernate使用的是配置文件的时候,只需要在bean'重配置如下属性即可:(这种配置hibernate3/4/5是没有区别的)

二、当你hibernate使用的是注解的时候且hibernate3时候

将sessionFactory  的class改为  org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean

且将 mappingDirectoryLocations属性改为如下

三、当你hibernate使用的是注解的时候且hibernate4/5时候

只需要将mappingDirectoryLocations属性改为如下即可

参考技术A hibernate4.0版本和3.0版本的区别
1.数据库方言设置
<property name=”dialect”>org.hibernate.dialect.mysql5Dialect</property>
在3.3版本中连接MySQL数据库只需要指明MySQLDialect即可。在4.1版本中可以指出MySQL5Dialect
2.buildSessionFactory
4.1版本中buildSessionFactory()已经被buildSessionFactory(ServiceRegistry ServiceRegistry)取代
解决办法:
Configuration cfg = new Configuration();
ServiceRegistry serviceRegistry =new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sf= cfg.configure().buildSessionFactory(serviceRegistry);
3.annotation
org.hibernate.cfg.AnnotationConfiguration;
Deprecated. All functionality has been moved to Configuration
这个注解读取配置的class已经废弃,现在读取配置不需要特别注明是注解,直接用Configuration cfg = new Configuration();就可以读取注解。
Hibernate4.1版本中推荐使用annotation配置,所以在引进jar包时把requested里面的包全部引进来就已经包含了annotation必须包了
4.Hibernate4.1已经可以自动建表,所以开发时只需要自己开发类然后配置好就OK。不需要考虑怎么建表

ssh全注解整合

使用注解的方式,配置文件最少可以精简到三个,web.xml、applicationContext.xml和struts.xml。Hibernate可以完全交给Spring来管理,这样连hibernate.cfg.xml也省了。下面就一起看看这些基本的配置吧!

 

web.xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--Spring配置
1.上下文 识别applicationContext.xml

2.监听器 在Tomcat容器启动的时候,帮我创建Spring容器,并且放入application中-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!--Struts2配置 核心过滤器 -->
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>

  

 

web.xml中包含了Spring和struts的基本配置,自动扫描Action的配置就是告诉tomcat,我要使用注解来配置struts。

 

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.baby"></context:component-scan>


<!--
1.数据源 c3p0
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>

<!--
2.识别到jdbc.properties
-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--
3.形成SessionFactory
-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<!--方言-->
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<!--自动建表-->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!--是否打印sql-->
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>
</props>
</property>
<!--关联小配置-->
<property name="packagesToScan" value="cn.baby.entity"></property>
</bean>

<!--
7.事务管理器
-->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--
8.事务真实配置
-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

  User实体

package com.tgb.ssh.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;


@Entity(name="t_user")
public class User {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;
	private String name;
	private String password;	
	 
	
	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 getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

  dao层实现一个增加的方法

package com.tgb.ssh.dao;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.tgb.ssh.model.User;

@Repository
public class UserDao {
	@Resource(name="sessionFactory") 
	private SessionFactory sessionFactory;
	
	public void addUser(User user ) {
		Session session = sessionFactory.getCurrentSession();
		session.save(user);
	}

}

  service层

package com.tgb.ssh.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tgb.ssh.dao.UserDao;
import com.tgb.ssh.model.User;

@Service
@Transactional
public class UserManager {
	@Resource
	UserDao userDao;
	
	public void addUser(User user) {
		userDao.addUser(user);
	}
	
}

  action层

UserAction通过注解配置Action的名字和返回的页面,通过@Resource活动Spring注入的UserManager对象,然后进行相应的操作。Action里还有@Namespace、@InterceptorRef等很多注解可以用,根据自己需要选择吧。

package com.tgb.ssh.action;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.opensymphony.xwork2.ActionSupport;
import com.tgb.ssh.model.User;
import com.tgb.ssh.service.UserManager;


@Results( { @Result(name="success",location="/success.jsp"),
        @Result(name="failure",location="/failure.jsp") }) 
public class UserAction extends ActionSupport {
    @Resource
    private UserManager userManager;
    private User user;
    
    @Action(value="addUser")
    public String addUser() {
        try {
            userManager.addUser(user);        
        } catch (Exception e) {
            e.printStackTrace();
            return "failure";
        }
        return "success";
        
    }    

    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    
    
}

  页面jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>添加用户</title>
  </head>
  
  <body>
      <form method="post" action="addUser">
        用户名:<input type="text" name="user.name"><br>
        密码:<input type="password" name="user.password"><br>        
        <input type="submit" value="登录"/>
    </form>    
  </body>
</html>

  

以上是关于Spring和Hibernate的注解整合 hibernate3和hibernate4/5的区别的主要内容,如果未能解决你的问题,请参考以下文章

SSH整合步骤之注解和非注解

ssh2项目整合 struts2.1+hibernate3.3+spring3 基于hibernate注解和struts2注解

SSH(Spring+Struts2+hibernate)整合基于注解开发的详解

Spring框架学习spring整合hibernate

Java框架:spring框架整合hibernate框架的xml配置(使用注解的方式)

Spring整合Hibernate的两种方式