Spring 對JDBC技術規範作了進一步封裝,它又叫Spring JDBCTemplate(jdbc模板技術)java
純JDBC:代碼清晰的、效率最高、代碼是最煩的、
Spring JDBCTemplate:代碼相對來講就不那麼清晰,效率要低一點,代碼相對簡單mysql
如何進行Spring和jdbc的集合?(數據庫的鏈接池)
(1) 導入jar 包:spring-jdbc.jar 驅動類 鏈接池 DruidUtil2(框架的原型)
(2) 配置類:@Configuration
(3) @Spring IOC + JDBC 實現
JdbcConfig: a.配置屬性 b.配置DataSource Bean
(4) 配置JdbcTemplate Bean @Beanspring
1.pom.xml 所須要的jar包sql
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!-- MySQL數據庫鏈接池 --> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.48</version> </dependency> <!-- Druid --> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.20</version> </dependency>
2. 一個實體類:Account.java數據庫
public class Account { private int id; private String name; private Double balance; public Account( String name, Double balance) { super(); this.name = name; this.balance = balance; } public Account(int id, String name, Double balance) { super(); this.id = id; this.name = name; this.balance = balance; } public Account() { super(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getBalance() { return balance; } public void setBalance(Double balance) { this.balance = balance; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((balance == null) ? 0 : balance.hashCode()); result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Account other = (Account) obj; if (balance == null) { if (other.balance != null) return false; } else if (!balance.equals(other.balance)) return false; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Account [id=" + id + ", name=" + name + ", balance=" + balance + "]"; } }
3. 接口:IAccount.javaapp
import java.util.List; /** * AccountDao接口 * @author 張澤 */ public interface IAccountDao { List<Account> findAll(); void delete(Account act); void saveOrUpdate(Account act); }
4.1 接口實現類(JDBC):AccountDaoJdbcImpl.java框架
import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; //@Component @Repository("accountDaoJdbcImpl") //-- 存儲、倉庫/ 作存儲服務 public class AccountDaoJdbcImpl implements IAccountDao { @Autowired private DataSource ds; @Override public List<Account> findAll() { try { Connection con = ds.getConnection(); String sql = "select * from account"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); List<Account> acts = new ArrayList<>(); while(rs.next()) { Account act = new Account(rs.getInt(1),rs.getString(2),rs.getDouble(3)); acts.add(act); } return acts; } catch (Exception e) {e.printStackTrace();} return null; } @Override public void delete(Account act) { // TODO Auto-generated method stub } @Override public void saveOrUpdate(Account act) { // TODO Auto-generated method stub } }
4.2 接口實現類(Spring JDBCTemplate):AccountDaoTemplateImpl.javaide
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository("accountDaoTemplateImpl") public class AccountDaoTemplateImpl implements IAccountDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public List<Account> findAll() { System.out.println("accountDaoTemplateImpl"); return jdbcTemplate.query( "select * from account", new BeanPropertyRowMapper<Account>(Account.class) ); } @Override public void saveOrUpdate(Account act) { if(act.getId()==0) { jdbcTemplate.update( "insert into account(name,balance) values(?,?)", new Object[] {act.getName(),act.getBalance()} ); }else { jdbcTemplate.update( "update account set name=?,balance=? where id=?", new Object[] {act.getName(),act.getBalance(),act.getId()} ); } } @Override public void delete(Account act) { jdbcTemplate.update( "delete from account where id=?", new Object[] {act.getId()} ); } }
5.1 JDBC 配置資源:jdbc.properties函數
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo
jdbc.username=root
jdbc.password=root
pool.maxActive=10
5.2 JDBC 配置類:JdbcConfig.java測試
import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.core.JdbcTemplate; import com.alibaba.druid.pool.DruidDataSource; /** * JdbcConfig類 * @author 張澤 * */ @Configuration @PropertySource("classpath:jdbc.properties") //--你的配置信息的位置 public class JdbcConfig { //-- 1. 獲取配置信息 @Value("${jdbc.driverClass}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Value("${pool.maxActive}") private int maxActive; //-- 2. 數據庫鏈接池對象 @Bean(name="dataSource") public DataSource createDataSource() { DruidDataSource ds = new DruidDataSource(); ds.setDriverClassName(driver); ds.setUrl(url); ds.setUsername(username); ds.setPassword(password); ds.setMaxActive(maxActive); return ds; } //-- 3. 配置JdbcTemplate @Bean(name="jdbcTemplate") public JdbcTemplate createJdbcTemplate(DataSource ds) { return new JdbcTemplate(ds);//-- 利用數據源構造JdbcTemplate } }
6. Spring 配置類:SpringConfig.java
/** * Spring 配置類 * 多配置的使用方式 */ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @ComponentScan("day")//--所在包名 @Import(JdbcConfig.class) //-- 在主配置中導入子配置 public class SpringConfig { }
7. 主函數入口:Invoker.java
import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Invoker { public static void main(String[] args) { ApplicationContext ctx= new AnnotationConfigApplicationContext(SpringConfig.class); DataSource ds = (DataSource)ctx.getBean("dataSource"); System.out.println(ds); } }
8. 測試類:TestAccountDao.java
import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes= {SpringConfig.class}) public class TestAccountDao { @Autowired @Qualifier("accountDaoTemplateImpl")//-- 選擇要調用 接口的實現類 private IAccountDao actDao; @Test public void testFind() { List<Account> acts = actDao.findAll(); for (Account account : acts) { System.out.println(account); } } @Test public void testSave() { actDao.saveOrUpdate(new Account("xx",12.0)); } @Test public void testUpdate() { actDao.saveOrUpdate(new Account(8,"xx",22.0)); } @Test public void testDelete() { actDao.delete(new Account(8,"xx",22.0)); } }