JDBC(2)----------簡單ORM對象關係映射

1、ORM的核心思想,是將數據庫表中的數據映射成java中的對象(一般一張表設計一個java實體類),便於在java中操作:

如:我現在有一張表account,內容如下:


那麼我們就需要建個對應的實體類:

要求:1)類的屬性名對應表的字段名

          2)提供公開的get/set方法

          3)實現序列化接口:Serializable

          4)另外,提供toString方法、有參、無參構造方法

public class Account implements Serializable{
	private Integer cardId;
	private String username;
	private String password;
	private Integer balance;
	private String mobile;
	private Date account_date;
	public Integer getCardId() {
		return cardId;
	}
	public void setCardId(Integer cardId) {
		this.cardId = cardId;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Integer getBalance() {
		return balance;
	}
	public void setBalance(Integer balance) {
		this.balance = balance;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public Date getAccount_date() {
		return account_date;
	}
	public void setAccount_date(Date account_date) {
		this.account_date = account_date;
	}
	@Override
	public String toString() {
		return "Account [cardId=" + cardId + ", username=" + username
				+ ", password=" + password + ", balance=" + balance
				+ ", mobile=" + mobile + ", account_date=" + account_date + "]";
	}
	public Account(Integer cardId, String username, String password,
			Integer balance, String mobile, Date account_date) {
		super();
		this.cardId = cardId;
		this.username = username;
		this.password = password;
		this.balance = balance;
		this.mobile = mobile;
		this.account_date = account_date;
	}
	public Account() {
		super();
	}
}

2、基於ORM的JDBC開發:

        實現增、刪、改、查:

                

 編碼流程:1)創建表

                  2)封裝實體類

                  3)編寫JDBC操作數據庫

3、Dao層(數據庫訪問對象  data access Object)

        1)我們對於數據庫一張表的增、刪、改、查

        2)對於一張表CRUD未來一定會涉及重複調用,所以,基於提高代碼可複用性,系統可維護性,我們將數據庫的CRUD封裝成爲一個Dao對象,DAO的數量,取決於項目中操作表的數量

       3)命名規範:

                              接口名:表名Dao

                              實體類名:接口名Impl implements接口

4、由於我們建立的是java project工程:所以需要用到JUnit測試

        建立一個測試類:TestAccount.java

import org.junit.Test;       //導包

public class TestAccount {  //類名不能用Test
	Scanner sc = new Scanner(System.in);
	AccountDaoImpl ad = new AccountDaoImpl();
	
	@Test  //註解
	public void deleteAccount(){  //將鼠標選中deleteAccount   鼠標右擊--->run as ---> JUnit Test
		System.out.println("輸入id:");
		int accountId = sc.nextInt(); 
		int i = ad.deleteAccount(accountId);
		System.out.println("刪除了"+i+"條數據");
	}
}
	

5、以Person類完整實例如下:

person表,其中id是序列,序列名:person_seq


1)導入工具類,並配置JDBC(1)中詳解

    jdbc.properties

