Spring集成JDBC

配置阿里巴巴提供的数据库连接类,让Spring帮忙管理

java 复制代码
<context:property-placeholder location="classpath:config.properties"></context:property-placeholder>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${driverClassName}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${uname}"></property>
        <property name="password" value="${upassword}"></property>
        <property name="initialSize" value="${initialSize}"></property><!--初始化连接数量-->
        <property name="maxActive" value="${maxActive}"></property><!--最大连接数量-->
        <property name="maxWait" value="${maxWait}"></property><!--最大等待超时时间-->
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

JdbcTemplate是Spring对jdbc的封装,提供了对数据库操作的方法,里面还可以直接包含数据源对象。

java 复制代码
@Data
@Repository
public class UserDao {
    @Autowired
    JdbcTemplate jdbcTemplate;
    Integer id;
    String name;

    public void select(){
        jdbcTemplate.update("insert into user(name)value (?)","aaa");
    }
}
java 复制代码
@Data
@Service("userService")
public class UserService {
    @Resource
    UserDao userDao;
    public void select(){
        userDao.select();
    }
}
java 复制代码
public class test {
    public static void main(String[] args) {
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");//读取配置文件
        UserService userService=applicationContext.getBean("userService",UserService.class);
        userService.select();
    }
}
相关推荐
小马过河R1 小时前
真实场景:用户自建定时任务与推送提醒Agent-架构设计与可靠性实践
数据库·人工智能·agent·vibe coding·ai coding
鹤落晴春2 小时前
【MySQL】 | 两阶段提交、主从复制
运维·数据库·mysql
SelectDB3 小时前
中小企业数据仓库怎么选?按数据规模、BI 并发和国产化要求分三档
数据库
SelectDB3 小时前
数据仓库一年要花多少钱?云数仓、自建 Doris 成本拆解与 TCO 计算指南
数据库
她的男孩3 小时前
Spring Boot 接 Flowable:请假单要同时走财务和行政,包容分支和默认分支怎么配
java·spring boot·工作流引擎
码少女4 小时前
MySQL——复杂查询
数据库·mysql
咖啡八杯4 小时前
LoginUser 适配器模式:适配 SysUser 到 UserDetails
java·开发语言·后端·框架·适配器模式·若依
北冥有鱼5 小时前
从 bean::method 里抠出注解:Java 方法引用元数据反查全记录
java·后端
CoderYanger5 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第四弹):@ControllerAdvice 源码分析+案例代码
java·数据库·spring boot·后端·spring·java-ee·mybatis
TDengine (老段)5 小时前
TDengine 读缓存与 LAST 查询完全指南
大数据·数据库·物联网·缓存·时序数据库·tdengine·涛思数据