Spring2.5 + JPA (Hibernate3.2) 实例源码(CTO)

2 篇文章 0 订阅
1 篇文章 0 订阅

今天因闲来无事,研究了一下JPA,并做了一个简单小示例来供大家分享,首先我们来简要介绍下JPA,JPA是通过SUN JDK5.0的注解和XML用来描

述对象与关系表的映射,并将运行期间实体对象持久化到数据库中去。
先来谈下实体BEAN的规范,具有ORM元素数据的领域对象就叫做实体,它应具备如下四个条件:
一、必须使用 javax.persistence.Entity 注解或XML映射文件中有对应的<entity>元素
二、必须具有一个不带参数的构造函数,类不能声明为final,方法和需要持久化的属性也不能声明为final
三、如果流离状态的实体对象需要以值的方式进行传递(如通过Session bean的远程业务接口传递),则必须实现java.io.Serializable 接口
四、需要持久化的属性,访问修饰符不能是public,它必须通过实体类方法进行访问

下面简要介绍下spring2.0与 spring2.5 在 MVC模式上的改进
2.5 跟 2.0 的MVC实现模式以经完全不一样,2.5 主要是引入了注解驱动,控制器不用再继承任何类或实现任何接口(SimpleFormController

或 MultiActionController),也无需在spring配置文件中定义请求和控制器,2.5中的控制器,通过注解就可以让一个POJO具有控制器的功能,

同时增强了框架的易用性、灵活性、扩展性、并提高一定的开发效率

下面是一个用 spring2.5 + jpa 实现的一个简单小示例
首先在ECLIPSE中建立一个WEB Project,将所需要的类库全部拷入到工程的LIB目录,还有一点需要到

http://sourceforge.net/project/showfiles.php?group_id=40712&package_id=156160&release_id=405227
根据相应的平台下载 hibernate-entitymanager.jar包放入到LIB目录,否则会报java.lang.ClassNotFoundException:

org.hibernate.ejb.HibernatePersistence 异常
我把该过程分为五步来写:
一、在工程的src目建立一个META-INF 文件,在当中添加一个persistenct.xml 文件,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence

http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
 version="1.0">
 <!-- 持久化单元名为SPRING_JPA在spring配置文件中要对应起来,使用本地事务 -->
 <persistence-unit name="SPRING_JPA" transaction-type="RESOURCE_LOCAL">
  <!-- 声明JPA规范由hibernate实现持久化 -->
  <provider>org.hibernate.ejb.HibernatePersistence</provider>
  <properties>
   <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
   <property name="hibernate.max_fetch_depth" value="3"/>
   <property name="hibernate.hbm2ddl.auto" value="update"/>
  </properties>
 </persistence-unit>
</persistence>
二、配置spring配置文件,分为二个applicationContext.xml 和 springjpa-servlet.xml XML文件,applicationContext.xml 定义业务逻辑

相关的配置,springjpa-servlet.xml 定义 spring MVC 的相应配置,文件代码如下:
springjpa-servlet.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 <!-- 自动装载注入 -->
 <context:component-scan base-package="*"></context:component-scan>
  <!-- 启动springMVC的注解驱动 -->
     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
     <!-- 模型视图的解析 -->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:suffix=".jsp"></bean>
</beans>

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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.microsoft.jdbc.sqlserver.SQLServerDriver"></property>
  <property name="url" value="jdbc:microsoft:sqlserver://192.168.0.180:1433;databaseName=pubs"></property>
  <property name="username" value="holpe"></property>
  <property name="password" value="holpe20080801"></property>
 </bean>
 <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  <property name="dataSource" ref="dataSource"></property>
  <property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"></property>
  <!-- <property name="persistenceUnitName" value="vissul"></property> -->
  <property name="loadTimeWeaver">
   <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"></bean>
  </property>
 </bean>
 <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  <property name="entityManagerFactory" ref="entityManagerFactory"></property>
 </bean>
 <tx:annotation-driven transaction-manager="txManager"/>
 <!-- 自动装载注入 -->
 <context:component-scan base-package="*"/>
 <bean id="loginDao" class="com.spring25jpa.dao.impl.LoginDaoImpl"/>
 <bean id="loginService" class="com.spring25jpa.service.impl.LoginService"/>
</beans>

三、建立spring 控制器,业务层、数据层、和JPA注解域对象
首先控制器 LoginAction.java
package com.spring25jpa.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.spring25jpa.service.ILoginService;

/**
 * <p>
 * 创 建 人:ChenTao
 * <p>
 * 创建日期:2009-5-12 下午02:37:34
 * <p>
 *
 */
@Controller
public class LoginAction {

 @Autowired
 public ILoginService loginService;
 
 @RequestMapping("/login.do")
 public String login(String userName,String password,ModelMap model){
  boolean succeed = loginService.login(userName,password);
  if(succeed){
   model.addAttribute("userName", userName);
   return "success";
  }
  return "error";
 }
}

业务处理类 LoginService.java
package com.spring25jpa.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.spring25jpa.dao.ILoginDao;
import com.spring25jpa.service.ILoginService;

/**
 * <p>
 * 创 建 人:ChenTao
 * <p>
 * 创建日期:2009-5-12 下午02:43:28
 * <p>
 *
 */
public class LoginService implements ILoginService {

 @Autowired
 private ILoginDao loginDao;

 @Transactional
 public boolean login(String userName,String password) {
  return loginDao.login(userName,password);
 }
}

数据处理类 LoginDaoImpl.java
package com.spring25jpa.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.spring25jpa.dao.ILoginDao;

/**
 * <p>
 * 创 建 人:ChenTao
 * <p>
 * 创建日期:2009-5-12 下午02:44:57
 * <p>
 *
 */
public class LoginDaoImpl implements ILoginDao{

 @PersistenceContext
 private EntityManager em;
 
 public boolean login(String userName,String password) {
  Query query = em.createQuery("from Users where userName=:userName and password=:password");
  query.setParameter("userName", userName);
  query.setParameter("password", password);
  return query.getResultList().size() > 0 ? true : false;
 }

}

持久化对象并进行了JPA注解
package com.spring25jpa.po;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@SuppressWarnings("serial")
@Entity
@Table(name="users")
public class Users implements Serializable{

 @Id
 @GeneratedValue
 private Integer uid;

 @Column(name="username",nullable=true,length=20)
 private String userName;

 @Column(name="pwd",nullable=true,length=20)
 private String password;

 @Column(name="birthday")
 private Date birthday;

 public Users(){
 }
 get set ......
}

四、配置最重要的文件 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">
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext.xml</param-value>
 </context-param>
 <!-- spring 启动监听器 -->
 <listener>
  <listener-class>
   org.springframework.web.context.ContextLoaderListener
  </listener-class>
 </listener>
 <!-- 处理请求的 servlet,它将加载 WEB-INF/springjpa-servlet.xml下的配置文件,以启动springMVC模块 -->
 <servlet>
  <servlet-name>springjpa</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>springjpa</servlet-name>
  <url-pattern>*.do</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

接下来第五步就是编写JSP页面,JSP页面就不贴出来了,相信大家都知道怎样去写,好了这样一个简单的示例就算写完了,经过运行后完全正确,

这也是我写的第一个 spring2.5+jpa的示例,有不当之处还请多多谅解
需要源码可到此处下载: http://download.csdn.net/source/1301318

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值