Implementation of the 9_JVN framework ORM Persistence Layer save operation (Nineth)

Source: Internet
Author: User

What this blog says:

Scenario : When using JDBC in the past, it is believed that many people have made different packages for JBDC because the operation of pure JDBC is relatively cumbersome. So today we're going to wrap it up, JBDC.

Integrate it into our JVN framework.

Solution Ideas :

It is not clear that you can see the following code directly.

1, the connection pool concept Druid is introduced before the database operation. Connection pool Benefits, I believe we all understand.

2, introduced threadlocal. generic specifies connection, which is used to store links. This class ensures that you get the same connection in one thread.

3, create the JDBC class to hold the driver user Pasword Jdbcurl.

4, create the pool interface, define the Getconnection method, interface-oriented thinking, there may be c3p0,druid and so on connection pool.

5, define the interface implementation class Druidpool, define properties threadlocal<connection> connections, initialize create in database link, provide getconnection () method, obtain, first judge

Connections.get () is empty, if empty, obtained from the Druid Connection pool, and then in Connections.set (conn);

6, create the DB class, which encapsulates the encapsulation of the JDBC operation.

7, Merge entity classes with DAO, define parent class Jvnmodel, with two attributes, String = tableName (corresponding table name), Map = attrs (database field), define save (), update (), delete (), find ()

And so on, this implementation of the Save () method (which is called db.save), that is, to save a data method, the other next section of the explanation.

8, for the analysis of the Save () operation, MySQL adds a data operation for INSERT into user (Name,age,school) VALUES (?,?,?) This structural analysis is in the following three steps,

Insert into user (key) values (Wenhao) How many key parameters are generated depending on the number of parameters to be inserted, number of question marks:

The first step key=name,age, school to get rid of the last "comma".

Step Two Wenhao =?,?,?, Remove the last comma

Then stitch it up insert into user (Name,age,school) VALUES (?,?,?) The corresponding parameter value is inserted in the execution.

Get insert INTO User (Name,age,school) VALUES (everxs,100, Tsinghua)

9, define the @model annotation class, to the corresponding model annotations.

10, start the scan with @model annotated class added into the map

code example:

Jdbc:

public class JDBC {private string Driver;private string User;private string Password;private string Jdbcurl;public Jdbc () {}public Jdbc (string driver, string user, string password, string jdbcurl) {super (); this.driver = Driver;this.user = user; This.password = Password;this.jdbcurl = Jdbcurl;} Public String Getdriver () {return driver;} public void Setdriver (String driver) {this.driver = driver;} Public String GetUser () {return user;} public void SetUser (String user) {this.user = user;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} Public String Getjdbcurl () {return jdbcurl;} public void Setjdbcurl (String jdbcurl) {this.jdbcurl = Jdbcurl;}}

Pool interface:

Public interface Pool {public  Connection getconnection ();}

Druidpool Implementation class:

