1. 程式人生 > >ORM思想--以面向物件的方式使用JDBC

ORM思想--以面向物件的方式使用JDBC

ORM(Object Relationship Mapping)的基本思想
– 表結構跟類對應; 表中欄位和類的屬性對應;表中記錄和物件對應;
– 讓javabean的屬性名和型別儘量和資料庫保持一致!
– 一條記錄對應一個物件。將這些查詢到的物件放到容器中(List,Set,Map)
• 將表中的一條記錄封裝到Object陣列中
• 將表中的一條記錄封裝到map中
• 將表中一條記錄封裝到javabean物件中
例子: 以orm方式來操作資料庫

package cn.njit.orm;

public class Products {
	private int pid;
	private String pname;
	private double price;
	private int categoryId;
	public Products() {
		
	}
	public Products(int pid,String pname,double price,int categoryId) {
		super();
		this.pid=pid;
		this.pname=pname;
		this.price=price;
		this.categoryId=categoryId;
	}
	
	public int getPid() {
		return pid;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public int getCategoryId() {
		return categoryId;
	}
	public void setCategoryId(int categoryId) {
		this.categoryId = categoryId;
	}
	public String toString() {
		return pname+"-"+price;
	}
}
----------------------------------------------------------------------
package cn.njit.orm;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import util.C3P0Utils;

public class ProductUtil {
	private static Connection conn;
	
	static {
			try {
				conn=C3P0Utils.getConnection();
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}
	
	void selectAll() {
		String sql="Select * from products";
		PreparedStatement psmt;
		try {
			psmt = conn.prepareStatement(sql);
		
		ResultSet rs=psmt.executeQuery();
		System.out.println("查詢全部:");
		while(rs.next()) {
			String pid=rs.getString("pid");
			String pname=rs.getString("pname");
			Double price=rs.getDouble("price");
			System.out.println(pid+"-"+pname+"-"+price);
		}
		System.out.println("查詢結束");
		rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	void closeAll() {
		try {
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
----------------------------------------------------------------------------
package cn.njit.orm;

public class TestORM {

	public static void main(String[] args) {
		ProductUtil pu = new ProductUtil();

		pu.selectAll();

		pu.closeAll();
	}  
}

執行結果