【JAVA】Srping和JDBC實現資料庫操作
前言
建立資料庫
首先建立我們的資料庫(這裡我使用的是Mysql),為了演示方便,我這裡簡單的建立一個spring資料庫,然後資料庫有一個user使用者表:
- 建立一個名為
spring
的資料庫。 - 建立一個名為user的資料表,表包括id、email、name、password四個欄位。
CREATE TABLE `user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `email` varchar(255) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;
建立實體類
建立一個實體類和資料庫的表相對應(模型用來儲存要操作的資料)。
package cn.zhenta.www.service.impl.Entity; public class User { int id; String email; String name; String password; public User(String email, String name, String password){ this.email = email; this.name = name; this.password = password; } public int getId(){ return id; } public void setId(int id) { this.id = id; } public String getEmail(){ return email; } public void setEmail(String email){ this.email = email; } public String getName(){ return name; } public void setName(String name){ this.name = name; } public String getPassword(){ return password; } public void setPassword(String password){ this.password = password; } }
模型中的成員屬性id
、email
、name
、password
分別對應資料表user的欄位,為每個成員屬性新增getter
和setter
方法,實現對成員屬性的操作。
資料訪問物件(DAO)模式
DAO(data access object),資料庫訪問物件,主要的功能就是用於驚險資料庫操作的。
UserDao介面
package cn.zhenta.www.service.impl.Dao; import cn.zhenta.www.service.impl.Entity.User; public interface UserDao { public void inSert(User User); }
抽象了User的操作,即User可以進行插入操作(inSert)。
UserDao介面的實現
package cn.zhenta.www.service.impl.Dao.impl;
import cn.zhenta.www.service.impl.Dao.UserDao;
import cn.zhenta.www.service.impl.Entity.User;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class UserDaoImpl implements UserDao {
private DataSource dataSource;
public void setDataSource(DataSource dataSource){
this.dataSource = dataSource;
}
public void inSert(User user){
String sql = "INSERT INTO `spring`.`user` (`email`, `name`, `password`) VALUES (?, ?,?)";
Connection conn = null;
try{
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, user.getEmail());
ps.setString(2, user.getName());
ps.setString(3, user.getPassword());
ps.executeUpdate();
ps.close();
}catch(SQLException e){
throw new RuntimeException(e);
}finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
}
這裡直接用了傳統的JDBC,沒有使用Spring的JdbcTemplate或者別的ORM框架。傳統JDBC和Spring的JdbcTemplate區別
private DataSource dataSource;
這裡對
資料來源配置
<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="customerDAO" class="cn.zhenta.www.service.impl.Dao.impl.UserDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<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/spring" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
</beans>
這裡為了方便直接使用了直連的資料來源(關於直連的資料來源和連線池的資料來源),也可以使用連線池的資料來源。
<bean id="customerDAO" class="cn.zhenta.www.service.impl.Dao.impl.UserDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
其中name="dataSource"
為向cn.zhenta.www.service.impl.Dao.impl.UserDaoImpl
這個類名為dataSource
成員屬性注入一個id
為dataSource
(ref="dataSource"
)的Bean(通過setter方法即setDataSource
),也就是
<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/spring" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
這樣在UserDao
的實現類UserDaoImpl
就能完成了資料來源的裝配了。
裝配Bean
package cn.zhenta.www.service.impl.Config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource(locations = {"Spring-Datasource.xml"})
@ComponentScan(basePackages = {"cn.zhenta.www.service.impl"})
public class Config {
}
@Configuration
宣告這個是配置類,@ImportResource
裝配xml配置檔案(Spring-Datasource.xml為直連資料來源的配置檔案),@ComponentScan
開啟元件掃描。
測試類
package cn.zhenta.www.service.impl.TestC;
import cn.zhenta.www.service.impl.Dao.UserDao;
import cn.zhenta.www.service.impl.Entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration(classes = cn.zhenta.www.service.impl.Config.Config.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class TestC {
@Autowired
UserDao userDao;
@Test
public void dd(){
User user = new User("22", "xue8","22");
userDao.inSert(user);
}
}
ContextConfiguration
指定Spring配置資訊來源,UserDao userDAO
引用UserDao介面,User user = new User("22", "xue8","22")
建立一個User實體類中儲存我們要儲存的資料,userDAO.inSert(user)
通過介面的實現類插入資料。介面的引用
最後我們資料庫成功插入了我們插入的資料。
歡迎加入JAVA學習群949419296,一起交流!