使用Spring進行JDBC操作詳細案例

Spring是一個一站式企業開發框架
1.表現層:springMVC
2.DAO層:SpringJDBC
3.Service層 :處理事務,日誌等等

Spring對象也支持JDBC,對JDBC只進行了薄薄的一層封裝
問題: Java開發已經有JDBC,爲什麼Spring還要支持JDBC操作呢?
最重要的原因: Spring操作JDBC能自動管理事務

在這裏插入圖片描述

在這裏插入圖片描述
在這裏插入圖片描述

操作步驟

1,創建數據庫 spring_jdbc
2.創建數據表 t_user

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

創建對應的domain對象

public class User {
	private Integer id;
	private String name;
	private String email;
	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 String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", email=" + email + "]";
	}
	public User(Integer id, String name, String email) {
		super();
		this.id = id;
		this.name = name;
		this.email = email;
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	
}

創建DAO

package com.ywq.spring.dao;

import java.util.List;

import com.ywq.spring.pojo.User;

public interface UserDao {
	
	void insert(User user);
	
	void deleteByPrimaryKey(Integer id);
	
	void updateByPrimaryKey(User user);
	
	User selectByPrimaryKey(Integer id);
	
	List<User> selectList();
}

創建Service

public class UserServiceImpl implements UserService {
	
	private UserDao dao;
	
	@Override
	public void save(User user) {
		dao.save(user);
	}

	@Override
	public void delete(Integer id) {
		dao.delete(id);
	}

	@Override
	public void update(User id) {
		dao.update(id);
	}

	@Override
	public User findById(Integer id) {
		// TODO Auto-generated method stub
		return dao.findById(id);
	}

	@Override
	public List<User> list() {
		// TODO Auto-generated method stub
		return dao.list();
	}

	public void setDao(UserDao dao) {
		this.dao = dao;
	}
}

Spring配置文件

package com.ywq.spring.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;

import com.alibaba.druid.pool.DruidDataSource;

/*
 * @Configuration 
 * 把當前類作爲Spring框架的配置文件 等價於 applicationContext.xml
 * 
 * @ComponentScan 配置包掃描位置
 * 
 * 
 * @PropertySource 讀取.properties配置文件
 * 
 */
@Configuration
@ComponentScan("com.ywq.spring")//等價於 <context:component-scan base-package="com.ywq.spring"/>
//@ComponentScan(basePackages = {"com.ywq.spring.dao","com.ywq.spring.service","com.ywq.spring.controller"} )
@PropertySource("classpath:db.properties")//<context:property-placeholder location="classpath:db.properties"/>
public class SpringConfig {
	/*
	 * @Value 讀取 Spring加載 .properties 配置文件 key 對應的值
	 * 
	 * @Value("${key}")
	 * 	 註解貼在 成員變量上面,自動會把讀取出來key對應的值賦值給成員變量
	 * 	如果不讀取值,可以直接寫值
	 * 
	 * @Value("com.mysql.jdbc.Driver");
	 */
	
	@Value("${jdbc.driverClassName}") //等價於 <property name="username" value="${jdbc.username}"/>
	//@Value("com.mysql.jdbc.Driver")
	private String driverClassName;
	
	@Value("${jdbc.url}")
	private String url;
	
	@Value("${jdbc.username}")
	private String username;
	
	@Value("${jdbc.password}")
	private String password;
	
	@Value("${jdbc.maxActive}")
	private Integer maxActive;
	
	
	
	@Bean(name = "dataSource",initMethod = "init",destroyMethod = "close")
	//@Scope("singleton")
	//等價於 <bean  id="dataSouce" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
	public DataSource getDataSource() {
		//創建阿里巴巴連接池對象
		DruidDataSource ds = new DruidDataSource();
		ds.setDriverClassName(driverClassName);
		ds.setUrl(url);
		ds.setUsername(username);
		ds.setPassword(password);
		ds.setMaxActive(maxActive);
		return ds;
	}
	
	/**
	 * 返回jdbcTemplate對象的 配置
	 */
	@Bean
	@Scope("prototype")//每一個dao中需要一個獨立jdbcTeample對象,所以是多例
	public JdbcTemplate getJdbcTemplate() {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());
		return jdbcTemplate;
	}

}

DAO實現類``

// 引入JDBCTemplate 模板類
	private JdbcTemplate jdbcTemplate;

	//使用setter方式注入數據源即可
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	@Override
	public void save(User user) {
		this.jdbcTemplate.update("insert into t_user (name,email) values (?,?)",
				user.getName(),user.getEmail());
	}

	@Override
	public void delete(Integer id) {
		this.jdbcTemplate.update("delete from t_user where id = ?",id);

	}

	@Override
	public void update(User user) {
		this.jdbcTemplate.update("update t_user set name = ?,email = ? where id = ?",
				user.getName(),user.getEmail(),user.getId());
	}

	@Override
	public User findById(Integer id) {
		String sql = "select * from t_user where id = ?";
		User user = this.jdbcTemplate.queryForObject(sql,new Object[] {id}, new RowMapper<User>() {
			@Override
			public User mapRow(ResultSet rs, int rowNum) throws SQLException {
				User user = new User();
				user.setName(rs.getString("name"));
				user.setEmail(rs.getString("email"));
				user.setId(id);
				return user;
			}
		});
		return user;
	}

	@Override
	public List<User> list() {
		String sql = "select * from t_user";
		
		List<User> users = this.jdbcTemplate.query(sql,new RowMapper<User>(){
			@Override
			public User mapRow(ResultSet rs, int rowNum) throws SQLException {
				User user = new User();
				user.setName(rs.getString("name"));
				user.setEmail(rs.getString("email"));
				user.setId(rs.getInt("id"));
				return user;
			}
		});
		
		return users;
	}

測試代碼

package com.ywq.spring.test;


import java.util.List;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.ywq.spring.SpringConfig;
import com.ywq.spring.pojo.User;
import com.ywq.spring.service.UserService;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
	
	@Resource
	private UserService userService;

	@Test
	public void testInsert() {
		User user = new User(null, "阿炳", "[email protected]");
		userService.insert(user);
	}

	@Test
	public void testDeleteByPrimaryKey() {
		
		userService.deleteByPrimaryKey(2);
	}

	@Test
	public void testUpdateByPrimaryKey() {
		
		User user = new User(7, "阿龍", "[email protected]");
		userService.updateByPrimaryKey(user);	
	}

	@Test
	public void testSelectByPrimaryKey() {
		User user = userService.selectByPrimaryKey(3);
		System.out.println(user);
	}

	@Test
	public void testSelectList() {
		
		List<User> users = userService.selectList();
		for (User user : users) {
			System.out.println(user);
		}
	}

}

相關jar包

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章