`
sunxboy
  • 浏览: 2877469 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Cascade Save for spring mongo data

 
阅读更多

1. we have some entities like below:

    AlarmLogs.java

package com.eifesun.monitor.web.model;

import static com.eifesun.monitor.DeviceType.fromValue;
import static com.eifesun.monitor.inverter.power20k.ErrorCode.getType;
import static org.joda.time.DateTime.now;

import java.util.Date;

import org.bson.types.ObjectId;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.joda.time.PeriodType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.annotation.Transient;
import org.springframework.data.annotation.Version;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;

import com.eifesun.monitor.DeviceType;
import com.eifesun.monitor.util.Helper;
import com.eifesun.monitor.web.model.mongodb.CascadeSave;

@Document(collection = "alarm_logs")
public class AlarmLogs {
    @Id
    private ObjectId id;
    @Version
    private Long version;
    @DateTimeFormat(iso = ISO.DATE_TIME)
    private Date alarmDate;
    private String deviceType;
    private String clientId;
    private String errorType;
    private int errorValue;

    @CreatedDate
    private DateTime createdDate;
    @LastModifiedDate
    private DateTime lastModifiedDate;

    @DBRef
    @CascadeSave
    private AlarmDetails alarmDetails;

    @Transient
    private static final String DATE_PARTEN = "MM/dd/yyyy HH:mm";

    public AlarmLogs() {
    }

    public AlarmLogs(DeviceType deviceType, String clientId, String errorType, int errorValue) {
        this.deviceType = deviceType.toValue();
        this.clientId = clientId;
        this.errorType = errorType;
        this.errorValue = errorValue;
        this.alarmDate = now().toDate();
    }

    public String getCreatedDate() {
        return createdDate.toString(DATE_PARTEN);
    }

    public String getAlarmRemainedTime() {
        Interval interval = new Interval(createdDate.getMillis(), createdDate.getMillis());
        DateTime start = this.version > 0 ? lastModifiedDate : now();
        interval.withEndMillis(start.getMillis());
        return Helper.FORMATTER.print(interval.toPeriod(PeriodType.yearMonthDayTime()));
    }

    public ObjectId getId() {
        return id;
    }

    public String getDeviceType() {
        return fromValue(deviceType).toDisplay();
    }

    public String getErrorMessage() {
        return getType(errorType).getDescription(errorValue);
    }

    public String getErrorType() {
        return errorType;
    }

    public int getErrorValue() {
        return errorValue;
    }

    public String getClientId() {
        return clientId;
    }

    public AlarmDetails getAlarmDetails() {
        return alarmDetails;
    }

    public void setAlarmDetails(AlarmDetails alarmDetails) {
        this.alarmDetails = alarmDetails;
    }

    public Long getVersion() {
        return version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public DateTime getLastModifiedDate() {
        return lastModifiedDate;
    }

}

 

   AlarmDetails.java

package com.eifesun.monitor.web.model;

import org.bson.types.ObjectId;
import org.joda.time.DateTime;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "alarm_details")
public class AlarmDetails {
    @Id
    private ObjectId id;
    private int panel1Power;
    private int panel2Power;
    private int panel1Current;
    private int panel2Current;
    private int panel1Voltage;
    private int panel2Voltage;
    private int outputPower;
    private int lineRAC;
    private int lineRV;
    private int lineSAC;
    private int lineSV;
    private int lineTAC;
    private int lineTV;
    private int gridFrequence;
    private int statusCode;
    private int boxTemperature;
    private int igbtTemperature;
    private int workingHour;
    @CreatedDate
    protected DateTime createdDate;

    public AlarmDetails() {
    }

    public int getPanel1Power() {
        return panel1Power;
    }

    public void setPanel1Power(int panel1Power) {
        this.panel1Power = panel1Power;
    }

    public int getPanel2Power() {
        return panel2Power;
    }

    public void setPanel2Power(int panel2Power) {
        this.panel2Power = panel2Power;
    }

    public int getPanel1Current() {
        return panel1Current;
    }

    public void setPanel1Current(int panel1Current) {
        this.panel1Current = panel1Current;
    }

    public int getPanel2Current() {
        return panel2Current;
    }

    public void setPanel2Current(int panel2Current) {
        this.panel2Current = panel2Current;
    }

    public int getPanel1Voltage() {
        return panel1Voltage;
    }

    public void setPanel1Voltage(int panel1Voltage) {
        this.panel1Voltage = panel1Voltage;
    }

    public int getPanel2Voltage() {
        return panel2Voltage;
    }

    public void setPanel2Voltage(int panel2Voltage) {
        this.panel2Voltage = panel2Voltage;
    }

    public int getOutputPower() {
        return outputPower;
    }

    public void setOutputPower(int outputPower) {
        this.outputPower = outputPower;
    }

    public int getLineRAC() {
        return lineRAC;
    }

    public void setLineRAC(int lineRAC) {
        this.lineRAC = lineRAC;
    }

    public int getLineRV() {
        return lineRV;
    }

    public void setLineRV(int lineRV) {
        this.lineRV = lineRV;
    }

    public int getLineSAC() {
        return lineSAC;
    }

    public void setLineSAC(int lineSAC) {
        this.lineSAC = lineSAC;
    }

    public int getLineSV() {
        return lineSV;
    }

    public void setLineSV(int lineSV) {
        this.lineSV = lineSV;
    }

    public int getLineTAC() {
        return lineTAC;
    }

    public void setLineTAC(int lineTAC) {
        this.lineTAC = lineTAC;
    }

    public int getLineTV() {
        return lineTV;
    }

    public void setLineTV(int lineTV) {
        this.lineTV = lineTV;
    }

    public int getGridFrequence() {
        return gridFrequence;
    }

    public void setGridFrequence(int gridFrequence) {
        this.gridFrequence = gridFrequence;
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public int getBoxTemperature() {
        return boxTemperature;
    }

    public void setBoxTemperature(int boxTemperature) {
        this.boxTemperature = boxTemperature;
    }

    public int getIgbtTemperature() {
        return igbtTemperature;
    }

    public void setIgbtTemperature(int igbtTemperature) {
        this.igbtTemperature = igbtTemperature;
    }

    public int getWorkingHour() {
        return workingHour;
    }

    public void setWorkingHour(int workingHour) {
        this.workingHour = workingHour;
    }

}

 

 

2. here we create a new annotation "CascadeSave" on fields "alarmDetails".

package com.eifesun.monitor.web.model.mongodb;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface CascadeSave {

}

 

  CascadingMongoEventListener.java

package com.eifesun.monitor.web.model.mongodb;

import java.lang.reflect.Field;

import javax.inject.Inject;

import org.springframework.data.annotation.Id;
import org.springframework.data.mapping.model.MappingException;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.util.ReflectionUtils;

@SuppressWarnings("rawtypes")
public class CascadingMongoEventListener extends AbstractMongoEventListener {
    @Inject
    private MongoOperations mongoOperations;

    @Override
    public void onBeforeConvert(final Object source) {
        ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {

            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                ReflectionUtils.makeAccessible(field);

                if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(CascadeSave.class)) {
                    final Object fieldValue = field.get(source);
                    if (fieldValue == null) {
                        return;
                    }

                    DbRefFieldCallback callback = new DbRefFieldCallback();
                    ReflectionUtils.doWithFields(fieldValue.getClass(), callback);
                    if (!callback.isIdFound()) {
                        throw new MappingException("Cannot perform cascade save on child object without id set");
                    }

                    mongoOperations.save(fieldValue);
                }
            }
        });
    }

    private static class DbRefFieldCallback implements ReflectionUtils.FieldCallback {
        private boolean idFound;

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);

            if (field.isAnnotationPresent(Id.class)) {
                idFound = true;
            }
        }

        public boolean isIdFound() {
            return idFound;
        }
    }
}

 

 

 

 

分享到:
评论

相关推荐

    Spring Data MongoDB中实现自定义级联的方法详解

    在Spring Data MongoDB中,开发人员经常遇到需要处理对象间的级联操作,比如级联保存(Cascade Save)。在关系型数据库中,类似的功能可以通过ORM框架如Hibernate实现,但在NoSQL数据库如MongoDB中,这种功能需要...

    opencv的各种haarcascade.xml文件

    haarcascades\haarcascade_eye.xml haarcascades\haarcascade_eye_tree_eyeglasses.xml haarcascades\haarcascade_frontalface_alt.xml haarcascades\haarcascade_frontalface_alt2.xml haarcascades\haar...

    Spring Data JPA系列3:JPA项目中核心场景与进阶用法介绍.doc

    Spring Data JPA 是一个强大的框架,它简化了Java应用程序中对关系数据库的访问。在Spring Boot项目中,Spring Data JPA 提供了便捷的方式来进行数据持久化操作,减少了大量重复的DAO层代码。本篇文章主要关注Spring...

    CMOS Cascade Sigma-Delta Modulators for Sensors and Telecom

    文章《CMOS Cascade Sigma-Delta Modulators for Sensors and Telecom》深入探讨了如何在传感器和电信应用中使用CMOS技术实现Sigma-Delta调制器。本文中涉及的关键知识点包括: 1. Sigma-Delta调制技术原理:Sigma-...

    A Convolutional Neural Network Cascade for Face Detection

    ### 卷积神经网络级联在人脸检测中的应用 #### 摘要 本文提出了一种基于卷积神经网络(Convolutional Neural Networks, CNN)的级联结构用于解决复杂环境下面部检测的问题。该方法旨在处理真实世界场景中由于姿态...

    haarcascade

    "haarcascade"是计算机视觉领域中用于对象检测的一个经典算法,主要应用于人脸识别,但也能够检测其他特征,如眼睛和手。这个算法是基于Adaboost算法和Haar-like特征的级联分类器,最初由Paul Viola和Michael Jones...

    Learning SURF cascade for fast and accurate object detection

    本文提出了一种新颖的学习框架,用于从大规模数据集中训练基于提升级联(boosting cascade)的对象检测器。该框架源自著名的Viola-Jones (VJ)框架,但通过三项关键改进使其与众不同:采用多维SURF特征而非一维Haar...

    springdatajap.rar

    Spring Data JPA是Spring框架的一个模块,用于简化Java Persistence API(JPA)的使用,它提供了更高级别的抽象,使得数据库操作变得更加简单。这个"springdatajap.rar"压缩包包含了一个Spring Data JPA的演示项目,...

    Open CASCADE Sample Source C#

    Open CASCADE Technology(简称Open CASCADE或OCCT)是一个开源的3D建模和CAD软件开发平台,主要用于构建基于几何模型的应用程序。它提供了丰富的API,支持多种几何数据结构、建模算法以及图形显示功能。C#版本的...

    cascade7.0.rar

    Cascade 7.0是一款专为RF(射频)链路分析设计的专业软件工具,它在射频通信领域中扮演着重要角色。RF链路分析是理解、设计和优化无线通信系统的关键步骤,尤其是在射频硬件设计和系统性能评估中。这款软件通过提供...

    haarcascade_upperbody.xml

    haarcascade_upperbody.xml

    Constrained Joint Cascade Regression Framework

    Constrained Joint Cascade Regression Framework for Simultaneous Facial Action Unit Recognition and Facial Landmark Detection

    Diversity-based Cascade Filters for JPEG Steganalysis

    ### Diversity-based Cascade Filters for JPEG Steganalysis #### 概述 在数字时代,大量的多媒体数据通过各种通信渠道传输。为了实现隐蔽通信的目的,**隐写术**被用来将秘密信息不可见地嵌入到这些媒体数据中。...

    cascade-function-.rar_cascade

    在IT行业中,级联(Cascade)常常用于描述一种数据结构或功能,其中下级数据依赖于上级数据。在这个场景中,"cascade-function-.rar_cascade" 提供的是一种实现省市级联功能的Java脚本,主要用于Web开发,尤其是前端...

    Python OpenCV haarcascade模型库下载haarcascade_mcs_mouth

    for (x, y, w, h) in mouths: cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) ``` 7. **显示结果**:最后,展示处理后的图像。 ```python cv2.imshow(' Mouth Detection', image) cv2.waitKey(0) cv2...

    component cascade tool 7.0.zip

    "component cascade tool 7.0.zip" 是一个用于微波仿真分析的软件工具包,主要功能在于级联多个微波组件以评估整个系统的性能。在微波工程领域,这种工具对于设计和优化通信、雷达系统以及其他微波技术应用至关重要...

    haarcascade.zip

    OpenCV+python:人脸检测时人脸识别xml文件:haarcascade_frontalface_default.xml,haarcascade_frontalface_alt2.xml,haarcascade_eye.xml等文件下载

    haarcascade_frontalface_alt2.xml

    OpenCV安装目录中的\data\ haarcascades目录下的haarcascade_frontalface_alt.xml与haarcascade_frontalface_alt2.xml都是用来检测人脸的Haar分类器。这个haarcascades目录下还有人的全身,眼睛,嘴唇的Haar分类器。...

    haarcascade-fullbody.xml.zip

    for (x, y, w, h) in bodies: cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) ``` 6. **显示或保存结果**:你可以使用`cv2.imshow`展示图像,或者用`cv2.imwrite`保存结果。 通过以上步骤,你就...

    hibernate cascade 测试demo

    `cascade`有多种类型,包括`save-update`、`merge`、`delete`、`all`、`all-delete-orphan`等,每种类型代表不同的操作传播策略。 1. `save-update`:当你保存或更新父实体时,也会同时保存或更新所有关联的子实体...

Global site tag (gtag.js) - Google Analytics