Java Annotations Project is simulated hibenernate generate SQL statement

Source: Internet
Author: User

Compiled some of the recent Java annotations , using Java annotations to emulate the Hibenernate ORM model to build the mapping of objects to SQL statements

Creation of Table annotations

Package Com.imooc.test;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import Java.lang.annotation.target;import javax.lang.model.element.Element ;//used as the annotation for a class, the life cycle is a runtime value @target ({elementtype.type}) @Retention (retentionpolicy.runtime) public @interface Table { String value ();}

Creation of field annotations

Package Com.imooc.test;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import * */@Target ({) When the scope is run for a field java.lang.annotation.target;/* Elementtype.field}) @Retention (retentionpolicy.runtime) public @interface Column {String value ();}

User table (Class)

package com.imooc.test; @Table ("user") public class filter {  @Column ("id")  private  int id;   @Column ("user_name")  private String userName;   @Column ( "user_name")  private String nickName;   @Column ("Age")  private int age;    @Column ("City")  private String city;   @Column ("email")  private  string email;   @Column ("mobile")  private string mobile; public int  getid ()  {  return id; } public void setid (int id)  {   this.id = id; } public string getusername ()  {  return  username; } public void setusername (String username)  {   This.username = username; } public string getnickname ()  {  return  nickname; }&nbSp;public void setnickname (String nickname)  {  this.nickName =  Nickname; } public int getage ()  {  return age; } public  void setage (int age)  {  this.age = age; } public  String getcity ()  {  return city; } public void setcity (String  city)  {  this.city = city; } public string getemail ()   {  return email; } public void setemail (String email)  {   this.email = email; } public string getmobile ()  {  return  mobile; } public void setmobile (String mobile)  {  this.mobile  = mobile; }}

Creating a Test class

Package Com.imooc.test, @Table ("Coder") public class Coder {@Column ("id") private int id; @Column ("name") Private String UserName; @Column ("Age") private int age;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetUserName () {return userName;} public void Setusername (String userName) {this.username = UserName;} public int getage () {return age;} public void Setage (int.) {this.age = age;}}

The generation process of SQL statements

package com.imooc.test;import java.lang.reflect.field;import  Java.lang.reflect.invocationtargetexception;import java.lang.reflect.method;public class test  { public static void main (String[] args)  {  //  How the code maps to the database   filter f1 = new filter ();   f1.setid (  FILTER F2);  = new filter ();   f2.setusername ("Lucy");   filter f3 = new  filter ();   f3.setemail ("[email protected],[email protected],[email protected]") ;   coder c1 = new coder ();   c1.setusername ("Ruanjianlin");   String sql1 = query (F1);   string sql2 = query (F2);   String  sql3 = query (F3);   string sql4 = query (C1);   System.out.println (SQL1);   system.out.println (SQL2);    system.out.println (SQL3);   system.out.println (SQL4); } private static  String query (object f)  {  // todo auto-generated method stub   stringbuilder sb = new stringbuilder ();   // 1. Gets the class's details by class by class type   class c = f.getclass ();  // java  Package.isannotationpresent () method usage Example Tutorial. The,  //  method returns True if a comment of the specified type exists on this element or returns FALSE  // 2. Gets the name of the table   boolean  exists = c.isannotationpresent (Table.class);  if  (!exists)  {    return null;  }  Table t =  (Table)  c.getannotation ( Table.class);   string tablename = t.value ();   sb.append ("Select* from   "). Append (TableName). Append ("  where 1=1  ");   // 3 traverse all fields   field[]  farray =&Nbsp;c.getdeclaredfields ();  for  (Field field : farray)  {     4 get sql   // 4.1 field name corresponding to each field    boolean fExists =  Field.isannotationpresent (Column.class);//  exists    //  determines if there is a field    if   (!fexists)  {    continue;   }   Column  Column = field.getannotation (Column.class);   string columnname =  Column.value ();   object fieldvalue = null;   string  Filedname = field.getname ();    // 4.2 Get the field value (Get the field's Get method first)    string  getMethodName =  "Get"      + filedname.substring (0, 1). toUpperCase ()      + filedname.substring (1);   try {     Method getMethod = c.getmethod (Getmethodname);//  Gets the value     //  the reflection channel to get the field value      fieldvalue = getmethod.invoke (f);   } catch  (SecurityException e )  {    // TODO Auto-generated catch block     E.printstacktrace ();   } catch  (nosuchmethodexception e)  {     // todo auto-generated catch block    e.printstacktrace ();    } catch  (illegalargumentexception e)  {    //  Todo auto-generated catch block    e.printstacktrace ();    }  catch  (illegalaccessexception e)  {    // TODO  Auto-generated catch block    e.printstacktrace ();    } catch   (Invocationtargetexception&nbsP;e)  {    // TODO Auto-generated catch block     e.printstacktrace ();   }   if  (fieldvalue == null      | |   (fieldvalue instanceof integer &&  (Integer)  fieldvalue == 0))  {    continue;   }   //4.3 assembled sql    Sb.append ("and "). Append (ColumnName);   if  (fieldvalue instanceof string)  {    if  ((String)  fieldvalue). Contains (","))  {      String[] values =  (String)  fieldvalue. Split (",");      sb.append (" in (");     for  (string v : values)  {       sb.append ("'"). Append (v). Append ("',");      }       sb.deletecharat (Sb.length ()  - 1);      sb.append (")");     } else {     sb.append ("= "). Append ( Fieldvalue). Append ("'");    }   } else {     Sb.append ("="). Append (Fieldvalue.tostring ());   }  }  return  Sb.tostring ();  }}

650) this.width=650; "Width=" 313 "height=" "title=" code. jpg "style=" width:466px;height:60px; "alt=" Wkiom1iukdwtmoanaadwlnulcdy319.jpg-wh_50 "src=" https://s1.51cto.com/wyfs02/M01/8D/E7/ Wkiom1iukdwtmoanaadwlnulcdy319.jpg-wh_500x0-wm_3-wmp_4-s_1068315026.jpg "/>

This article is from the "Ruanjianlin" blog, make sure to keep this source http://ruanjianlin.blog.51cto.com/11146685/1900584

Java Annotations Project is simulated hibenernate generate SQL statement

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.