`
dev_liu
  • 浏览: 109833 次
  • 性别: Icon_minigender_1
  • 来自: 成都
最近访客 更多访客>>
社区版块
存档分类
最新评论

spring与数据持久层的集成(提供一个模版)

阅读更多

一、配置DataSource
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
 <property name="jndiName">
  <value>java:comp/env/jdbc/myDatasource</value>
 </property>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
  <property name="dataSource"><ref bean="dataSource"/></property>
  <property name="mappingResources">
    <list>
      <value>com/springinaction/training/model/Course.hbm.xml</value>
      <value>com/springinaction/training/model/User.hbm.xml</value>
    </list>
  </property>
  <property name="hibernateProperties">
    <props>
      <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    </props>
  </property>
</bean>

二、使用JdbcTemplate

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update(
  "UPDATE user SET age = ? WHERE id = ?",
  new PreparedStatementSetter() {
  public void setValues(PreparedStatementSetter ps)
  throws SQLException {
  ps.setInt(1, 18);
  ps.setString(2, "erica");
       }
  }
);

在Spring中使用方法:
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  <property name="dataSource"><ref bean="dataSource"/></property>
</bean>
<bean id="studentDao" class="StudentDaoJdbc">
  <property name="jdbcTemplate"><ref bean="jdbcTemplate"/></property>
</bean>

在DAO类中定义
public class StudentDaoJdbc implements StudentDao {
 private JdbcTemplate jdbcTemplate;
 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  this.jdbcTemplate = jdbcTemplate;
 }
 …
}

三、以Batch方式批量插入数据
public int[] updatePersons(final List persons) {
  String sql = "insert into person (id, firstName, lastName) " +"values (?, ?, ?)";
  BatchPreparedStatementSetter setter = null;
  setter = new BatchPreparedStatementSetter() {
   public int getBatchSize() {
    return persons.size();
   }
   public void setValues(PreparedStatement ps, int index)
    throws SQLException {
     Person person = (Person) persons.get(index);
     ps.setInt(0, person.getId().intValue());
     ps.setString(1, person.getFirstName());
     ps.setString(2, person.getLastName());
   }
  };
  return jdbcTemplate.batchUpdate(sql, setter);
}
四、Spring中查询数据
返回单条记录
public Person getPerson(final Integer id) {
 String sql = "select id, first_name, last_name from person " + "where id = ?";
 final Person person = new Person();
 final Object[] params = new Object[] { id };
 jdbcTemplate.query(sql, params, new RowCallbackHandler() {
   public void processRow(ResultSet rs) throws SQLException {
     person.setId(new Integer(rs.getInt("id")));
     person.setFirstName(rs.getString("first_name"));
     person.setLastName(rs.getString("last_name"));
   }
  });
 return person;
}
返回多条记录
class PersonRowMapper implements RowMapper {
 public Object mapRow(ResultSet rs, int index)
  throws SQLException {
   Person person = new Person();
   person.setId(new Integer(rs.getInt("id")));
   person.setFirstName(rs.getString("first_name"));
   person.setLastName(rs.getString("last_name"));
   return person;
 }
}

public List getAllPersons() {
 String sql = "select id, first_name, last_name from person";
 return jdbcTemplate.query(
  sql, new RowMapperResultReader(new PersonRowMapper()));
}

调用存储过程:
public void archiveStudentData() {
 CallableStatementCallback cb = new CallableStatementCallback() {
  public Object doInCallableStatement(CallableStatement cs)
   throws SQLException{
    cs.execute();
    return null;
   }
  };
 jdbcTemplate.execute("{ ARCHIVE_STUDENTS }", cb);
}

五、在Spring中集成Hibernate
配置文件:
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
 <property name="jndiName">
  <value>java:comp/env/jdbc/trainingDatasource</value>
 </property>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
  <property name="dataSource">
    <ref local="dataSource"/>
  </property>
  <property name="mappingResources">
    <list>
    <value>com/tongking/model/User.hbm.xml</value>
    </list>
  </property>
  <property name="hibernateProperties">
  <props>
   <prop key="hibernate.dialect">net.sf.hibernate.dialect.OracleDialect</prop>
   <prop key="hibernate.show_sql">true</prop>
   </props>
  </property>
</bean>

<bean id="hibernateTemplate"
 class="org.springframework.orm.hibernate.HibernateTemplate">
 <property name="sessionFactory">
 <ref bean="sessionFactory"/>
 </property>
</bean>

<bean id="studentDao" class="com.springinaction.training.dao.hibernate.StudentDaoHibernate">
 <property name="hibernateTemplate">
  <ref bean="hibernateTemplate"/>
 </property>
</bean>

代码:
public class UserDAOHibernate extends HibernateDaoSupport implements UserDAO {
  public List getUsers() {
   return getHibernateTemplate().find("from User");
  }
  public User getUser(Long id) {
   User user = (User) getHibernateTemplate().get(User.class, id);
   if (user == null) {
    throw new ObjectRetrievalFailureException(User.class, id);
   }
    return user;
  }
  public void saveUser(User user) {
   getHibernateTemplate().saveOrUpdate(user);
  }
  public void removeUser(Long id) {
   getHibernateTemplate().delete(getUser(id));
  }
}

三、在Spring中进行事务管理
 TransactionProxyFactoryBean consults a method’s transaction attributes to determine
how to administer transaction policies on that method

 The getTransactionAttribute() method is called to find the transaction
attributes for a particular method, given the target class and method.

<bean id="courseService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
 <property name="proxyInterfaces">
  <list>
   <value>
    com.springinaction.training.service.CourseService
   </value>
  </list>
 </property>

 <property name="target">
   <ref bean="courseServiceTarget"/>
 </property>
 <property name="transactionManager">
   <ref bean="transactionManager"/>
 </property>
 <property name="transactionAttributeSource">
   <ref bean="attributeSource"/>
 </property>
</bean>

<bean id="myTransactionAttribute" class="org.springframework.transaction.interceptor.DefaultTransactionAttribute">
 <property name="propagationBehaviorName">
  <value>PROPAGATION_REQUIRES_NEW</value>
 </property>
 <property name="isolationLevelName">
  <value>ISOLATION_REPEATABLE_READ</value>
 </property>
</bean>
<bean id="transactionAttributeSource" class="org.springframework.transaction.interceptor.MatchAlwaysTransactionAttributeSource">
 <property name="transactionAttribute">
  <ref bean="myTransactionAttribute"/>
 </property>
</bean>

CourseService course=context.getBean("courseService");

六、在Spring中访问DataSource
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" singleton="true">
 <property name="jndiName">
  <value>java:comp/env/jdbc/myDatasource</value>
 </property>
</bean>

七、在Spring中实现JavaMail服务
<bean id="mailSession" class="org.springframework.jndi.JndiObjectFactoryBean">
 <property name="jndiName">
  <value>java:comp/env/mail/Session</value>
 </property>
</bean>

<bean id="mailSender" class="org.springrframework.mail.javamail.JavaMailSenderImpl">
 <property name="session">
  <ref bean="mailSession"/>
 </property>
</bean>

实现代码:
public void sendCourseEnrollmentReport() {
  Set courseList = courseDao.findAll();
  SimpleMailMessage message = new SimpleMailMessage(this.mailMessage);
  
  StringBuffer messageText = new StringBuffer();//定义用于存入邮件内容
  messageText.append("Current enrollment data is as follows:\n\n");
  for(Iterator iter = courseList.iterator(); iter.hasNext(); ) {
    Course course = (Course) iter.next();
    messageText.append(course.getId() + " ");
    messageText.append(course.getName() + " ");
    int enrollment = courseDao.getEnrollment(course);
    messageText.append(enrollment);
  }//将从数据库中取得内容放至邮件中
  message.setText(messageText.toString());
  try {
   mailSender.send(message);//发送邮件
  } catch (MailException e) {
   LOGGER.error(e.getMessage());
  }
}

八、定时功能:
1.creating a job
public class EmailReportJob extends QuartzJobBean {
 public EmailReportJob() {}
 protected void executeInternal(JobExecutionContext context)
 throws JobExecutionException {
  courseService.sendCourseEnrollmentReport();
 }
 private CourseService courseService;
 public void setCourseService(CourseService courseService) {
  this.courseService = courseService;
 }
}
2.在配置文件中定义:
<bean id="reportJob"class="org.springframework.scheduling.quartz.JobDetailBean">
 <property name="jobClass">
   <value>com.springinaction.training.schedule.EmailReportJob</value>
 </property>
 <property name="jobDataAsMap">
  <map>
   <entry key="courseService">
    <ref bean="courseService"/>
   </entry>
  </map>
 </property>
</bean>
3.Scheduling the job
<bean id="simpleReportTrigger"class="org.springframework.scheduling.quartz.SimpleTriggerBean">
 <property name="jobDetail">
   <ref bean="reportJob"/>
 </property>
 <property name="startDelay">
   <value>3600000</value>
 </property>
 <property name="repeatInterval">
   <value>86400000</value>
 </property>
</bean>
以上方法不能用于具体的时间点定时功能,但下面的方法可以
<bean id="cronReportTrigger"class="org.springframework.scheduling.quartz.CronTriggerBean">
 <property name="jobDetail">
  <ref bean="reportJob"/>
 </property>
 <property name="cronExpression">
  <value>0 0 6 * * ?</value>
 </property>
</bean> //6:00 a.m. every day.

直接通过配置文件声明定时执行方法
<bean id="courseServiceInvokingJobDetail">
 class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
 <property name="targetObject">
   <ref bean="courseService"/>
 </property>
 <property name="targetMethod">
   <value>sendCourseEnrollmentReport</value>
 </property>
</bean>

九、在Spring中使用JMS
1、发送消息:
public void sendSettlementMessage(final PaySettlement settlement) {
  jmsTemplate.send(
  new MessageCreator() {
    public Message createMessage(Session session)
     throws JMSException {
       MapMessage message = session.createMapMessage();
       message.setString("authCode",
       settlement.getAuthCode());
       message.setString("customerName",
       settlement.getCustomerName());
       message.setString("creditCardNumber",
       settlement.getCreditCardNumber());
       message.setInt("expirationMonth",
       settlement.getExpirationMonth());
       message.setInt("expirationYear",
       settlement.getExpirationYear());
       return message;
     }
    }
  );
}

配置文件:
bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
 <property name="connectionFactory">
   <ref bean="jmsConnectionFactory"/>
 </property>
 <property name="defaultDestination">
   <ref bean="destination"/>
 </property>
</bean>

<bean id="jmsConnectionFactory"class="org.springframework.jndi.JndiObjectFactoryBean">
 <property name="jndiName">
   <value>connectionFactory</value>
 </property>
</bean>

<bean id="destination" class="org.springframework.jndi.JndiObjectFactoryBean">
 <property name="jndiName">
   <value>creditCardQueue</value>
 </property>
</bean>

2、消费消息
public PaySettlement processSettlementMessages() {
  Message msg = jmsTemplate.receive("creditCardQueue");
  try {
    MapMessage mapMessage = (MapMessage) msg;
    PaySettlement paySettlement = new PaySettlement();
    paySettlement.setAuthCode(mapMessage.getString("authCode"));
    paySettlement.setCreditCardNumber(
    mapMessage.getString("creditCardNumber"));
    paySettlement.setCustomerName(
    mapMessage.getString("customerName"));
    paySettlement.setExpirationMonth(
    mapMessage.getInt("expirationMonth"));
    paySettlement.setExpirationYear(
    mapMessage.getInt("expirationYear"));
    return paySettlement;
  } catch (JMSException e) {
   throw JmsUtils.convertJmsAccessException(e);
  }
}

配置文件:
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
 <property name="receiveTimeout">
  <value>10000</value>
 </property>
</bean>

分享到:
评论
2 楼 gougou8180 2007-06-05  
i agree with you
1 楼 dev_liu 2007-01-09  
看了是网页不支持xml?总之,我建议jms不用spring集成,因为在你需要简便的时候很简便,但是需要重新去连接或者是提供一些多线程消息处理的时候,你需要大量的使用反射,那就比较复杂了,所以简单的时候很简单,复杂的时候很复杂,感觉没必要用spring,当然这是我的个人意见,刚入门.只是参考.

相关推荐

    轻量级Java持久层框架MiniDAO:基于SpringJDBC与FreeMarker的源码实现

    项目名称:轻量级Java持久层框架MiniDAO...MiniDAO致力于简化数据访问层代码,通过FreeMarker模板提供灵活的SQL管理方式,同时继承了Spring JDBC的易用性和高效性,为Java开发者提供了一个简洁、高效的持久层解决方案。

    基于SpringJdbc和Freemarker的JAVA轻量级持久层框架设计源码

    本设计源码提供了一个基于SpringJdbc和Freemarker的JAVA轻量级持久层框架。项目包含158个文件,主要使用Java编程语言。文件类型包括72个Java源代码文件、64个Freemarker模板文件、5个XML配置文件、5个SQL文件、4个...

    spring4.1核心包

    相关介绍 1. spring-aop-4.1.1.RELEASE.jar ... 这就提供了(并且要求)在改变系统持久状态的活动和产生显示内容的活动之间 有一个清晰的分层。 20. spring-websocket-4.1.1.RELEASE.jar websocket消息架构

    Spring.3.x企业应用开发实战(完整版).part2

    Spring3.0是Spring在积蓄了3年之久后,隆重推出的一个重大升级版本,进一步加强了Spring作为Java领域第一开源平台的翘楚地位。  Spring3.0引入了众多Java开发者翘首以盼的新功能和新特性,如OXM、校验及格式化框架...

    Spring3.x企业应用开发实战(完整版) part1

    Spring3.0是Spring在积蓄了3年之久后,隆重推出的一个重大升级版本,进一步加强了Spring作为Java领域第一开源平台的翘楚地位。  Spring3.0引入了众多Java开发者翘首以盼的新功能和新特性,如OXM、校验及格式化框架...

    Spring-Reference_zh_CN(Spring中文参考手册)

    处理多个持久化单元 12.6.2. JpaTemplate 和 JpaDaoSupport 12.6.3. 基于原生的JPA实现DAO 12.6.4. 异常转化 12.6.5. 事务管理 12.6.6. JpaDialect III. Web 13. Web框架 13.1. 介绍 13.1.1. 与其他web框架的集成 ...

    Spring-generator一键生成数据库文件

    Spring-generator 不是框架,它不会影响现有的任何机构,它只是一个解决你重复做某些事情的工具,它也不拘束与某个语言,它的使命就是将数据库表结构取出来,剩下的就取决于你怎么使用 FreeMarker 编写模板生成你想...

    spring in action英文版

     1.6.4 持久层框架  1.7 小结  第2章 装配Bean  2.1 容纳你的Bean  2.1.1 BeanFactory介绍  2.1.2 使用应用上下文  2.1.3 Bean的生命  2.2 基本装配  2.2.1 使用XML装配  2.2.2 添加一...

    springboot_study-master.zip

    该部分以 Spring Boot 框架为主线,内容包括Json数据封装、日志记录、属性配置、MVC支持、在线文档、模板引擎、异常处理、AOP 处理、持久层集成等等。 进阶篇(11—17课)主要是介绍 Spring Boot 在项目中拔高一些...

    Spring in Action(第2版)中文版

    a.2把spring添加为一个maven2依赖项 a.3spring与ant a.4spring与log4j 附录b用(和不用)spring进行测试 b.1测试简介 b.1.1理解不同类型的测试 b.1.2使用junit b.1.3spring在测试中的角色 b.2单元测试...

    Spring in Action(第二版 中文高清版).part2

    第一部分 Spring的核心 第1章 开始Spring之旅 1.1 Spring是什么 1.2 开始Spring之旅 1.3 理解依赖注入 1.3.1 依赖注入 1.3.2 DI应用 1.3.3 企业级应用中的依赖注入 1.4 应用AOP 1.4.1 AOP介绍 1.4.2 AOP...

    Spring in Action(第二版 中文高清版).part1

    第一部分 Spring的核心 第1章 开始Spring之旅 1.1 Spring是什么 1.2 开始Spring之旅 1.3 理解依赖注入 1.3.1 依赖注入 1.3.2 DI应用 1.3.3 企业级应用中的依赖注入 1.4 应用AOP 1.4.1 AOP介绍 1.4.2 AOP...

    一个最简单的SSH框架

    service 为 action 提供统计的调用接口,封装持久层的 DAO. 2 .可以写一些自己的业务方法。 3 .统一的 javabean 管理方法 4 .声明式事务管理 5. 集成 Hiberante 3 ) Hiberante ,负责持久化层,完成数据库...

    cassandratemplate:Spring Mvc + Spring Data + Mysql + Cassandra Web 模板

    卡桑德拉模板Project 旨在用作 Web 项目模板,其中包括与 mysql 和 cassandra 的持久层集成。 还使用了 Spring 数据和 spring mvc。 Velocity 被选择并配置为模板引擎。 为了运行程序 cassandra.properties 和 mysql...

    源码基于JSP的OA办公自动化管理系统(Struts1.2+Hibernate3.0+Spring2+DWR).rar

    后端数据持久层由Hibernate3.0负责,它通过对象关系映射(ORM)简化了数据库的操作,并且提供了丰富的缓存机制和事务管理功能,有效提升了数据处理的效率和安全性。Spring2则贯穿于整个系统,以其依赖注入和面向切面...

    springboot夕阳红公寓管理系统的设计与实现.zip

    MyBatis:作为数据持久层框架,MyBatis与数据库交互,提供了简洁的SQL编写和映射机制。MySQL:作为后端数据库,存储所有公寓管理相关数据。Thymeleaf:作为前端模板引擎,Thymeleaf负责生成动态的HTML页面,提供给...

    demo:Spring启动演示项目

    persistence 持久层集成mybatis service 集成了dubbo,test目录下有dubbo消费者 Junit单元测试 service-api 接口 utils 工具类,简单封装了okhttp 3.0 web 使用的是spring推荐的模板引擎 thymeleaf ,优点是前后端...

    Spring-Generator

    工具默认集成了以MyBatis作为持久化层的模板,如果需要JPA相关等模板可以自己参考工具的文档进行编写 生成实体类 生成WEB API相关接口 Controller 生成业务逻辑相关的Service/ServiceImpl 生成操作数据库的Dao接口...

    springboot 整合 mybaitsplus

    SpringBoot集成MyBatisPlus 技术选型: 核心框架:Spring Boot 1.5.1 安全框架:Apache Shiro 视图框架:Spring MVC 持久层框架:MyBatis MyBatisPlus 缓存技术:EhCache,Redis 数据库连接池:Druid 日志管理:SLF4J...

    低清版 大型门户网站是这样炼成的.pdf

    4.1.1 持久化与持久层 191 4.1.2 jdbc劣势 192 4.1.3 实体域模型与关系数据模型 193 4.1.4 orm中间件 196 4.2 hibernate简介 196 4.2.1 hibernate体系结构 196 4.2.2 hibernate api简介 197 4.2.3 配置...

Global site tag (gtag.js) - Google Analytics