Use Java to implement your own database or ing framework

Source: Internet
Author: User

The or framework is translated as an object relationship ing framework. When it comes to the or framework, we will immediately think of the well-known hibernate, ibatis, and some other object relationship ing frameworks, and marvel at its magic. When you are amazed, you may be interested in exploring their implementation principles. Next we will implement a simple or framework.

First, why should we use the or framework? Although OOA and OOP have become the mainstream idea of software programming, relational databases are still the most popular and efficient databases. So the question is, how can we persist the data produced in our object-oriented ideology program to a relational database? Of course, there are a lot of methods. The most direct thing is to use the SQL language to store data in the database according to their relationship, but this is very troublesome to implement, in order to implement a simple function, we often need to write hundreds of lines of code, which is time-consuming and laborious. We can also use popular ORM frameworks, such as Hibernate and ibatis. In fact, most small and medium-sized companies use hibernate as their preferred choice. Hibernate is a very good or framework. It encapsulates JDBC in a lightweight manner, so that we can use the object-oriented idea to manipulate the database as we like. Next, we will explore how to implement a simple or framework to complete the same functions as hibernate.

In order to illustrate the central idea of implementation, we will skip the details first. Make the following rules for implementation:

  1. The Class Name of the VO object needs to be mapped to the table name of the database. For example, if the VO object class is named user. Java, the database table is user;
  2. The member variable name of the vo object maps the field name of the database table. For example, if the member variable in the user is ID, name, and birthday, the field name in the User table of the database must also be ID, name, birthday;
  3. The correspondence between the member variable type in the VO object and the field type in the database table is as follows ): integer ing int (8), long corresponds to int (16), float corresponds to float (10, 2), double corresponds to double (16, 4), date corresponds to timestamp, string corresponds to text.
  4. The VO object must contain an integer member variable ID. The field name mapped to the database is ID, the type is int (8), and the primary key is automatically increased.

Here we only paste some key code. The entire project has been extended to csdn and you can download it separately.
First, create a Vo class:

package com.zzb;import java.util.Date;public class User {private Integer id; private Float value;private String name;private Date date;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Date getDate() {return date;}public void setDate(Date date) {this.date = date;}public Float getValue() {return value;}public void setValue(Float value) {this.value = value;}}

This class has an integer type ID, three other member variables, and the corresponding get/set method, which is a standard pojo.

According to our or rules, the name of the table mapped to the database is user, and the field name and field type in the table are

Id int (8) auto_increment primary key
Name text
Value float (8, 2)
Date Timestamp

Then, we need a general DAO class. The general Dao includes five methods (the method listed is the main method, and the method body has been omitted). The Code is as follows:

public class BaseDAO {public int add(Object o) throws Exception{}public int update(Object o) throws Exception{}public int delete(Object o) throws Exception{}public List query(Object o) throws Exception{}}

The four methods in the class add, modify, delete, and query objects respectively.

Next is our core class. The main task of this class is to generate corresponding SQL statements based on four situations of object addition, deletion, modification, and query, and then perform database operations through SQL statements to complete or ing. The Code is as follows:

public class StandardSQL {public String add(Object o) throws Exception{}public String update(Object o) throws Exception{}public String delete(Object o) throws Exception{}public String query(Object o) throws Exception{}}
  1. The add method generates an insert statement and runs add (User). The return string is insert into user (name, value, date) values ('****', ****,'**********');
  2. The update method generates an update statement and runs Update (User). The returned string is: update user set name = '*****', value = ***, date = '**********' Where id = *;
  3. The delete method generates a delete statement, runs Delete (user), and returns the string: delete from user where id = *;
  4. The query method generates a query statement and runs query (User). The return string is select name, value, ID, date from user where name like '% ***** % ';
  5. In addition, to facilitate table creation, we also need a create method to generate table creation statements. After passing the user as a parameter, a string is returned: create Table if not exists user (ID int (8) auto_increment, Name text, value float (8, 2), date timestamp, primary key (ID ))

The above are the functions to be completed by our core class.

Next, we will write a database connection class to encapsulate the connection operations:

package com.zzb;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class DB {public Connection getConnection(){Connection conn =null;try {Class.forName("com.mysql.jdbc.Driver").newInstance();conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/business", "root", "123");} catch (Exception e) {e.printStackTrace();}return conn;}public void releaseConnection(ResultSet rs,Statement stat,Connection conn){if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stat != null) {try {stat.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}}

Here, my database names are business, user names, and passwords are root and 123 respectively. You can modify them based on your own situation and do not forget to introduce MySQL JDBC.

Finally, we create a test class to test whether the test class is successful.

package com.zzb;import java.util.Date;import java.util.List;import org.junit.Test;public class TestDB {BaseDAO dao = new BaseDAO();@Testpublic void testcreate() throws Exception{StandardSQL standardSQL = new StandardSQL();String sql = standardSQL.create(new User());System.out.println(sql);dao.executeUpdate(sql);}@Testpublic void testadd() throws Exception{User user = new User();user.setName("xiaohong");user.setValue((float)45.60);user.setDate(new Date());dao.add(user);}@Testpublic void testupdate() throws Exception{User user = new User();user.setId(1);user.setName("xiaowang");user.setValue((float)90.88);user.setDate(new Date());dao.update(user);}@Testpublic void testquery() throws Exception{User user = new User();user.setName("xiaowang");List<User> list = dao.query(user);for(User u: list){System.out.print(u.getId()+"    ");System.out.print(u.getName()+"    ");System.out.println(u.getDate());}}@Testpublic void testdel() throws Exception{User user = new User();user.setId(1);dao.delete(user);}}

The test class has five methods: Table creation, insertion, modification, query, and deletion.

Here, we can see that the so-called or ing is to get the object information through the Java object, use reflection, generate SQL statements, and then operate on the database using JDBC. In this program, we have not performed transaction processing, no connection pool, no multi-Table ing, and poor portability, it only persists a simple Java object to the corresponding table in the database. However, as an exercise, I have explained how to implement my own or framework. I hope you will be inspired after reading it. It is not easy to write, and the right should be a reference. You are welcome to give your reference.

Project: Download source code

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.