模拟Hibernate框架的小demo

模拟Hibernate框架的小demo

该程序为尚学堂马士兵老师讲解,模拟了hibernate的原理,主要应用了字符串拼接,反射知识。

step1,新建数据库

  

use jd;
create table _student(
_id int(11),
_nage varchar(20),
_age int(11));

step 2 student实体类,再次略过

 

step3,编写session类,模拟hibernate的实现原理。

 

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

import com.bjsxt.hibernate.model.Student;

public class Session {
	static String tableName = "_Student";
	static Map<String, String> cfs = new HashMap<String, String>();
	static String[] methodNames;

	public Session() {
		cfs.put("_id", "id");
		cfs.put("_name", "name");
		cfs.put("_age", "age");
		methodNames = new String[cfs.size()];
	}

	public static void save(Student s) throws Exception {
		// TODO Auto-generated method stub
		int index = 0;
		String sql = createSql();

		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection(
					"jdbc:mysql://localhost/jd", "root", "123456");
			PreparedStatement ps = conn.prepareStatement(sql);
				

			for (int i = 0; i < methodNames.length; i++) {
				Method m = s.getClass().getMethod(methodNames[i]);
				Class r = m.getReturnType();
				if (r.getName().equals("java.lang.String")) {
					String returnValue = (String) m.invoke(s);
					ps.setString(i + 1, returnValue);
					System.out.println(returnValue);
				}
				if (r.getName().equals("int")) {
					Integer returnValue = (Integer) m.invoke(s);
					ps.setInt(i + 1, returnValue);
					System.out.println(returnValue);
				}
				// System.out.println(m.getName()+","+m.getReturnType()+","+r.getName());
			}
			System.out.println(sql);
			ps.executeUpdate();	
			ps.close();
			conn.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private static String createSql() {

		String str2 = "";
		String str1 = "";
		int index = 0;
		for (String s : cfs.keySet()) {//s为_id,_Age,_Name
			String v = cfs.get(s);
			v = Character.toUpperCase(v.charAt(0)) + v.substring(1);//Id,Name,Age
			//System.out.println(v+"涛");
			methodNames[index] = "get" + v; // str1+=s+",";//getId,getName,getAge
			//System.out.println(s);
			//System.out.println(methodNames[index]);
			str1 += s + ",";
			index++;
			System.out.println(str1);
		}
		str1 = str1.substring(0, str1.length() - 1);
		//System.out.println(str1);
		for (int i = 0; i < cfs.size(); i++) {

			if (i == cfs.size() - 1) {
				str2 += "?";
			} else {
				str2 += "?,";
			}

		}
		//System.out.println(str2);
		String sql = "insert into " + tableName + "(" + str1 + ")"
				+ " values (" + str2 + ")";
		System.out.println(sql+"createSql方法里面");
		return sql;
	}

}

step4,测试,

import com.bjsxt.hibernate.model.Student;
public class StudentTest {

	public static void main(String[] args) throws Exception {

		Student s = new Student();
		s.setId(10);
		s.setName("s1");
		s.setAge(1);		
		Session session = new Session();
		session.save(s);
	}
}

 

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/110101.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Linux基本操作命令 实验

    Linux基本操作命令 实验一、实验目的:1. 熟悉Linux基本命令。2. 熟悉Linux操作系统。二、实验环境:一台装有Linux的机器。三、实验内容:1.文件操作命令的使用。用vi编辑器新建一个testl文件输入thisistestl~!查看文件与目录ls进入Linux系统,输入ls-m按回车键执行。 一、实验目的:1. 熟悉Linux基本命令。2. 熟悉Linux操作系统。 二、实验环境:一台装有Linux的机器…

    2022年9月29日
    4
  • java实现html转word_javaweb与html区别

    java实现html转word_javaweb与html区别前段时间在做html生成word功能,找了好几种方案,有的用jacob,但是这个比较麻烦,又是dll又是jar的,依赖太多了,而且代码量比较多,所有以采用了freemarker来生成word,制作一个模板就可以生成word文档了,生成的图片也不会依赖本地路径。制作模板,打开word,制作报告的样式,然后另存为xml格式,最好是2003格式的xml,不然会出现不兼容的现象。完成之后修改为ftl格

    2022年10月11日
    3
  • 关于Js后退几种方式

    关于Js后退几种方式2019独角兽企业重金招聘Python工程师标准>>>…

    2022年7月25日
    8
  • java序列化和反序列化以及序列化ID的作用分析

    java序列化和反序列化以及序列化ID的作用分析java序列化和反序列化以及序列化ID的作用分析

    2022年6月18日
    26
  • Oracle insert into select大数据量踩过的坑

    Oracle insert into select大数据量踩过的坑1、简单粗暴insertintotable1select*fromtable2;commit;灰度环境机器配置不好,二百多万数据十来分钟没有导完,产生大量归档日志。删除索引约束后可能要好点。大数量有风险,可能会导致归档日志撑爆。2、nologgingaltertabletable1nologging;insert/*+append*/intotable…

    2022年7月15日
    86
  • 【sshd】sshd_config 中 PermitRootLogin 的forced-commands-only的限定密钥登陆、限定执行命令

    【sshd】sshd_config 中 PermitRootLogin 的forced-commands-only的限定密钥登陆、限定执行命令主讲:PermitRootLogin的可选项众所周知,sshd_config是sshd的配置文件,其中PermitRootLogin可以限定root用户通过ssh的登录方式,如禁止登陆、禁止密码登录、仅允许密钥登陆和开放登陆,以下是对可选项的概括:参数类别 是否允许ssh登陆 登录方式 交互shell yes 允许 没有限制 没有限制 without-password 允许 除密码以外 没有限制 forced-commands-on

    2022年6月1日
    29

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号