(转载别人的,用于学习和日后查看)
Spring对数据库操作都依赖数据源。
Spring有默认的数据源实现org.springframework.jdbc.datasource.DriverManagerDataSource,但也可以配置其他的数据源实现,比如DBCP的数据源public class BasicDataSource implements javax.sql.DataSource。
一旦获取到数据源DataSource实例,就可以通过DataSource获取到数据库连接,操作数据库。
下面是Spring数据源的一个简单配置和应用。
应用环境:MySQL5
drop
table
if
exists
user;
/*==============================================================*/
/* Table: user */
/*==============================================================*/
create table user
(
id bigint AUTO_INCREMENT not null,
name varchar(24),
age int,
primary key (id)
);
/*==============================================================*/
/* Table: user */
/*==============================================================*/
create table user
(
id bigint AUTO_INCREMENT not null,
name varchar(24),
age int,
primary key (id)
);
public
class User {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
public
interface IUserDAO {
public void insert(User user);
public User find(Integer id);
}
public void insert(User user);
public User find(Integer id);
}
/**
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-4-22 11:40:18<br>
* <b>Note</b>: 子类DAO
*/
public class UserDAO extends BaseDAO implements IUserDAO {
public void insert(User user) {
String name = user.getName();
int age = user.getAge().intValue();
Connection conn = null;
Statement stmt = null;
try {
conn = getConnection();
stmt = conn.createStatement();
stmt.execute( "INSERT INTO user (name,age) " + "VALUES('" + name + "'," + age + ")");
} catch (SQLException e) {
e.printStackTrace();
}
finally {
if (stmt != null) {
try {
stmt.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public User find(Integer id) {
Connection conn = null;
Statement stmt = null;
try {
conn = getConnection();
stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(
"SELECT * FROM user WHERE id=" + id.intValue());
if (result.next()) {
Integer i = new Integer(result.getInt(1));
String name = result.getString(2);
Integer age = new Integer(result.getInt(3));
User user = new User();
user.setId(i);
user.setName(name);
user.setAge(age);
return user;
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
if (stmt != null) {
try {
stmt.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
return null;
}
}
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-4-22 11:40:18<br>
* <b>Note</b>: 子类DAO
*/
public class UserDAO extends BaseDAO implements IUserDAO {
public void insert(User user) {
String name = user.getName();
int age = user.getAge().intValue();
Connection conn = null;
Statement stmt = null;
try {
conn = getConnection();
stmt = conn.createStatement();
stmt.execute( "INSERT INTO user (name,age) " + "VALUES('" + name + "'," + age + ")");
} catch (SQLException e) {
e.printStackTrace();
}
finally {
if (stmt != null) {
try {
stmt.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public User find(Integer id) {
Connection conn = null;
Statement stmt = null;
try {
conn = getConnection();
stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(
"SELECT * FROM user WHERE id=" + id.intValue());
if (result.next()) {
Integer i = new Integer(result.getInt(1));
String name = result.getString(2);
Integer age = new Integer(result.getInt(3));
User user = new User();
user.setId(i);
user.setName(name);
user.setAge(age);
return user;
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
if (stmt != null) {
try {
stmt.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
return null;
}
}
/**
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-4-22 13:53:56<br>
* <b>Note</b>: 基类DAO,提供了数据源注入
*/
public class BaseDAO {
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Connection getConnection() {
Connection conn = null;
try {
conn = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-4-22 13:53:56<br>
* <b>Note</b>: 基类DAO,提供了数据源注入
*/
public class BaseDAO {
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Connection getConnection() {
Connection conn = null;
try {
conn = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
<?
xml
version
="1.0"
encoding
="UTF-8"
?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
< beans >
< bean id ="dataSource"
class ="org.springframework.jdbc.datasource.DriverManagerDataSource" >
< property name ="driverClassName" >
< value >com.mysql.jdbc.Driver </ value >
</ property >
< property name ="url" >
< value >jdbc:mysql://localhost:3306/springdb </ value >
</ property >
< property name ="username" >
< value >root </ value >
</ property >
< property name ="password" >
< value >leizhimin </ value >
</ property >
</ bean >
< bean id ="baseDAO" class ="com.lavasoft.springnote.ch05_jdbc02.BaseDAO" abstract ="true" >
< property name ="dataSource" >
< ref bean ="dataSource" />
</ property >
</ bean >
< bean id ="userDAO"
class ="com.lavasoft.springnote.ch05_jdbc02.UserDAO" parent ="baseDAO" >
</ bean >
</ beans >
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
< beans >
< bean id ="dataSource"
class ="org.springframework.jdbc.datasource.DriverManagerDataSource" >
< property name ="driverClassName" >
< value >com.mysql.jdbc.Driver </ value >
</ property >
< property name ="url" >
< value >jdbc:mysql://localhost:3306/springdb </ value >
</ property >
< property name ="username" >
< value >root </ value >
</ property >
< property name ="password" >
< value >leizhimin </ value >
</ property >
</ bean >
< bean id ="baseDAO" class ="com.lavasoft.springnote.ch05_jdbc02.BaseDAO" abstract ="true" >
< property name ="dataSource" >
< ref bean ="dataSource" />
</ property >
</ bean >
< bean id ="userDAO"
class ="com.lavasoft.springnote.ch05_jdbc02.UserDAO" parent ="baseDAO" >
</ bean >
</ beans >
/**
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-4-22 11:41:34<br>
* <b>Note</b>: 客户端测试
*/
public class SpringDAODemo {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext( "D:\\_spring\\src\\com\\lavasoft\\springnote\\ch05_jdbc02\\bean-jdbc.xml");
User user = new User();
user.setName( "caterpillar");
user.setAge( new Integer(30));
IUserDAO userDAO = (IUserDAO) context.getBean( "userDAO");
userDAO.insert(user);
user = userDAO.find( new Integer(1));
System.out.println( "name: " + user.getName());
}
}
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-4-22 11:41:34<br>
* <b>Note</b>: 客户端测试
*/
public class SpringDAODemo {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext( "D:\\_spring\\src\\com\\lavasoft\\springnote\\ch05_jdbc02\\bean-jdbc.xml");
User user = new User();
user.setName( "caterpillar");
user.setAge( new Integer(30));
IUserDAO userDAO = (IUserDAO) context.getBean( "userDAO");
userDAO.insert(user);
user = userDAO.find( new Integer(1));
System.out.println( "name: " + user.getName());
}
}
运行结果:
log4j:WARN No appenders could be found for logger (org.springframework.core.CollectionFactory).
log4j:WARN Please initialize the log4j system properly.
name: jdbctemplate
Process finished with exit code 0
log4j:WARN Please initialize the log4j system properly.
name: jdbctemplate
Process finished with exit code 0
注意:Spring配置文件中对继承的配置,DataSource注入方式,通过继承来注入,从而简化编程。
上面用的是Spring的自己的数据源实现,现在假如要换成apache的DBCP数据源,则配置改为如下即可:
<
bean
id
="dataSource"
class ="org.apache.commons.dbcp.BasicDataSource" singleton ="true" >
< property name ="driverClassName" >
< value >com.mysql.jdbc.Driver </ value >
</ property >
< property name ="url" >
< value >jdbc:mysql://localhost:3306/springdb </ value >
</ property >
< property name ="username" >
< value >root </ value >
</ property >
< property name ="password" >
< value >leizhimin </ value >
</ property >
</ bean >
class ="org.apache.commons.dbcp.BasicDataSource" singleton ="true" >
< property name ="driverClassName" >
< value >com.mysql.jdbc.Driver </ value >
</ property >
< property name ="url" >
< value >jdbc:mysql://localhost:3306/springdb </ value >
</ property >
< property name ="username" >
< value >root </ value >
</ property >
< property name ="password" >
< value >leizhimin </ value >
</ property >
</ bean >