MyBatisPrimaryBase.java 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package jnpf.base;
  2. import com.baomidou.mybatisplus.annotation.TableField;
  3. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  4. import io.swagger.v3.oas.annotations.media.Schema;
  5. import jnpf.constant.MsgCode;
  6. import jnpf.exception.DataException;
  7. import java.lang.reflect.Field;
  8. import java.lang.reflect.ParameterizedType;
  9. import java.lang.reflect.Type;
  10. /**
  11. * 联合主键
  12. *
  13. * 门户管理单条数据,可以由平台、门户ID、系统ID 三种数据定位
  14. * 它们组合成门户管理的联合主键,此类将其看成一个主键来配合QueryWrapper使用
  15. *
  16. * @author JNPF开发平台组 YanYu
  17. * @version v3.4.8
  18. * @copyrignt 引迈信息技术有限公司
  19. * @date 2023-04-20
  20. */
  21. public abstract class MyBatisPrimaryBase<T> {
  22. {
  23. ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();
  24. Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
  25. Class<T> clz = (Class<T>)actualTypeArguments[0];
  26. try {
  27. entity = clz.getDeclaredConstructor().newInstance();
  28. } catch (Exception ignore) {}
  29. }
  30. @Schema(description = "查询器")
  31. protected QueryWrapper<T> queryWrapper = new QueryWrapper<>();
  32. private T entity;
  33. @Schema(description = "获取处理后的查询器")
  34. public QueryWrapper<T> getQuery(){
  35. try{
  36. for (Field field : this.getClass().getDeclaredFields()) {
  37. try{
  38. TableField annotation = entity.getClass().getDeclaredField(field.getName()).getAnnotation(TableField.class);
  39. String columnName;
  40. if(annotation != null) {
  41. columnName = annotation.value();
  42. }else if(field.getName().equalsIgnoreCase("id")) {
  43. columnName = "F_Id";
  44. }else if(field.getName().equalsIgnoreCase("creatorId")){
  45. columnName = "F_Creator_Id";
  46. }else {
  47. columnName = field.getName();
  48. }
  49. field.setAccessible(true);
  50. Object value = field.get(this);
  51. if(value != null) queryWrapper.eq(columnName, value);
  52. }catch (Exception ignore){}
  53. }
  54. }catch (Exception ignore){}
  55. return queryWrapper;
  56. }
  57. @Schema(description = "获取实例")
  58. public T getEntity() throws Exception {
  59. checkEntity();
  60. for (Field field : this.getClass().getDeclaredFields()) {
  61. for (Field entityField : entity.getClass().getDeclaredFields()) {
  62. if(entityField.getName().equals(field.getName())){
  63. entityField.setAccessible(true);
  64. field.setAccessible(true);
  65. entityField.set(entity, field.get(this));
  66. }
  67. }
  68. }
  69. return entity;
  70. }
  71. private void checkEntity() throws Exception{
  72. for (Field field : this.getClass().getFields()) {
  73. Object o = field.get(this);
  74. if(o == null){
  75. throw new DataException(MsgCode.DB011.get(field.getName()));
  76. }
  77. }
  78. }
  79. }