Dynamically modifying class annotations (Assignment)

Source: Internet
Author: User

1. Dynamic modification of annotations culprit:

Java code
/**
* Object Pooling Tool Class
*
* Current ORM Dynamic Mapping solution available
*
* @author Andy.zheng
* @since 2012.09.25 15:55 PM
* @vesion 1.0
*
*/
public class Classpoolutils {


/**
* Runtime Dynamic ORM Table mapping
*
*
* @param entityclassname the fully qualified class name of the entity to be mapped
* @param tableName The name of the table to be mapped
* @return the mapped class object
*/
public static class<?> TableMapping (String entityclassname, String tableName) {
Class<?> c = null;

if (Stringutils.isempty (entityclassname) | | Stringutils.isempty (TableName)) {
throw new IllegalArgumentException ("The Mapping parameter is invalid!");
}

try {
Classpool Classpool = Classpool.getdefault ();
Classpool.appendclasspath (New Classclasspath (Classpoolutils.class));
Classpool.importpackage ("Javax.persistence");
Ctclass clazz = Classpool.get (entityclassname);
Clazz.defrost ();
Classfile classfile = Clazz.getclassfile ();

Constpool Constpool = Classfile.getconstpool ();
Annotation tableannotation = new Annotation ("Javax.persistence.Table", Constpool);
Tableannotation.addmembervalue ("name", New Stringmembervalue (TableName, Constpool));
Get run-time annotation properties
Annotationsattribute attribute = (annotationsattribute) classfile.getattribute (Annotationsattribute.visibletag);
Attribute.addannotation (tableannotation);
Classfile.addattribute (attribute);
Classfile.setversiontojava5 ();
Clazz.writefile ();

TODO The entity must not be loaded in the current ClassLoader. (Loading the same class with a classloader will only load once)
c = Clazz.toclass ();
Entityclassloader loader = new Entityclassloader (ClassPoolUtils.class.getClassLoader ());
c = clazz.toclass (loader, NULL);
} catch (Exception e) {
E.printstacktrace ();
}
&nbsp;
return C;
}

public static void Main (string[] args) {
Class<?> clazz = classpoolutils.tablemapping ("Com.andy.model.order.Order", "order1");
System.out.println ("Modified @table:" + clazz.getannotation (table.class));
}
}

2. PO class loader:

Java code
/**
* Entity class Loader *
* This loader is primarily used to reload entities after dynamic modification of entities at runtime
*
* @author Andy.zheng
* @since 2012.09.25 16:18 PM
* @vesion 1.0
*
*/
public class Entityclassloader extends ClassLoader {

Private ClassLoader parent;

Public Entityclassloader (ClassLoader parent) {
This.parent = parent;
}

@Override
Public class<?> loadclass (String name) throws ClassNotFoundException {
Return This.loadclass (name, false);
}

@Override
Protected synchronized class<?> loadclass (String name, Boolean resolve)
Throws ClassNotFoundException {
Class<?> clazz = this.findloadedclass (name);
if (null! = parent) {
Clazz = Parent.loadclass (name);
}
if (null = = Clazz) {
This.findsystemclass (name);
}

if (null = = Clazz) {
throw new ClassNotFoundException ();
}
if (null! = Clazz && Resolve) {
This.resolveclass (Clazz);
}

return clazz;
}

/**
* @param args
*/
public static void Main (string[] args) {

}

}

3. Leave the latest mapping object to Hibernate ~ Of course this stuff is of course in the DAO layer ha, you need to overwrite hibernate to initialize the default loaded mapping object. You can put it in such a way as Basehiberantedao, when you need to dynamically map the table name, first tune it, and then write your hql. Of course, if the interface is unified, you can also play a higher level. (For interfaces that need dynamic mapping, a silent dynamic mapping!!!) Which is unknown to God),

/**
* Runtime Dynamic ORM Table mapping
*
* @param tablemapping Map Collection
* Key-table name to be mapped value-entity object to be mapped
*/
@SuppressWarnings ("unused")
protected void TableMapping (map<string, class<?>> tablemapping) {
Assert.notempty (TableMapping, "the mapping parameter is empty!");
For (String TableName:tableMapping.keySet ()) {
class<?> Entityclass = Tablemapping.get (tableName);
String className = Entityclass.getname ();
Classmetadata metadata = This.getsessionfactory (). Getclassmetadata (ClassName);
class<?> Mappedclass = Metadata.getmappedclass ();
Mappedclass = classpoolutils.tablemapping (ClassName, tableName);
}
}

Invocation Example:

Java code
Public page<orderdetail> getList (int currentpage, int pageSize) {
This.tablemapping (New HashMap () {
{
This.put ("Orderdetail1", Orderdetail.class);
}
});
page<orderdetail> page = This.<orderdetail>paginglist ("", CurrentPage, pageSize);
Assert.notempty (Page.getitems ());
return page;
}

Execute statement:

SQL code
Hibernate:select Count (*) as col_0_0_ from OrderDetail orderdetai0_
Hibernate:select orderdetai0_.id as id15_, orderdetai0_.docid as docid15_, orderdetai0_. Errordesc as errordesc15_, orderdetai0_.insertedtime as inserted3_15_, orderdetai0_. OrderID as orderid15_, orderdetai0_.ordernum as ordernum15_, orderdetai0_. Segmentsids as segments5_15_, Orderdetai0_.selltype as selltype15_, orderdetai0_.status as status15_ from OrderDetail Ord erdetai0_

Dynamically modifying class annotations (Assignment)

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.