Open xiongxin opened 8 years ago
application.xml
<bean id="dataSource"
class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<context:property-placeholder location="config.properties" />
config.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/music
jdbc.username=root
jdbc.password=root
JdbcTemplateDao.java
package com.netease.context.jdbc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
/**
* Created by xiongxin on 16/3/21.
*/
@Repository
public class JdbcTemplateDao {
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void createTable() {
this.jdbcTemplate.execute("create table myuser (id integer, first_name varchar(100)" +
", last_name varchar(100))");
}
public void insertTable() {
this.jdbcTemplate.update("insert into myuser values (1, ?, ?)", "Han", "Mei Mei");
this.jdbcTemplate.update("insert into myuser values (1, ?, ?)", "Li", "Li Lei");
}
public int countTable() {
return this.jdbcTemplate.queryForObject("select count(*) from myuser", Integer.class);
}
public List<User> getUserList() {
return jdbcTemplate.query("select * from myuser", new RowMapper<User>() {
public User mapRow(ResultSet resultSet, int i) throws SQLException {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setFirst_name(resultSet.getString("first_name"));
user.setFirst_name(resultSet.getString("last_name"));
return user;
}
});
}
}
TestDao.java
package com.netease.context.jdbc;
import com.netease.context.ioc.ScrewDriver;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.SystemEnvironmentPropertySource;
/**
* Created by xiongxin on 16/3/21.
*/
public class TestDao {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("application-context.xml");
JdbcTemplateDao dao = context.getBean("jdbcTemplateDao", JdbcTemplateDao.class);
//dao.createTable();
//dao.insertTable();
System.out.println(dao.countTable());
}
}
数据库访问
DAO
ORM
数据库访问
DataSource(数据源)
Spring JdbcTemplate
定义JdbcTemplate
注入JdbcTemplate