Implementation of the save operation on the persistence layer of ORM in the 9_Jvn framework (Lecture 9), 9_jvnorm

Source: Internet
Author: User

Implementation of the save operation on the persistence layer of ORM in the 9_Jvn framework (Lecture 9), 9_jvnorm

Content of this blog:

Scenario: In the past, many people believed that jbdc had made different encapsulation, because pure JDBC operations were relatively cumbersome. So today we will encapsulate JBDC.

Integrate it into our Jvn framework.

Solution:

You can directly view the following code.

1. Introduce the connection pool concept druid before operating the database. I believe everyone understands the advantages of the connection pool.

2. Introduce ThreadLocal. Specify a generic Connection to store links. This class ensures that you get the same Connection in a thread.

3. Create a JDBC class to store driver user pasword jdbcUrl.

4. Create a pool interface, define the getConnection method, and provide interface-oriented ideas. In the future, there may be connection pools such as c3p0 And druid.

5. Define the interface implementation class DruidPool, define the ThreadLocal attribute <Connection> connections, initialize and create the Connection to the database, and provide the getConnection () method. When obtaining the Connection, first judge

Whether connections. get () is null. If it is null, it is obtained from the Druid connection pool and then in connections. set (conn );

6. Create a DB class that encapsulates the JDBC operation.

7. Merge the object class with DAO and define the parent class JvnModel, which has two attributes: String = tableName (corresponding to the table name), Map = attrs (database field ), define save (), update (), delete (), find ()

(DB. save is called here) to save a data method.

8. For the analysis of the save () operation, Mysql adds a data operation to insert into user (name, age, school) values (?,?,?) The structure analysis is as follows,

Insert into user (key) values (wenhao:

Step 1: remove the last comma (,) from key = name, age, and school ".

Step 2 wenhao = ?,?, ?, Remove the last comma

Insert into user (name, age, school) values (?,?,?) Insert the corresponding parameter values during execution.

Insert into user (name, age, school) values (everxs, 100, Tsinghua)

9. Define the @ Model annotation class and give the corresponding model annotation.

10. Add the class with @ Model annotation in the scan to the Map.

Sample Code:

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; private ThreadLocal <Connection> connections = new ThreadLocal <Connection> (); /*** create druid * @ param jdbc */public DruidPool (Jdbc jdbc) {dataSource = new DruidDataSource (); dataSource. setDriverClassName (jdbc. getDriver (); dataSource. setUsername (jdbc. getUser (); dataSource. setPassword (jdbc. getPassword (); dataSource. setUrl (jdbc. getJdbcUrl (); dataSource. setPoolPreparedStatements (true); dataSource. setMaxPoolPreparedStatementPerConnectionSize (20); dataSource. setInitialSize (5); dataSource. setMinIdle (1); dataSource. setMaxActive (10); dataSource. setMaxWait (60000); // enable the monitoring statistics function try {dataSource. setFilters ("stat");} catch (SQLException e) {e. printStackTrace ();} // for mysql dataSource. setPoolPreparedStatements (false);} public DruidPool () {}/ *** get a Connection * @ return */public synchronized Connection getConnection () {Connection conn = connections. get (); System. out. println ("Enter:" + conn); try {if (conn = null | conn. isClosed () {conn = dataSource. getConnection (); System. out. println ("after 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> (); private 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:

/*** Common Database Query class * @ author everxs **/public class Db {/*** save operation * @ return */public static int save (String tableName, jvnModel 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 value S [] = 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 + ")"; ps = conn. prepareStatement (SQL, Statement. RETURN_GENERATED_KEYS); for (I = 0; I <values. length; I ++) {ps. setObject (I + 1, values [I]);} // execute the operation result = ps.exe cut EUpdate (); rs = ps. getGeneratedKeys (); if (rs. next () {// it knows that there is only one column, so the first column Long id = rs is obtained. 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 annotation:

/*** Annotation object class ** @ author everxs **/@ Retention (RetentionPolicy. RUNTIME) public @ interface Model {String name ();}

Scan code:

Public static void scanClass (Constant constant) {// get the absolute path strength of classes String path = ScanKit. class. getClassLoader (). getResource (""). getPath (); // obtain the full name of the class, for example, con. everxs. test. testController. classList <String> listClass = FileKit. listClassFileAbsolutePath (path); for (String clazzStr: listClass) {try {// find the ClassClass clazz = Class with the full name of this 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 ");}}}

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 Member (); member. set ("name", "everxs"); member. set ("age", 18); member. save (); renderString ("added successfully! ");}}

Result: The database is successfully saved.

 

About Jvn:

The framework is named Jvn. There are continuous development videos in the blog. Each blog post is a knowledge point. For introduction and learning about the framework, you can start from the first lecture on my blog;

The content of the source code and video: http://pan.baidu.com/s/1i3iY9fv

Jvn framework QQ chat group: 399603805

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

Forever brother eight...

 

    

 

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.