【spring源码学习】spring集成orm数据框架

【一】简易的数据源配置

(1)配置文件

<!--springJdbcTemplemate数据操作配置信息 -->

    <bean id="driver" class="com.mysql.jdbc.Driver"></bean>

   <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
           <property name="url"><value>jdbc:mysql://localhost:3306/mobile_thinks</value></property>
           <property name="username"><value>root</value></property>
           <property name="password"><value>shangxiaofei</value></property>
           <property name="driver" ref="driver"/>
   </bean>
   <bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
           <property name="dataSource" ref="dataSource"/>
   </bean>

View Code

(2)测试类

package com.mobile.thinks.service.impl;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.mobile.thinks.entity.User;
import com.mobile.thinks.service.UserInfoService;

@Service(value="userInfoServiceImpl")
public class UserInfoServiceImpl implements UserInfoService{

    @Autowired
    private JdbcTemplate JdbcTemplate;

    @Override
    public User createUserAcountByUser(String userId) {
        //sql
        String sql="select * from thinks_user where id='"+userId+"'";

        //转换器
        RowMapper<User> rowMapper=new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User user=new User();
                user.setId(rs.getString("id"));
                user.setUserName(rs.getString("user_name"));
                user.setPassword(rs.getString("password"));
                user.setName(rs.getString("name"));
                user.setAddress(rs.getString("address"));
                user.setAge(rs.getInt("age"));
                user.setCreateTime(rs.getDate("create_time"));
                user.setUpdateTime(rs.getDate("update_time"));
                return user;
            }

        };

        //查询
        List<User> users= JdbcTemplate.query(sql,rowMapper);
        User user=users.get(0);

        //创建记录
        String insertSql="INSERT INTO thinks_user_acount(id, acount_name, acount_type, amount, user_id, age, create_time, update_time)VALUES('12344567890poiuytrewq', '"+user.getName()+"的账户', '人民币',"+new BigDecimal(88888888)+",'"+user.getId()+"', 28, now(), now());";

        JdbcTemplate.execute(insertSql);
        return user;
    }

}

View Code

 【二】JNDI方式配置在tomcat数据源,使用com.alibaba.druid连接池

(1)将数据库数据源用到的jdbc的jar包和数据库连接池的jar包copy到tomcat解压包的lib目录下

(2)在tomcat的conf目录下的context.xml配置文件中添加jndi数据源的配置

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context>

<Resource
    name="jdbc/thinkDS"
    auth="Container"
    type="javax.sql.DataSource"
    factory="com.alibaba.druid.pool.DruidDataSourceFactory"
    maxActive="10"
    minIdle="1"
    initialSize="1"
    maxWait="10000"
    username="root"
    password="shangxiaofei"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/mobile_thinks"
     />

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->
</Context>

View Code

(3)在项目的xml配置文件里引用jndi的配置

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
        xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="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.xsd
              http://www.springframework.org/schema/aop
              http://www.springframework.org/schema/aop/spring-aop.xsd
              http://www.springframework.org/schema/task
              http://www.springframework.org/schema/task/spring-task.xsd
              http://www.springframework.org/schema/data/jpa
           http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

   <!-- <context:property-placeholder location="classpath:resources.properties"/> -->

    <!-- 扫描注解Bean -->
    <context:component-scan base-package="com.mobile.thinks.**">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
        <context:include-filter type="annotation" expression="org.springframework.beans.factory.annotation.Autowired"/>
    </context:component-scan>

    <!--springJdbcTemplemate数据操作配置信息 -->
    <bean id="driver" class="com.mysql.jdbc.Driver"></bean>
   <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
           <property name="url"><value>jdbc:mysql://localhost:3306/mobile_thinks</value></property>
           <property name="username"><value>root</value></property>
           <property name="password"><value>shangxiaofei</value></property>
           <property name="driver" ref="driver"/>
   </bean>
   <bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
           <property name="dataSource" ref="dataSource"/>
   </bean>

   <!-- spring集成jndi数据源配置 -->
   <bean id="jndiDataSources" class="org.springframework.jndi.JndiObjectFactoryBean">
           <property name="jndiName">
            <value>java:comp/env/jdbc/thinkDS</value>
        </property>
   </bean>

    <bean id="jndiJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
           <property name="dataSource" ref="jndiDataSources"/>
   </bean>

   <!-- springHibernate继承 -->

</beans>

View Code

(4)项目中使用jndi数据源

@Service(value="userInfoServiceImpl")
public class UserInfoServiceImpl implements UserInfoService{

    @Autowired
    private JdbcTemplate JdbcTemplate;

