Using reflection simulation to implement Hibernate

Source: Internet
Author: User

An object to be stored in the database, generally need to connect to the database through the JDBC , create SQL statement , Execution Execute or executeupdate Method ,

a lot of steps , The process is tedious . , and SQL statement is not an object-oriented language .

Hibernate This approach is object-oriented

. Hibernate objects and databases are connected at both ends ,

is a ORM Object Relational Mapping ,

associating with a relational database by manipulating objects , make additions and deletions to the database ,

simplifies programming , and Cross-database platform , just explain the dialect used , it operations that are automatically converted to various databases .

-------------of Simulation Ideas

1. First create an entity class. For example Student

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.) {this.age = age;}}


2. Set up Database hibernate, set up table Student,varchar _id primary Key,varchar _name,int _age. Remember to import the MySQL jar package in MyEclipse

Slightly

3. Create a Session class , when calling The Save method , the contents of the corresponding class will be read according to the configuration file. , the SQL statement is automatically established and executed .

Establish a mapping that corresponds to the name of the database table and the class name , corresponding to the field name and attribute name of the database table .

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 {//table name string tableName = "_student";//The Map collection of field names and attribute names, key is the field name in the database, value is the property name in the class, and according to value all get method names Map<string, string> columnsfields = New Hashmap<string,string> (); String[] Methodname;//session Constructs the initialization information, such as the Student class initialization Id,name,age property, the database field is _id,_name,_agepublic Session () { Columnsfields.put ("_id", "id"), columnsfields.put ("_name", "name"), Columnsfields.put ("_age", "age");// MethodName stores all get method names for this class. MethodName = new string[columnsfields.size ()];} public void Save (Student s) throws exception{string sql = Createsql (); Class.forName ("Com.mysql.jdbc.Driver"); Connection conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/_student", "root", "root"); PreparedStatement PS = conn.preparestatement (sql),//ps.setxxx () = S.getxxx (); for (int i = 0; i<methodname.length;i++) {//Get the method prototype based on the method name. Method m = S.getclass(). GetMethod (Methodname[i]);//Based on the return value type object to get the class name of the return value, determine which set method to call Preparestatement class ReturnType = M.getreturntype (); if ("Java.lang.String". Equals (Returntype.getname ())) {String v = (string) m.invoke (s); System.out.println (v);//zhangsanps.setstring (i+1,v);} else if ("int". Equals (Returntype.getname ())) {Integer v = (integer) m.invoke (s); System.out.println (v);//1 18ps.setint (i+1,v);} System.out.println (M.getname () + "," +m.getreturntype ());} Ps.executeupdate ();} The INSERT statement for the spelling SQL private String createsql () {//str1 field name, such as _id,_age,_namestring str1 = ""; int index=0;for (String key:column Sfields.keyset ()) {///record the corner mark, get the value corresponding to the key, intercept the first character into uppercase, and get the Get method name by the front plus get. String v = columnsfields.get (key), V = "Get" +character.touppercase (V.charat (0)) +v.substring (1); Methodname[index] = v; STR1 = str1 + key + ","; index++;} STR1 = str1.substring (0,str1.length ()-1); System.out.println (str1);//_id,_age,_name//str2 question mark, such as?,?,? String str2 = ""; for (int i = 0; I < columnsfields.size (); i++) {str2 = str2 + "?,";} str2 = str2.substring (0,str2.length ()-1); System.out.println (STR2);//?,?,?//Spelled SQL statement string s = "INSERT INTO" +tablename+ "(" +str1+ ")" + "values" + "(" +str2+ "); System.out.println (s);//insert into _student (_id,_age,_name) VALUES (?,?,?) return s;}}
4. Test class, for testing

Testhibernate.java

public class Testhibernate {public static void main (string[] args) throws Exception {Student s = new Student (); S.setage (18 ); S.setid (1); S.setname ("Zhangsan"); Session Session = new session (); Session.save (s);}}





Using reflection simulation to implement Hibernate

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.