Spring入门笔记--Spring MVC--JDBCTemplate

Spring MVC--JDBCTemplate

配置样例

application.xml

    <!--加载外部properties文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="databaseProp" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="databaseProp"/>
    </bean>

test.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateTest {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Test
    public void test() {
        jdbcTemplate.execute("insert into account (name, money) values ('TOM', 35)");
    }

    @Test
    public void test2() {
        List<Account> accounts = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
        System.out.println(accounts);
    }
    @Test
    public void test3() {
        Account account = jdbcTemplate.queryForObject("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class), "TOM");
        System.out.println(account);
    }
}

接口

@Nullable 
public <T> T queryForObject(     String sql,
    org.springframework.jdbc.core.RowMapper<T> rowMapper,
    @Nullable Object... args )

public <T> java.util.List<T> query(     String sql,
    org.springframework.jdbc.core.RowMapper<T> rowMapper )
posted @ 2022-07-13 23:32  Saski&Naruto  阅读(63)  评论(0)    收藏  举报