Java Annotations and reflections the practice of making DAO base classes

Source: Internet
Author: User
Tags throw exception

First of all, three annotations.

Primary key annotations

Package comments;import java.lang.annotation.Documented; import java.lang.annotation.elementtype;import java.lang.annotation.inherited; import java.lang.annotation.Retention; import Java.lang.annotation.retentionpolicy;import java.lang.annotation.target;/** * PRIMARY KEY * @author Administrator */@Target (Elementtype. FIELD) @Retention (retentionpolicy.runtime) @Documented @Inherited public @interface    key {}             

Package comments;import java.lang.annotation.Documented; import java.lang.annotation.elementtype;import java.lang.annotation.inherited; import java.lang.annotation.Retention; import Java.lang.annotation.retentionpolicy;import java.lang.annotation.target;/** * Set this note if not associated with data * @ Author Administrator * */@Target (Elementtype. FIELD) @Retention (retentionpolicy.runtime) @Documented @Inherited public @interface    notrecord {}             

Package comments;Import java.lang.annotation.Documented;Import Java.lang.annotation.ElementType;import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import Java.lang.annotation.RetentionPolicy; import Java.lang.annotation.Target; /** * Set table name * @author  Administrator * */@Target (elementtype.type) @Retention ( Retentionpolicy.runtime) @Documented @Inherited public @interface Table {  public String name();}               

Then the custom exception class

package org;/** * 设置自定义异常 * @author  Administrator * */public class NumException extends Exception { private String name; public NumException(String name){ this.name=name; } public String toString(){ return name; }}

Entity class

package org;Import comments. Key;Import comments. Table;Import Comments.notrecord;@Table (name ="Student")PublicClassStudent {@Key Private String ID;private String name;@notRecordPrivate String sex;Privateint age;Public StringGetId() {return ID; }PublicvoidSetId(String ID) {This.id = ID; }Public StringGetName() {return name; }PublicvoidSetName(String name) {THIS.name = name; }public String getSex () {return sex;} public void setsex (String sex) {this.sex = sex;} public int getage () {return age;} public void setAge  (int age) {this.age = Age;}}   

class that processes entity classes to generate SQL.

Package Org;import Java.lang.reflect.field;import comments. Key;import comments.Table;import Comments.notrecord;publicClass Processing {/** * Generate INSERT INTO SQL statement from entity class * @param CL *@return* @throws illegalargumentexception * @throws illegalaccessexception * @throws numexception */Public StringSave (ObjectCL) throws IllegalArgumentException, Illegalaccessexception, numexception{String sql="INSERT into";IfCl!=null) {field[] fiels=Cl.getclass (). Getdeclaredfields ();Get collection of Reflected objects Boolean t=Cl.getclass (). Isannotationpresent (Table.Class);Get the class if there are annotationsif (t) {Tabletab=Cl.getclass (). Getannotation (Table.Class); sql+=Tab.name ();Get table name String name ="";Record field name String value ="";Record Value name Boolean bl=false;Record whether the primary key is emptyfor (FieldFl:fiels) {Cyclic assemblyFl.setaccessible (TRUE);Turn on access to a private variable Object tobj=Fl.GetCL);if (tobj!=null) {IfFl.isannotationpresent (Key.Class)) {Determine if there is a primary key bl=true; }if (!Fl.isannotationpresent (Notrecord.Class) {name+=Fl.getname () +","; value+="'" +tobj.ToString () +"‘,"; } } }if (BL) {if (name.Length () >0) name=name.substring (0,name.Length ()-1);if (value.Length () >0) value=value.substring (0,value.Length ()-1); sql+="(" +name+") VALUES (" +value+")"; }else throw new Numexception ("The class primary key cannot be empty" is not found); }else throw new Numexception ("Incoming object is not an entity class"); }else throw new Numexception ("Incoming object cannot be empty");Throw exceptionreturn SQL; }/** * Incoming Object update * @param obj *@return* @throws illegalargumentexception * @throws illegalaccessexception * @throws numexception */Public StringUpdate (Object obj) throws IllegalArgumentException, Illegalaccessexception, numexception{String sql="Update";if (obj!=null) {field[] Fiels=obj.getclass (). Getdeclaredfields ();Gets the collection of reflected objects, Boolean t=obj.getclass (). Isannotationpresent (Table.Class);Get the class if there are annotationsif (t) {TableTab=obj.getclass (). Getannotation (Table.Class); sql+=Tab.name () +"Set";Get Table name StringWH ="";Record Field name String k=""; Boolean bl=false;Record whether the primary key is emptyfor (FieldFl:fiels) {Cyclic assemblyFl.setaccessible (TRUE);Turn on access to a private variable Object tobj=Fl.Get (obj);if (tobj!=null) {IfFl.isannotationpresent (Key.Class)) {Determine if there is a primary key bl=true; k=Fl.getname () +"= '" +tobj.ToString () +"' Where";}else{if (!Fl.isannotationpresent (Notrecord.Class)) {wh+=Fl.getname () +"= '" +tobj.ToString () +"‘,"; } } } }if (BL) { if (wh.length () >0) wh=wh.substring (0,wh.Length ()-1); if (k.length () >0) k=k.substring (0,k.Length ()-1); sql+=k+wh;} Else throw new Numexception ("Cannot find class primary key primary key cannot be empty");} Else throw new Numexception ("Incoming object is not an entity class");} Else throw new Numexception ("Incoming object cannot be empty");  Throws an exception to return SQL;}}                 

Finally, the test class

package org;Import java.lang.annotation.Annotation;Import Java.lang.reflect.Field;Import comments.Table;import comments. Key; public class Temp {public static Span class= "Hljs-keyword" >void Main (string[] aa) throws IllegalArgumentException, Illegalaccessexception, numexception{Student stu=new Student ( ); Stu.setid ( "CCC"), Stu.setname ( "name"), Stu.setage (18); Stu.setsex ( "male"); //stu=null; System.out. println (new processing ().  Save (Stu)); System.out. println (new processing (). Update (Stu));}}    

Java Annotations and reflections the practice of making DAO base classes

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.