    @Resource(name="jndiJdbcTemplate")
    private JdbcTemplate jndiJdbcTemplate;
    @Override
    public User findUserById(String userId) {
        //sql
        String sql="select * from thinks_user where id='"+userId+"'";

        //转换器
        RowMapper<User> rowMapper=new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                        User user=new User();
                        user.setId(rs.getString("id"));
                        user.setUserName(rs.getString("user_name"));
                        user.setPassword(rs.getString("password"));
                        user.setName(rs.getString("name"));
                        user.setAddress(rs.getString("address"));
                        user.setAge(rs.getInt("age"));
                        user.setCreateTime(rs.getDate("create_time"));
                        user.setUpdateTime(rs.getDate("update_time"));
                        return user;
            }

        };

        //查询
        List<User> users= jndiJdbcTemplate.query(sql,rowMapper);
        User user=users.get(0);
        return user;
    }
}

View Code

 

时间: 2024-09-20 05:46:48

【spring源码学习】spring集成orm数据框架的相关文章

spring源码系列(一)sring源码编译 spring源码下载 spring源码阅读

想对spring框架进行深入的学习一下,看看源代码,提升和沉淀下自己,工欲善其事必先利其器,还是先搭建环境吧. 环境搭建 sping源码之前是svn管理,现在已经迁移到了github中了,新版本基于gradle构建项目.所以构建sping源码环境必须先安装github以及Gradle. 当然了如果不想安装github客户端可以直接去git下载项目:spring中git地址https://github.com/spring-projects/spring-framework 安装github 首先

Spring源码学习之:FactoryBean的使用

转载:http://book.51cto.com/art/201311/419081.htm ==========个人理解========================= FactoryBean和BeanFactory的关系[1]FactoryBean:是一个接口,是一个用户自定义实现类实现该接口的A类.当ioc容器初始化完成后.BeanFactory(ioc容器)调用getBean("beanname")的时候,返回的bean不是A类对应的实例,而是A类getObject()方法返

spring源码学习之:spring容器的applicationContext启动过程

 Spring 容器像一台构造精妙的机器,我们通过配置文件向机器传达控制信息,机器就能够按照设定的模式进行工作.如果我们将Spring容器比喻为一辆汽车,可以将 BeanFactory看成汽车的发动机,而ApplicationContext则是 整辆汽车,它不但包括发动机,还包括离合器.变速器以及底盘.车身.电气设备等其他组件.在ApplicationContext内,各个组件按部就班. 有条不紊地完成汽车的各项功能. ApplicationContext内部封装 了一个BeanFactory对

【spring源码学习】spring的事务管理的源码解析

[一]spring事务管理(1)spring的事务管理,是基于aop动态代理实现的.对目标对象生成代理对象,加入事务管理的核心拦截器==>org.springframework.transaction.interceptor.TransactionInterceptor.===>spring事务管理的核心拦截器===>需要配置的数据项:事务管理机制配置属性的查找类transactionAttributeSource,事务管理的核心处理器PlatformTransactionManager

【spring源码学习】spring配置的事务方式是REQUIRED,但业务层抛出TransactionRequiredException异常问题

(1)spring抛出异常的点:org.springframework.orm.jpa.EntityManagerFactoryUtils public static DataAccessException convertJpaAccessExceptionIfPossible(RuntimeException ex) { // Following the JPA specification, a persistence provider can also // throw these two

spring源码学习之:xml标签扩展配置例子

在很多情况下,我们需要为系统提供可配置化支持,简单的做法可以直接基于Spring的标准Bean来配置,但配置较为复杂或者需要更多丰富控制的 时候,会显得非常笨拙.一般的做法会用原生态的方式去解析定义好的xml文件,然后转化为配置对象,这种方式当然可以解决所有问题,但实现起来比较繁琐, 特别是是在配置非常复杂的时候,解析工作是一个不得不考虑的负担.Spring提供了可扩展Schema的支持,这是一个不错的折中方案,完成一个自定义 配置一般需要以下步骤: 设计配置属性和JavaBean 编写XSD文

【spring源码学习】springMVC之映射,拦截器解析,请求数据注入解析,DispatcherServlet执行过程

[一]springMVC之url和bean映射原理和源码解析 映射基本过程 (1)springMVC配置映射,需要在xml配置文件中配置<mvc:annotation-driven >  </mvc:annotation-driven> (2)配置后,该配置将会交由org.springframework.web.servlet.config.MvcNamespaceHandler处理,该类会转交给org.springframework.web.servlet.config.Anno

【spring源码学习】spring的远程调用实现源码分析

[一]spring的远程调用提供的基础类 (1)org.springframework.remoting.support.RemotingSupport ===>spring提供实现的远程调用客户端实现的基础类 ===>例子:org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean org.springframework.remoting.caucho.HessianProxyFactoryBean (2)org.

【spring源码学习】spring的AOP面向切面编程的实现解析

一:Advice(通知)(1)定义在连接点做什么,为切面增强提供织入接口.在spring aop中主要描述围绕方法调用而注入的切面行为.(2)spring定义了几个时刻织入增强行为的接口  =>org.springframework.aop.BeforeAdvice   org.springframework.aop.MethodBeforeAdvice  =>org.springframework.aop.AfterAdvice   org.springframework.aop.After