【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

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值