In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "Spring Data JPA mapping how to customize entity classes". In daily operation, I believe many people have doubts about how to customize entity classes in Spring Data JPA mapping. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "Spring Data JPA mapping how to customize entity classes". Next, please follow the editor to study!
Spring Data JPA Mapping Custom entity Class
This problem has been bothering me for 2 days, and it seems that it can also be solved with jpql.
Let's talk about your own function first: query oracle's recent sql execution records.
Sql is simple: [if you need to page, you need to page yourself manually, because if you use the paging tool, the first page query will not query rownum, and the second page query will query rownum. However, the parameters in the returned List must correspond to one-to-one in the entity class, so there is an uncontrollable attribute rownum, so we cannot use the Pageable input parameter interface. You need to customize the pageSize pageNum parameters]
SELECT t.SQL_ID AS SQL ID, t.SQL_TEXT AS SQL statement, t.HASH_VALUE AS complete SQL hash value, total time of t.ELAPSED_TIME AS parsing execution in microseconds, total number of t.EXECUTIONS AS execution, last time of t.LAST_ACTIVE_TIME AS execution T.CPU_TIME AS CPU execution time microseconds FROM v$sqlarea t WHERE t.PARSING_SCHEMA_NAME IN ('Clippers DBAAS') AND t.EXECUTIONS > 10 AND t.LAST_ACTIVE_TIME > TO_DATE (' 0001-01-01 01-01 01 purge 01purse 01mm, 'yyyy-MM-dd hh34:mi:ss') AND t.ELAPSED_TIME > 0 AND t.CPU_TIME > 0 ORDER BY t.EXECUTIONS DESC
But I use Spring Data JPA. This web site says that query results cannot be automatically mapped to custom entity classes. This is more painful, on the Internet to find a wheel. Go to your own Dao layer first and find out the collection array, so use List
< Object [ ] >Receive [I simplified the sql to test whether it can be successful]
@ Query (value= "SELECT\ r\ n" + "t.SQL_ID,\ r\ n" + "t.ELAPSED_TIME,\ r\ n" + "t.EXECUTIONS,\ r\ n" + "t.LAST_ACTIVE_TIME" \ r\ n "+" t.CPU_TIME\ r\ n "+" FROM\ r\ n "+" v$sqlarea t\ r\ n "+" WHERE\ r\ n "+" t.PARSING_SCHEMA_NAME IN ('compressed DBAAS') AND t.EXECUTIONS > 100\ r\ n "+" ORDER BY\ r\ n "+" t.EXECUTIONS DESC ", nativeQuery=true) public List findTopSQLS4 ()
Then there is the entity class: note that the entity class must contain a constructor, and the parameters in the constructor must be in the same order as the parameters queried in your SQL
Package com.befery.oams.entity; import java.io.Serializable;import java.math.BigInteger;import java.security.Timestimport java.util.Date; import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.Table; @ Entity@Table (name = "v$sqlarea") public class V$sqlarea implements Serializable {@ Id private String sqlId; private Number elapsedTime; / / parsing + Total sql execution time microseconds private Number executions; / / number of execution private Date lastActiveTime; private Number cpuTime Public String getSqlId () {return sqlId;} public void setSqlId (String sqlId) {this.sqlId = sqlId;} public Number getElapsedTime () {return elapsedTime;} public void setElapsedTime (Number elapsedTime) {this.elapsedTime = elapsedTime;} public Number getExecutions () {return executions;} public void setExecutions (Number executions) {this.executions = executions;} public Date getLastActiveTime () {return lastActiveTime;} public void setLastActiveTime (Date lastActiveTime) {this.lastActiveTime = lastActiveTime } public Number getCpuTime () {return cpuTime;} public void setCpuTime (Number cpuTime) {this.cpuTime = cpuTime;} public V$sqlarea () {} public V$sqlarea (String sqlId, Number elapsedTime, Number executions, Date lastActiveTime,Number cpuTime) {this.sqlId = sqlId; this.elapsedTime = elapsedTime; this.executions = executions; this.lastActiveTime = lastActiveTime; this.cpuTime = cpuTime;}}
And then there are the wheels on the Internet.
Package com.befery.oams.util; import org.slf4j.Logger;import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; public class EntityUtils {private static Logger logger = LoggerFactory.getLogger (EntityUtils.class) / * convert array data to entity classes * the order of array elements here must be the same as the order of attributes in the entity class constructor * * @ param list array object collection * @ param clazz entity classes * @ param entity classes * @ param model Instantiated entity class * @ return entity class collection * / public static List castEntity (List list Class clazz, Object model) {List returnList = new ArrayList () If (list.isEmpty ()) {return returnList;} / / gets the number of elements in each array collection Object [] co = list.get (0); / / gets the attribute name, attribute value, attribute category List attributeInfoList = getFiledsInfo (model) of the current entity class / / create an attribute category array Class [] c2 = new Class [attributeInfoList.size ()]; / / error if (attributeInfoList.size ()! = co.length) {return returnList;} / / determine the constructor for (int I = 0; I) if the number of elements in the array collection is inconsistent with the number of attributes of the entity class.
< attributeInfoList.size(); i++) { c2[i] = (Class) attributeInfoList.get(i).get("type"); } try { for (Object[] o : list) { Constructor constructor = clazz.getConstructor(c2); returnList.add(constructor.newInstance(o)); } } catch (Exception ex) { logger.error("实体数据转化为实体类发生异常:异常信息:{}", ex.getMessage()); return returnList; } return returnList; } /** * 根据属性名获取属性值 * * @param fieldName 属性名 * @param modle 实体类 * @return 属性值 */ private static Object getFieldValueByName(String fieldName, Object modle) { try { String firstLetter = fieldName.substring(0, 1).toUpperCase(); String getter = "get" + firstLetter + fieldName.substring(1); Method method = modle.getClass().getMethod(getter, new Class[]{}); Object value = method.invoke(modle, new Object[]{}); return value; } catch (Exception e) { return null; } } /** * 获取属性类型(type),属性名(name),属性值(value)的map组成的list * * @param model 实体类 * @return list集合 */ private static List getFiledsInfo(Object model) { Field[] fields = model.getClass().getDeclaredFields(); List list = new ArrayList(fields.length); Map infoMap = null; for (int i = 0; i < fields.length; i++) { infoMap = new HashMap(3); infoMap.put("type", fields[i].getType()); infoMap.put("name", fields[i].getName()); infoMap.put("value", getFieldValueByName(fields[i].getName(), model)); list.add(infoMap); } return list; }} 最后的操作,调用 castEntity() 方法: @GetMapping(value = "/list") @ResponseBody public List selectTopSQLUntreated() { System.out.println("============================TOPSQL START================================="); List list = v$sqlareaDao.findTopSQLS4(); List list1 =EntityUtils.castEntity(list, V$sqlarea.class,new V$sqlarea()); System.out.println("============================TOPSQL END================================="); return list1; } 看一下日志的输出 ============================TOPSQL START================================= Hibernate: SELECT t.SQL_ID, t.ELAPSED_TIME, t.EXECUTIONS, t.LAST_ACTIVE_TIME, t.CPU_TIME FROM v$sqlarea t WHERE t.PARSING_SCHEMA_NAME IN ( 'C##DBAAS' ) AND t.EXECUTIONS >one hundred
ORDER BY
T.EXECUTIONS DESC
= = TOPSQL END==
2019-03-12 18 com.befery.oams.config.LogAspectConfig 06 INFO 57.108 21076-[nio-8081-exec-7] com.befery.oams.config.LogAspectConfig:-return content-
2019-03-12 18 cpuTime 06com.befery.oams.config.LogAspectConfig INFO 21076-[nio-8081-exec-7] com.befery.oams.config.LogAspectConfig: Response content: [{"cpuTime": 84731, "elapsedTime": 183491, "executions": 348," lastActiveTime ": 1552385204000," sqlId ":" f05fn7j6rbcsj "}, {" cpuTime ": 17827,33036," executions ": 212," lastActiveTime ": 1552385203000," sqlId ":" avc1jqzz04wpr "}, {" cpuTime ": 9054," elapsedTime ": 23874," executions ": 174,174 "lastActiveTime": 1552385204000, "sqlId": "b4xr1nw5vtk2v"}, {"cpuTime": 102017, "elapsedTime": 97842, "executions": 1552313331000, "sqlId": "711b9thj3s4ug"}, {"cpuTime": 89011, "elapsedTime": 90341, "executions": 153, "lastActiveTime": 1552313331000, "sqlId": "grqh2qs9ajypn"}, {"cpuTime": 58984," elapsedTime ": 81214,135," lastActiveTime ": 1552385214000," sqlId ":" d442vk7001fvw "}, {" cpuTime ": 172604818," elapsedTime ": 41375561059 "executions": 122, "lastActiveTime": 1552297847000, "sqlId": "170am4cyckruf"}, {"cpuTime": 13194, "elapsedTime": 31267, "executions": 31267, "lastActiveTime": 1552383540000, "sqlId": "9q00dg3n0748y"}]
2019-03-12 18 com.befery.oams.config.LogAspectConfig 06 INFO 57.114 21076-[nio-8081-exec-7] com.befery.oams.config.LogAspectConfig:-return content-
Example of JPA configuration class entity mapping
A: two examples
/ * * @ author xiaofanku@live.cn * / @ Entity@Table (name= "apo_config") public class SiteConfig implements Serializable {@ Id @ GeneratedValue (strategy = GenerationType.IDENTITY) private Long ID; private String caption; @ ElementCollection (fetch = FetchType.LAZY) @ MapKeyColumn (name= "name") @ Column (name= "value") @ CollectionTable (name= "apo_config_attributes", joinColumns=@JoinColumn (name= "ca_id") private Map attributes = new HashMap () / / GET/SET}
Test code
@ Test public void test () {SiteConfig sc=new SiteConfig (); sc.setID (1L); sc.setCaption (Global configuration); Map data=new HashMap (); data.put ("site", "csdn.net"); data.put ("account", "xiaofanku"); sc.setAttributes (data); siteConfigDao.save (sc) @ Test public void getConfig () {SiteConfig config=siteConfigDao.findOne (1L); assertEquals (config.getAttributes () .get ("site"), "csdn.net");}
Apo_config: table structure
Apo_config_attributes: table structure
B: three examples
/ * @ author xiaofanku@live.cn * / @ Entity@Table (name= "apo_config") public class SiteConfig implements Serializable {@ Id @ GeneratedValue (strategy = GenerationType.IDENTITY) private Long ID; private String caption; @ OneToMany (cascade=CascadeType.ALL, orphanRemoval = true) @ MapKey (name= "name") @ JoinTable (name= "apo_config_attributes") private Map attributes=new HashMap () / / GET/SET} / * * @ author xiaofanku@live.cn * / @ Entity@Table (name= "apo_attributes") public class ConfigAttribute implements Serializable {@ Id @ GeneratedValue (strategy = GenerationType.IDENTITY) private Long ID; @ Column (name= "name") private String name; private String value; / / GET/SET}
Test code
@ Test @ Ignore public void test () {SiteConfig sc=new SiteConfig (); sc.setID (1L); sc.setCaption (Global configuration); Map data=new HashMap (); ConfigAttribute ca1=new ConfigAttribute (); ca1.setName ("site"); ca1.setValue ("csdn.net"); data.put ("site", ca1); ConfigAttribute ca2=new ConfigAttribute (); ca2.setName ("account") Ca2.setValue ("xiaofanku"); data.put ("account", ca2); sc.setAttributes (data); siteConfigDao.save (sc);} @ Test @ Ignore public void getConfig () {SiteConfig config=siteConfigDao.findOne (1L); assertEquals (config.getAttributes (). Get ("site"). GetValue (), "csdn.net");}
Apo_config: table structure
Apo_attributes: table structure
Apo_config_attributes: intermediate table structure
C: use ASF Commons BeanUtils to construct a Dynamic Class
Import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Set;import org.apache.commons.beanutils.BasicDynaClass;import org.apache.commons.beanutils.ConvertUtils;import org.apache.commons.beanutils.DynaBean;import org.apache.commons.beanutils.DynaProperty;/** * uses Commons Beanutils to implement dynamic classes * @ author xiaofanku@live.cn * @ since 20171024 * / public class DynamicClass {private final DynaBean config / * construct a running type * @ param attributeMeta key attribute name, where value is the type of attribute name, for example: java.lang.Boolean * @ throws IllegalAccessException * @ throws InstantiationException * @ throws ClassNotFoundException * / public DynamicClass (Map attributeMeta) throws IllegalAccessException, InstantiationException, ClassNotFoundException {DynaProperty [] props=covert (attributeMeta) .toArray (new DynaProperty [] {}); BasicDynaClass dynaClass = new BasicDynaClass ("CustomConfig", null, props) This.config = dynaClass.newInstance ();} / * construct a running type * @ param attributes * @ throws ClassNotFoundException * @ throws InstantiationException * / public DynamicClass (Set attributes) throws ClassNotFoundException, IllegalAccessException, InstantiationException {DynaProperty [] props=covert (attributes) .toArray (new DynaProperty [] {}); BasicDynaClass dynaClass = new BasicDynaClass ("CustomConfig", null, props) This.config = dynaClass.newInstance (); load (attributes);} / * * get the attribute value * @ param attributeName attribute name * @ return * / public Object getValue (String attributeName) {return config.get (attributeName) } / * get the attribute value * @ param attributeName attribute name * @ param classType attribute type * @ param * @ return * @ throws java.lang.ClassCastException * / public T getValue (String attributeName, Class classType) throws java.lang.ClassCastException {return (T) getValue (attributeName) } / * set property * @ param attributeName attribute name * @ param attributeValue attribute value * / public void setValue (String attributeName, String attributeValue) {DynaProperty dp = config.getDynaClass () .getDynaProperty (attributeName); config.set (attributeName, ConvertUtils.convert (attributeValue, dp.getType () } / * set property * @ param attribute property instance * @ throws ClassNotFoundException * / public void setValue (Attribute attribute) throws ClassNotFoundException {config.set (attribute.getName (), ConvertUtils.convert (attribute.getValue (), Class.forName (attribute.getClassName () } / * load the attribute collection and populate the dynamic class instance * @ param attributes * / private void load (Set attributes) {for (Attribute attr: attributes) {try {config.set (attr.getName (), ConvertUtils.convert (attr.getValue (), Class.forName (attr.getClassName () } catch (ClassNotFoundException e) {} / * returns a DynaProperty list * @ param attributes * @ return * @ throws ClassNotFoundException * / private List covert (Set attributes) throws ClassNotFoundException {List attres=new ArrayList () For (Attribute attr: attributes) {attres.add (new DynaProperty (attr.getName (), Class.forName (attr.getClassName ();} return attres } / * returns a DynaProperty list * @ param attributeMeta key attribute name. Value is the type of attribute name, for example: java.lang.Boolean * @ return * @ throws ClassNotFoundException * / private List covert (Map attributeMeta) throws ClassNotFoundException {List properties=new ArrayList (); Set attrSet=attributeMeta.keySet (); for (String attrName: attrSet) {String className=attributeMeta.get (attrName) Properties.add (new DynaProperty (attrName, Class.forName (className));} return properties } public static enum Type {BOOLEAN ("java.lang.Boolean"), INTEGER ("java.lang.Integer"), LONG ("java.lang.Long"), STRING ("java.lang.String"), CHAR ("java.lang.Character"), DOUBLE ("java.lang.Double"), FLOAT ("java.lang.Float"); private final String name Private Type (String className) {this.name=className;} public String getName () {return name;}} public static class Attribute {/ / attribute name, for example: value of show private final String name; / / attribute name, example: "true" private final String value / / the type of the attribute name, for example: java.lang.Boolean private final String className; public Attribute (String name, String value, String className) {this.name = name; this.value = value; this.className = className;} public String getName () {return name;} public String getValue () {return value } public String getClassName () {return className;} @ Override public int hashCode () {int hash = 5; hash = 97 * hash + Objects.hashCode (this.name); hash = 97 * hash + Objects.hashCode (this.className); return hash } @ Override public boolean equals (Object obj) {if (this = = obj) {return true;} if (obj = = null) {return false;} if (getClass ()! = obj.getClass ()) {return false } final Attribute other = (Attribute) obj; if (! Objects.equals (this.name, other.name)) {return false;} if (! Objects.equals (this.className, other.className)) {return false;} return true;}}
Test the code:
Test public void test () {Set sas=new HashSet (); sas.add (new Attribute ("logo", "logo.png", DynamicClass.Type.STRING.getName ()); sas.add (new Attribute ("pageSize", "50", DynamicClass.Type.INTEGER.getName ()); sas.add (new Attribute ("shortcut", "true", DynamicClass.Type.BOOLEAN.getName () Try {DynamicClass dc=new DynamicClass (sas); Integer ps = dc.getValue ("pageSize", Integer.class); System.out.println (ps); dc.setValue ("pageSize", "150th"); System.out.println (dc.getValue ("pageSize"));} catch (Exception e) {e.printStackTrace () } @ Test @ Ignore public void base () {Map am = new HashMap (); am.put ("logo", DynamicClass.Type.STRING.getName ()); am.put ("pageSize", DynamicClass.Type.INTEGER.getName ()); am.put ("shortcut", DynamicClass.Type.BOOLEAN.getName ()); try {DynamicClass dc = new DynamicClass (am) Dc.setValue ("pageSize", "150th"); System.out.println (dc.getValue ("pageSize")); dc.setValue (new Attribute ("shortcut", "true", DynamicClass.Type.BOOLEAN.getName ()); System.out.println (dc.getValue ("shortcut")) } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}} at this point, the study on "how to customize entity classes by Spring Data JPA mapping" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.