Based on the object class and the corresponding primary key attribute, it is worth the corresponding entity:
Public <t> T findbyid (class <t> entityclass, serializable entityid ){
Return (t) Super. gethibernatetemplate (). Get (entityclass, entityid );
}
For example, findbyid (user. class, "123"), user is the entity class, and "123" is the value corresponding to the <ID> attribute in user. HBM. xml.
According to the object class and variable corresponding primary key attributes, it is worth all objects:
// Serializable... entityids is a variable parameter, that is, 0 or multiple
Public <t> List <t> findbyids (class <t> entityclass, final serializable... entityids ){
If(Entityids = NULL | entityids. Length = 0 ){
Return new arraylist <t> (0 );
}
// Obtain the object name based on the object class
String entityname = entityclass. getname ();
// Create a configuration object
Configuration CFG = new configuration ();
// Obtain mapping corresponding to the object based on the object name
Persistentclass = cfg. getclassmapping (entityname );
// If no mapping exists in configuration, add this object.
If (persistentclass = NULL ){
CFG = cfg. addclass (entityclass );
Persistentclass = cfg. getclassmapping (entityname );
}
// Obtain the name of the attribute corresponding to the object primary key
String pkname = persistentclass. getidentifierproperty (). getname ();
// Obtain the name of the primary key field of the table corresponding to the object (Do not confuse these two types.)
// String pkname = persistentclass. gettable (). getprimarykey (). getcolumn (0). getname ();
System. Out. println (pkname );
Try {
String querystring = "from" + entityname + "m where M ."
+ Pkname + "in (: entityids )";
If (entityids. Length = 1 ){
Querystring = "from" + entityclass. getname () + "e where E." + pkname + "=: entityid ";
}
Final string exehql = querystring;
Return super.gethibernatetemplate(cmd.exe cutefind (New hibernatecallback (){
Public object doinhibernate (session)
Throws hibernateexception, sqlexception {
Query query = session. createquery (exehql );
If (entityids. Length = 1 ){
Query = query. setparameter ("entityid", entityids [0]);
} Else {
Query = query. setparameterlist ("entityids", entityids );
}
Return query. List ();
}
});
} Catch (runtimeexception re ){
Throw re;
}
}