/** * Druid Connection Pool * @author Everxs * */public class Druidpool implements pool{private static Druiddatasource Datasource;priv  Ate threadlocal<connection> connections = new threadlocal<connection> ();/** * Create good druid * @param jdbc */public Druidpool (jdbc jdbc) {dataSource = new Druiddatasource ();d atasource.setdriverclassname (Jdbc.getdriver ()); Datasource.setusername (Jdbc.getuser ());d Atasource.setpassword (Jdbc.getpassword ());d Atasource.seturl ( Jdbc.getjdbcurl ());d atasource.setpoolpreparedstatements (true); Datasource.setmaxpoolpreparedstatementperconnectionsize ();d atasource.setinitialsize (5);d Atasource.setminidle (1);d atasource.setmaxactive;d atasource.setmaxwait (60000);//Enable monitoring statistics function try {datasource.setfilters ("stat");} catch (SQLException e) {e.printstacktrace ();} For MySQL datasource.setpoolpreparedstatements (false);} Public Druidpool () {}/** * Gets a connection * @return */public synchronized Connection getconnection () {Connection conn = Connectio Ns.get (); System.out.println ("Enter:" +conn); try {if (conn==null| | Conn.isclosed ()) {conn = Datasource.getconnection (); SYSTEM.OUT.PRINTLN ("null:" +conn); Connections.set (conn);}} catch (Exception e) {throw new RuntimeException (e);} Return conn;}}

Jvnmodel class:

public class Jvnmodel<t extends jvnmodel> {private map<string,object> attrs = new hashmap<string, OBJECT&G t; ();p rivate  String tableName = JvnConfig.CONSTANT.getTable (). GetTable (This.getclass ());/** * Save operation * @return * * public  int Save () {int i = Save (JvnConfig.pool.getConnection ()); return i;} /** * Save operation * @return */public int Save (Connection conn) {int i = Db.save (TableName, this); return i;} Public map<string, Object> Getattrs () {return attrs;} public void Setattrs (map<string, object> attrs) {this.attrs = Attrs;} Public String Gettablename () {return tableName;} public void Settablename (String tableName) {this.tablename = TableName;} public void Set (String attr,object value) {attrs.put (attr, value);} Public Object get (String attr) {return attrs.get (attr);}}

DB Class:

/** * Database Query General class * @author Everxs * */public class Db {/** * save operation * @return */public static int Save (String tablename,jvnmod El model) {return Save (TableName, Model,jvnconfig.pool.getconnection ());} /** * Save operation * @return */public static int Save (String Tablename,jvnmodel model,connection conn) {int result=-1; PreparedStatement ps= null; ResultSet rs =null;try{string keys= ""; String Wenhao = ""; Object values[]=new string[model.getattrs (). Size ()];int i = 0; Map<string,string>strmap = Mapkit.tostringmap (Model.getattrs ()); for (String Attr:strMap.keySet ()) {keys = keys+ Attr+ ","; Wenhao = wenhao+ "?,"; Values[i] = Strmap.get (attr); i++;} if (Keys.endswith (",")) {keys = keys.substring (0,keys.length ()-1);} if (Wenhao.endswith (",")) {Wenhao = Wenhao.substring (0,wenhao.length ()-1);} String sql = "INSERT INTO" +tablename+ "(" +keys+ ") VALUES (" +wenhao+ ")";p s = conn.preparestatement (sql,statement.return_ Generated_keys); for (i = 0; i < values.length; i++) {Ps.setobject (i + 1, values[i]);} Execute operation result = Ps.execuTeupdate (); rs = Ps.getgeneratedkeys ();                  if (Rs.next ()) {//knows only one column, so get the first column Long id = rs.getlong (1);     Model.set ("id", id); }}catch (Exception e) {throw new RuntimeException (e);} Finally{if (rs!=null) {try {rs.close ()} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} if (ps!=null) {try {ps.close ();} catch (SQLException e) {e.printstacktrace ()}} try {if (Conn!=null&&conn.getautocommit ()) {conn.close ();}} catch (Exception e) {e.printstacktrace ()}} return result;}}

Model Annotations:

/** * Annotation Entity class * @author Everxs * */@Retention (retentionpolicy.runtime) public @interface Model {String name ();}

Scan Class Code:

public static void Scanclass (Constant Constant) {//Get classes Absolute Road Strength string path = ScanKit.class.getClassLoader (). GetResource (""). GetPath ();//Get the full name of the class  for example: con.everxs.test.testcontroller.classlist<string> listclass= Filekit.listclassfileabsolutepath (path); for (String Clazzstr:listclass) {try {//Find Classclass Clazz of this class full name = Class.forName (CLAZZSTR); if (clazz!=null) {Controller controller= (Controller) clazz.getannotation (Controller.class) ; Model model = (model) clazz.getannotation (Model.class), if (controller!=null) {Constant.setroute (Controller.space (), Clazz);} if (model!=null) {constant.gettable (). settable (Clazz, Model.name ());}}} catch (Exception e) {System.out.println ("class file not Found");}}}

To test the member class:

@Model (name = "Member") public class member extends jvnmodel<member>{}

Test controller:

@Controller (space = "/member") public class Membercontroller extends jvncontroller{public void Save () {member member = new M Ember (); Member.set ("Name", "Everxs"); Member.set ("Age"); Member.save (); Renderstring ("Add success!") ");}}

Result: The database was saved successfully.

about JVN:

Framework named JVN, the blog has a continuous development of video, each blog is a knowledge point, about the framework of the introduction and learning, from my blog first start to look at;

The source and video of this content:HTTP://PAN.BAIDU.COM/S/1I3IY9FV

JVN frame QQ Exchange Group:399603805

Blog home:http://www.cnblogs.com/everxs/

Forever Starling ...

    

Implementation of the 9_JVN framework ORM Persistence Layer save operation (Nineth)

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.