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

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: 【一】简易的数据源配置(1)配置文件 jdbc:mysql://localhost:3306/mobile_thinks root shangxiaofei ...

【一】简易的数据源配置

(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

 

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
4天前
|
存储 前端开发 Java
Spring Boot 集成 MinIO 与 KKFile 实现文件预览功能
本文详细介绍如何在Spring Boot项目中集成MinIO对象存储系统与KKFileView文件预览工具,实现文件上传及在线预览功能。首先搭建MinIO服务器,并在Spring Boot中配置MinIO SDK进行文件管理;接着通过KKFileView提供文件预览服务,最终实现文档管理系统的高效文件处理能力。
|
5天前
|
缓存 Java Spring
手写Spring Ioc 循环依赖底层源码剖析
在Spring框架中,IoC(控制反转)是一个核心特性,它通过依赖注入(DI)实现了对象间的解耦。然而,在实际开发中,循环依赖是一个常见的问题。
15 4
|
11天前
|
XML 缓存 Java
spring源码剖析-spring-beans(内部核心组件,BeanDefinition的注册,BeanWapper创建)
spring源码剖析-spring-beans(内部核心组件,BeanDefinition的注册,BeanWapper创建)
39 10
|
11天前
|
XML 存储 Java
spring源码刨析-spring-beans(内部核心组件,beanDefinition加载过程)
spring源码刨析-spring-beans(内部核心组件,beanDefinition加载过程)
|
11天前
|
人工智能 开发框架 Java
重磅发布!AI 驱动的 Java 开发框架:Spring AI Alibaba
随着生成式 AI 的快速发展,基于 AI 开发框架构建 AI 应用的诉求迅速增长,涌现出了包括 LangChain、LlamaIndex 等开发框架,但大部分框架只提供了 Python 语言的实现。但这些开发框架对于国内习惯了 Spring 开发范式的 Java 开发者而言,并非十分友好和丝滑。因此,我们基于 Spring AI 发布并快速演进 Spring AI Alibaba,通过提供一种方便的 API 抽象,帮助 Java 开发者简化 AI 应用的开发。同时,提供了完整的开源配套,包括可观测、网关、消息队列、配置中心等。
554 6
|
9天前
|
XML 前端开发 Java
控制spring框架注解介绍
控制spring框架注解介绍
|
9天前
|
存储 NoSQL Java
Spring Session框架
Spring Session 是一个用于在分布式环境中管理会话的框架,旨在解决传统基于 Servlet 容器的会话管理在集群和云环境中的局限性。它通过将用户会话数据存储在外部介质(如数据库或 Redis)中,实现了会话数据的跨服务器共享,提高了应用的可扩展性和性能。Spring Session 提供了无缝集成 Spring 框架的 API,支持会话过期策略、并发控制等功能,使开发者能够轻松实现高可用的会话管理。
Spring Session框架
|
10天前
|
XML 存储 Java
Spring-源码深入分析(二)
Spring-源码深入分析(二)
|
10天前
|
XML 设计模式 Java
Spring-源码深入分析(一)
Spring-源码深入分析(一)
|
16天前
|
Java 应用服务中间件 开发者
深入探索并实践Spring Boot框架
深入探索并实践Spring Boot框架
27 2
下一篇
无影云桌面