Spring教程
作者: 时海 hadoop迷
使用Spring自带DataSource

1、application.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value=" jdbc:mysql://localhost:3306/test"></property>
    </bean>

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

2、程序

package spring.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);
        jdbcTemplate.execute("create table user(id int primary key,name varchar(10),age int)");
        int returnCode = jdbcTemplate.update("insert into  user values(?,?,?)", new Object[]{1, "zhansan", 20});
        System.out.println(returnCode);
        //output: 1
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
        User user = jdbcTemplate.queryForObject("select * from user where id=?", rowMapper, new Object[]{1});
        System.out.println(user);
    }
}

POJO类:

package spring.example;

public class User {
    private Integer id;
    private String name;
    private Integer age;
    ...省略getter setter方法
 







一个创业中的苦逼程序员
  • 回复
隐藏