使用java反射机制简单模拟hibernate的save

实体类:Student.java

public class Student {

	private int id;
	private String name;
	private int age;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

 

核心类:Session.java

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;

public class Session {

	String tableName = "student";
	Map<String, String> cfg = new HashMap<String, String>();
	String[] methodNames;

	public Session() {
		// key-表字段,value-实体类属性名
		cfg.put("id", "id");
		cfg.put("name", "name");
		cfg.put("age", "age");

		methodNames = new String[cfg.size()];
	}

	public void save(Student student) throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/hibernate", "root", "root");
		PreparedStatement pstmt = conn.prepareStatement(createSQL());
		for (int i = 0; i < methodNames.length; i++) {
			// 利用java反射机制
			Method m = student.getClass().getMethod(methodNames[i]);
			if ("int".equals(m.getReturnType().getName())) {
				pstmt.setInt(i + 1, (Integer) m.invoke(student));
			} else if ("java.lang.String".equals(m.getReturnType().getName())) {
				pstmt.setString(i + 1, (String) m.invoke(student));
			}
		}
		pstmt.executeUpdate();
		pstmt.close();
		conn.close();
	}

	private String createSQL() {
		String str1 = "";
		int index = 0;
		for (String key : cfg.keySet()) {
			str1 += key + ", ";
			String value = cfg.get(key);
			methodNames[index++] = "get" + Character.toUpperCase(value.charAt(0)) + value.substring(1);
		}
		str1 = str1.substring(0, str1.length() - 2);

		String str2 = "";
		for (int i = 0; i < cfg.size(); i++) {
			str2 += "?, ";
		}
		str2 = str2.substring(0, str2.length() - 2);

		String sql = "insert into " + tableName + "(" + str1 + ") values (" + str2 + ")";

		return sql;
	}

}

 

测试类:StudentTest.java

public class StudentTest {

	public static void main(String[] args) throws Exception {
		Student student = new Student();
		student.setId(3);
		student.setName("王五");
		student.setAge(23);

		Session session = new Session();
		session.save(student);
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值