ORM Thought -- Using JDBC in an Object-Oriented Way

Keywords: Database SQL Java Attribute

Basic Ideas of ORM (Object Relation Mapping)
- Table structure corresponds to classes; field and class attributes correspond to each other; records and objects correspond to each other in tables;
Make javabean's attribute names and types as consistent as possible with the database!
A record corresponds to an object. Place these queried objects in containers (List,Set,Map)
Encapsulate a record in a table into an Object array
Encapsulate a record in a table into a map
Encapsulate a record in a table into a javabean object
Example: Operating a database in orm mode

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("All queries:");
		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("End of query");
		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();
	}  
}

Posted by Joe Haley on Thu, 31 Jan 2019 13:09:15 -0800