spring Jdbc 支持
spring jdbc 实例 , 数据库:mysql
CREATE TABLE `customer` (
`CUST_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`NAME` varchar(100) NOT NULL,
`AGE` int(10) unsigned NOT NULL,
PRIMARY KEY (`CUST_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
实体类 : Customer.java
package com.cn.entity;
public class Customer {
int custId;
String name;
int age;
public Customer(int custId, String name, int age) {
this.age = age;
this.custId = custId;
this.name = name;
}
public Customer() {
// TODO 自動生成されたコンストラクター・スタブ
}
public int getCustId() {
return custId;
}
public void setCustId(int custId) {
this.custId = custId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Customer [custId=" + custId + ", name=" + name + ", age=" + age + "]";
}
}
service: CustomerDAO.java
当中的 jdbcTemplate 和 JdbcDaoSupport 是springJdbc api使用的测试。(简化DB连接和释放)
需要导入jar包:spring-tx-4.3.0.RELEASE.jar
package com.cn.services;
import java.util.List;
import com.cn.entity.Customer;
public interface CustomerDAO {
// 使用JdbcTemplate
public void insertUseJdbcTemplate(Customer customer);
// 使用JdbcDaoSupport
public List<Customer> findUseJdbcDaoSupport(int custId);
// insert
public void insert(Customer customer);
//find
public Customer findByCustomerId(int custId);
}
接口实现类:JdbcCustomerDAO.java
package com.cn.servicesImpl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import com.cn.entity.Customer;
import com.cn.services.CustomerDAO;
import com.cn.utils.MyRowMaps;
/**
*
* @author b1707007
*
* 使用 JdbcDaoSupport 需要jar包: spring-tx-4.3.0.RELEASE.jar
*
*/
public class JdbcCustomerDAO extends JdbcDaoSupport implements CustomerDAO {
@Autowired
private DataSource dataSource;
@Override
public void insertUseJdbcTemplate(Customer customer) {
String sql = "INSERT INTO CUSTOMER " + "(CUST_ID, NAME, AGE) VALUES (?, ?, ?)";
getJdbcTemplate().update(sql, new Object[] { customer.getCustId(),
customer.getName(),customer.getAge()});
}
@Override
public List<Customer> findUseJdbcDaoSupport(int custId) {
List<Customer> lCustomers = new ArrayList<>();
String sql = "SELECT * FROM CUSTOMER LIMIT ?";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
lCustomers = jdbcTemplate.query(sql, new MyRowMaps(), new Object[]{custId});
return lCustomers;
}
@Override
public void insert(Customer customer) {
String sql = "INSERT INTO CUSTOMER " + "(CUST_ID, NAME, AGE) VALUES (?, ?, ?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, customer.getCustId());
ps.setString(2, customer.getName());
ps.setInt(3, customer.getAge());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
@Override
public Customer findByCustomerId(int custId) {
String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = ?";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, custId);
Customer customer = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
customer = new Customer(rs.getInt("CUST_ID"), rs.getString("NAME"), rs.getInt("Age"));
}
rs.close();
ps.close();
return customer;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
public DataSource getDatasrc() {
return dataSource;
}
public void setDatasrc(DataSource datasrc) {
this.dataSource = datasrc;
}
}
配置文件:testIoC.xml
Jdbc相关配置:
<!-- 实体类 --!>
<bean id="Customer" class="com.cn.entity.Customer"/>
<!--
使用 JdbcDaoSupport.getJdbcTemplate 依赖 jdbcTemplate
--!>
<bean id="customerDAO" class="com.cn.servicesImpl.JdbcCustomerDAO">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
<!-- DBconf -->
<import resource="Spring-Datasource.xml" />
完整配置文件:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean
class ="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<!-- 使用p模式需要声明 xmlns:p="http://www.springframework.org/schema/p" -->
<bean id="user" class="com.cn.entity.User" p:userName="PuserName"/>
<bean id="Customer" class="com.cn.entity.Customer"/>
<bean id="UserManger" class="com.cn.entity.UserManger">
<property name="name" value="小花"></property>
</bean>
<!-- 未解决:@Qualifier 无效 -->
<!-- <bean id="UserMangerB" class="com.cn.entity.UserManger">
<property name="name" value="小花2"></property>
<property name="adress" value="adress2"></property>
</bean> -->
<bean id="customerDAO" class="com.cn.servicesImpl.JdbcCustomerDAO">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
<!-- DBconf -->
<import resource="Spring-Datasource.xml" />
</beans>
Spring-Datasource.xml
<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-2.5.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/home" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
</beans>
测试类:Test_Jdbc.java
package com.cn.test;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.cn.entity.Customer;
import com.cn.entity.User;
import com.cn.services.CustomerDAO;
public class Test_Jdbc {
@Test
public void testJdbc(){
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("testIoC.xml");
CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");
List<Customer> list = customerDAO.findUseJdbcDaoSupport(4);
for(Customer cus : list){
System.out.println(cus);
}
User user = (User)context.getBean("user");
System.out.println(user.getUserName());
}
}
DB中数据:
INSERT INTO `home`.`customer` (`CUST_ID`, `NAME`, `AGE`) VALUES ('1', 'tao', '29');
INSERT INTO `home`.`customer` (`CUST_ID`, `NAME`, `AGE`) VALUES ('2', 'tao', '29');
INSERT INTO `home`.`customer` (`CUST_ID`, `NAME`, `AGE`) VALUES ('3', 'tao', '29');
INSERT INTO `home`.`customer` (`CUST_ID`, `NAME`, `AGE`) VALUES ('4', 'tao', '29');
运行结果:
Customer [custId=1, name=tao, age=29]
Customer [custId=2, name=tao, age=29]
Customer [custId=3, name=tao, age=29]
Customer [custId=4, name=tao, age=29]
PuserName