driverClassName=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:ORCL
username=hr
password=123

   JDBCUtil.java

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtil {
	public static Properties p = new Properties();
	static{
		InputStream ins = null;
		try {
			ins = JDBCUtil.class.getResourceAsStream("/JDBC.properties");
			p.load(ins);
			Class.forName(p.getProperty("driverClassName"));
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				ins.close();
			} catch (IOException e) {
				e.printStackTrace();
			}	
		}	
	}
	public static Connection getConnection(){
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(p.getProperty("url"),p.getProperty("username"),p.getProperty("password"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static void closeAll(PreparedStatement ps,Connection conn,ResultSet rs){
		try{
			if(rs != null){ // 避免空指針異常
				rs.close();
			}
			if(ps != null){
				ps.close();
			}
			if(conn != null){
				conn.close();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

2)建立Person.java類:

import java.util.Date;

public class Person {
	private Integer id ;
	private String name;
	private String mobile;
	private String telphone;
	private String email;
	private String city;
	private Date date;
	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 getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getTelphone() {
		return telphone;
	}
	public void setTelphone(String telphone) {
		this.telphone = telphone;
	}
	public String getEmil() {
		return email;
	}
	public void setEmil(String emil) {
		this.email = emil;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", mobile=" + mobile
				+ ", telphone=" + telphone + ", emil=" + email + ", city="
				+ city + ", date=" + date + "]";
	}
	public Person(Integer id, String name, String mobile, String telphone,
			String email, String city, Date date) {
		super();
		this.id = id;
		this.name = name;
		this.mobile = mobile;
		this.telphone = telphone;
		this.email = email;
		this.city = city;
		this.date = date;
	}
	public Person() {
		super();
	}
}

3)Dao層,創建PersonDao.java

import java.util.*;
public interface PersonDao{
      //插入聯繫人信息
       public Integer insertPerson(Person p) ;
      //更新聯繫人信息
       public void updatePerson(Person p);
      //刪除聯繫人信息
       public void deletePerson(Integer id);
      //根據id查詢聯繫人信息
       public Person queryPersonById(Integer id);
       //查詢所有聯繫人信息
       public List<Person> queryAllPersons() ;
       //根據姓名模糊查找聯繫人信息
       public List<Person> queryPersonsByName(String name);
       //根據手機號碼模糊查找聯繫人信息
       public List<Person> queryPersonsByMobile(String mobile);
       //查看當前月過生日的聯繫人
       public List<Person> queryPersonsByMonth();
}

4)實現 Dao層,創建PersonDaoImpl.java

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PersonDaoImpl implements PersonDao {

	@Override
	public Integer insertPerson(Person p) {
		int i =0;
		Connection conn = JDBCUtil.getConnection();
		PreparedStatement ps = null;
		String sql = "insert into person values(person_seq.nextval,?,?,?,?,?,?)";
		try {
			
			ps = conn.prepareStatement(sql);
			ps.setString(1, p.getName());
			ps.setString(2, p.getMobile());
			ps.setString(3, p.getTelphone());
			ps.setString(4, p.getEmil());
			ps.setString(5, p.getCity());
			ps.setDate(6, new java.sql.Date(p.getDate().getTime()));
			
			i = ps.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JDBCUtil.closeAll(ps, conn, null);
		}
		return i;
	}

	@Override
	public void updatePerson(Person p) {
		Connection conn = JDBCUtil.getConnection();
		PreparedStatement ps = null;
		
		String sql = "update person set name = ?,mobile=?,"
				+ "telphone=?,email=?,city=?,birthday=? where id = ?";
		
		try {
			
			ps = conn.prepareStatement(sql);
			ps.setString(1, p.getName());
			ps.setString(2, p.getMobile());
			ps.setString(3, p.getTelphone());
			ps.setString(4, p.getEmil());
			ps.setString(5, p.getCity());
			ps.setDate(6, new java.sql.Date(p.getDate().getTime()));
			ps.setInt(7, p.getId());
			
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JDBCUtil.closeAll(ps, conn, null);
		}
		
	}

	@Override
	public void deletePerson(Integer id) {
		Connection conn = JDBCUtil.getConnection();
		PreparedStatement ps = null;
		
		String sql = "delete from person where id = ?";
		
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			ps.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JDBCUtil.closeAll(ps, conn, null);
		}
		
	}

	@Override
	public Person queryPersonById(Integer id) {
		Person person = null;
		Connection conn = JDBCUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select * from person where id = ?";
		
		try {
			
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			rs = ps.executeQuery();
			if(rs.next()){
				
				person = new Person();
				person.setId(id);
				person.setName(rs.getString(2));
				person.setMobile(rs.getString(3));
				person.setTelphone(rs.getString(4));
				person.setEmil(rs.getString(5));
				person.setCity(rs.getString(6));
				person.setDate(rs.getDate(7));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JDBCUtil.closeAll(ps, conn, rs);
		} 
		return person;
	}

	@Override
	public List<Person> queryAllPersons() {
		List<Person> list = new ArrayList<Person>();
		Connection conn = JDBCUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select * from person";
		
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()){
				Person p = new Person(
						rs.getInt(1),
						rs.getString(2),
						rs.getString(3),
						rs.getString(4),
						rs.getString(5),
						rs.getString(6),
						rs.getDate(7)
						);
				list.add(p);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JDBCUtil.closeAll(ps, conn, rs);
		}
		
		return list;
	}

	@Override
	public List<Person> queryPersonsByName(String name) {
		List<Person> list = new ArrayList<Person>();
		Connection conn = JDBCUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select * from person where name = ?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, name);
			rs = ps.executeQuery();
			while(rs.next()){
				Person p = new Person(
						rs.getInt(1),
						rs.getString(2),
						rs.getString(3),
						rs.getString(4),
						rs.getString(5),
						rs.getString(6),
						rs.getDate(7)
						);
				list.add(p);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JDBCUtil.closeAll(ps, conn, rs);
		}
		return list;
	}

	@Override
	public List<Person> queryPersonsByMobile(String mobile) {
		List<Person> list = new ArrayList<Person>();
		Connection conn = JDBCUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select * from person where mobile = ?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, mobile);
			rs = ps.executeQuery();
			while(rs.next()){
				Person p = new Person(
						rs.getInt(1),
						rs.getString(2),
						rs.getString(3),
						rs.getString(4),
						rs.getString(5),
						rs.getString(6),
						rs.getDate(7)
						);
				list.add(p);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JDBCUtil.closeAll(ps, conn, rs);
		}
		return list;
	}

	@Override
	public List<Person> queryPersonsByMonth() {
		List<Person> list = new ArrayList<Person>();
		Connection conn = JDBCUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("MM");
		String s = sdf.format(date);
		
		String sql = "select * from person where to_char(birthday,'MM') = ?";
		
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, s);
			rs = ps.executeQuery();
			while(rs.next()){
				Person p = new Person(
						rs.getInt(1),
						rs.getString(2),
						rs.getString(3),
						rs.getString(4),
						rs.getString(5),
						rs.getString(6),
						rs.getDate(7)
						);
				list.add(p);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JDBCUtil.closeAll(ps, conn, rs);
		}
		return list;
	}

}

5)進行JUnit測試:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

import org.junit.Test;

public class TestPerson {
	   PersonDaoImpl pd = new PersonDaoImpl();
	   Scanner sc = new Scanner(System.in);
	   @Test
	   public void testInsertPerson(){
		   Person p = new Person();
		   System.out.println("輸入名字:");
		   String name = sc.next();
		   System.out.println("輸入手機號:");
		   String mobile = sc.next(); 
		   System.out.println("輸入電話:");
		   String telphone = sc.next();
		   System.out.println("輸入郵箱:");
		   String email = sc.next();
		   System.out.println("輸入城市:");
		   String city = sc.next();
		   System.out.println("輸入生日:");
		   String birthday =  sc.next();
		   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		   Date date = null;
		   try {
		      date = sdf.parse(birthday);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		   	p.setName(name);
		   	p.setTelphone(telphone);
		   	p.setMobile(mobile);
		   	p.setEmil(email);
		   	p.setCity(city);
		   	p.setDate(date);
		        int a = pd.insertPerson(p);
		 	System.out.println("成功插入"+a+"行數據!");
	    }
	   
	   
	@Test
	public void updatePerson(){
	    List<Person> list = pd.queryAllPersons();
	    String name = null;
	    System.out.println("輸入要更新的id:");
	    int id = sc.nextInt();
	    for (Person person : list) {
	        if(person.getId().equals(id)){
	            System.out.println("輸入更新的名字:");
		     name = sc.next();
		     Person p = new Person(id,name,person.getMobile(),person.getTelphone(),person.getEmil(),person.getCity(),person.getDate());
		     pd.updatePerson(p);
		     System.out.println("信息更新成功!");
		     return ;
		}
	    } 	    	
	}
	    
	    
       @Test
       public void deletePerson(){
    	   pd.deletePerson(2);
    	   System.out.println("刪除成功!");
       }
	   
       @Test
       public void queryPersonById(){
		   System.out.println("輸入id:");
		   int id = sc.nextInt();
    	   Person p = pd.queryPersonById(id);
    		   System.out.println(p);
    	   
       }
	    
       @Test
       public void queryAllPersons() {
    	   List<Person> list = pd.queryAllPersons();
    	   for (Person person : list) {
    		   System.out.println(person);
    	   }
       }
       
       @Test
       public void queryPersonsByName(){
    	   System.out.println("輸入要查詢的名字:");
    	   String name = sc.next();
    	   List<Person> list = pd.queryPersonsByName(name);
    	   for (Person person : list) {
    		   System.out.println(person);
    	   }
       }
       
       @Test
       public void queryPersonsByMobile(){
    	   System.out.println("輸入要查詢的電話號碼:");
    	   String mobile = sc.next();
    	   List<Person> list = pd.queryPersonsByMobile(mobile);
    	   for (Person person : list) {
    		   System.out.println(person);
    	   }
       }
       
       @Test
       public void queryPersonsByMonth(){
    	  List<Person> list = pd.queryPersonsByMonth();
    	  
    	  for (Person person : list) {
			System.out.println(person);
		}
       }
} 


以上均是java project 工程;
發佈了49 篇原創文章 · 獲贊 14 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章