spring JPA增量保存实体

发布于 2024-10-30 08:10:03 字数 5530 浏览 1 评论 0原文

我正在尝试逐步持久化一个实体。

这是实体类的概述


package aop.web.teacher.rmodels;
// Generated 11 Feb, 2011 3:57:41 PM by Hibernate Tools 3.2.2.GA


import java.util.Date;

import java.util.HashSet;

import java.util.Set;

import javax.persistence.CascadeType;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.FetchType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.ManyToOne;

import javax.persistence.OneToMany;

import javax.persistence.Table;

import javax.persistence.Temporal;

import javax.persistence.TemporalType;


import org.hibernate.validator.constraints.NotEmpty;

/**
 * AopTeacherMaster generated by hbm2java
 */
@Entity
@Table(name="aop_teacher_master"
    ,schema="public"
)
public class AopTeacherMaster  implements java.io.Serializable {


     private long id;
     private AopTeachersDistrictMaster aopTeachersDistrictMasterByCurrDistrict;
     private AopInstitutionmaster aopInstitutionmaster;
     private AopTeachersDistrictMaster aopTeachersDistrictMasterByPermDistrict;
     @NotEmpty(message="Fathers name is mandatory")
     private String fathersName;
     @NotEmpty
     private String currAddLine1;
     private String currAddLine21;
     private String currAddLine22;
     private String currAddLine3;
     private String currDevelopmentBlock;
     private String currPoliceStation;
     private String currCity;
     private String currPin;
     private String currState;
     private String currCountry;
     private String permAddLine1;
     private String permAddLine21;
     private String permAddLine22;
     private String permAddLine3;
     private String permDevelopmentBlock;
     private String permPoliceStation;
     private String permCity;
     private String permPin;
     private String permState;
     private String permCountry;
     private Date dateOfBirth;
     private Character gender;
     private Character maritalStatus;
     private String religion;
     private String caste;
     private String landLineNumber;
     private String mobileNumber;
     private String email;
     private String uidNum;
     private String bankName;
     private String bankBranch;
     private String bankAccountNum;
     private String gpfNum;
     private Set aopTeachersSanctionedPostDetailsForCurrentIncumbentId = new HashSet(0);
     private Set aopTeachersSanctionedPostDetailsForFirstIncumbentId = new HashSet(0);

    public AopTeacherMaster() {
    }


    public AopTeacherMaster(long id) {
        this.id = id;
    }

现在我有一个类似向导的两步流程,位于第一个屏幕中 用户输入实体的一些属性并且实体被合并, 在第二步中,填充附加或其余属性。

我正在使用基于 spring 3 注解的控制器,其中我使用实体类 作为命令对象。

第一次实体会使用屏幕一个值保存,然后我发送 来自合并的引用作为第二个屏幕的命令对象。

然而,第二个屏幕似乎填充了那里的条目,但使 来自第一个屏幕的现有属性。

这是相同的控制器代码


    @RequestMapping(value = "/insertteacher.html", method = RequestMethod.POST)
    public 
    String testEm(@Valid AopTeacherMaster teacher, BindingResult result,
            Map model) {
        logger.info("Checking Teacher for error");
        if (result.hasErrors()) {
            logger.info("User data has:" + result.getErrorCount() + " errors!");
            // ////////////////////

            for (Object object : result.getAllErrors()) {
                if (object instanceof FieldError) {
                    FieldError fieldError = (FieldError) object;

                    logger.error("Error on field::" + fieldError.getField()
                            + " || error type ::" + fieldError.getCode());
                }

            }
            model.put("smessage", "There was an error");
            return "teachersmasterInsert";
        }
        logger.info("Attemped saving!");
        teacher=schoolMasterService.add(teacher);//recieved the reference after merge! Will be used for command object in the next screen
        model.put("teacher", teacher);//This is the command object for second screen
        model.put("smessage", "teacher inserted successfully");
        return "teachersmasterInsert2";

        // List myList=testDaoService.findAllTeachers();
        // for(Teachermaster t:myList){logger.info("Got::"+t.getId());}

    }


    @RequestMapping(value = "/insertteacher2.html", method = RequestMethod.POST)
    public 
    String testEm2(@Valid AopTeacherMaster teacher, BindingResult result,
            Map model) {
        logger.info("Checking Teacher for error second insert");
        if (result.hasErrors()) {
            logger.info("User data has:" + result.getErrorCount() + " errors!");
            // ////////////////////

            for (Object object : result.getAllErrors()) {
                if (object instanceof FieldError) {
                    FieldError fieldError = (FieldError) object;

                    logger.error("Error on field::" + fieldError.getField()
                            + " || error type ::" + fieldError.getCode());
                }

            }
            model.put("smessage", "There was an error");
            return "teachersmasterInsert";
        }
        logger.info("Attemped saving!");
        teacher=schoolMasterService.add(teacher);
        model.put("teacher", teacher);
        model.put("smessage", "teacher second instance inserted successfully");
        return "teachersmasterInsert";

        // List myList=testDaoService.findAllTeachers();
        // for(Teachermaster t:myList){logger.info("Got::"+t.getId());}

    }

这是正确的方法吗?否则 我怎样才能实现这种增量保存? 请建议! 提前致谢。

I am trying to persist an entity incrementally.

Here is an overview of the Entity class


package aop.web.teacher.rmodels;
// Generated 11 Feb, 2011 3:57:41 PM by Hibernate Tools 3.2.2.GA


import java.util.Date;

import java.util.HashSet;

import java.util.Set;

import javax.persistence.CascadeType;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.FetchType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.ManyToOne;

import javax.persistence.OneToMany;

import javax.persistence.Table;

import javax.persistence.Temporal;

import javax.persistence.TemporalType;


import org.hibernate.validator.constraints.NotEmpty;

/**
 * AopTeacherMaster generated by hbm2java
 */
@Entity
@Table(name="aop_teacher_master"
    ,schema="public"
)
public class AopTeacherMaster  implements java.io.Serializable {


     private long id;
     private AopTeachersDistrictMaster aopTeachersDistrictMasterByCurrDistrict;
     private AopInstitutionmaster aopInstitutionmaster;
     private AopTeachersDistrictMaster aopTeachersDistrictMasterByPermDistrict;
     @NotEmpty(message="Fathers name is mandatory")
     private String fathersName;
     @NotEmpty
     private String currAddLine1;
     private String currAddLine21;
     private String currAddLine22;
     private String currAddLine3;
     private String currDevelopmentBlock;
     private String currPoliceStation;
     private String currCity;
     private String currPin;
     private String currState;
     private String currCountry;
     private String permAddLine1;
     private String permAddLine21;
     private String permAddLine22;
     private String permAddLine3;
     private String permDevelopmentBlock;
     private String permPoliceStation;
     private String permCity;
     private String permPin;
     private String permState;
     private String permCountry;
     private Date dateOfBirth;
     private Character gender;
     private Character maritalStatus;
     private String religion;
     private String caste;
     private String landLineNumber;
     private String mobileNumber;
     private String email;
     private String uidNum;
     private String bankName;
     private String bankBranch;
     private String bankAccountNum;
     private String gpfNum;
     private Set aopTeachersSanctionedPostDetailsForCurrentIncumbentId = new HashSet(0);
     private Set aopTeachersSanctionedPostDetailsForFirstIncumbentId = new HashSet(0);

    public AopTeacherMaster() {
    }


    public AopTeacherMaster(long id) {
        this.id = id;
    }

Now I have a 2 step wizard like process where in the first screen
user enters some of the properties of the entity and the entity gets merged,
In the second step additional or rest of the properties are filled.

I am using spring 3 annotation based controller where I am using the entity class
as the command object.

On the first go entity gets saved with screen one values then I am sending the
reference from merge as command object for second screen.

However, second screen seems to populate the entries there but nullifies the
existing properties which were from the first screen.

Here is the controller code for the same


    @RequestMapping(value = "/insertteacher.html", method = RequestMethod.POST)
    public 
    String testEm(@Valid AopTeacherMaster teacher, BindingResult result,
            Map model) {
        logger.info("Checking Teacher for error");
        if (result.hasErrors()) {
            logger.info("User data has:" + result.getErrorCount() + " errors!");
            // ////////////////////

            for (Object object : result.getAllErrors()) {
                if (object instanceof FieldError) {
                    FieldError fieldError = (FieldError) object;

                    logger.error("Error on field::" + fieldError.getField()
                            + " || error type ::" + fieldError.getCode());
                }

            }
            model.put("smessage", "There was an error");
            return "teachersmasterInsert";
        }
        logger.info("Attemped saving!");
        teacher=schoolMasterService.add(teacher);//recieved the reference after merge! Will be used for command object in the next screen
        model.put("teacher", teacher);//This is the command object for second screen
        model.put("smessage", "teacher inserted successfully");
        return "teachersmasterInsert2";

        // List myList=testDaoService.findAllTeachers();
        // for(Teachermaster t:myList){logger.info("Got::"+t.getId());}

    }


    @RequestMapping(value = "/insertteacher2.html", method = RequestMethod.POST)
    public 
    String testEm2(@Valid AopTeacherMaster teacher, BindingResult result,
            Map model) {
        logger.info("Checking Teacher for error second insert");
        if (result.hasErrors()) {
            logger.info("User data has:" + result.getErrorCount() + " errors!");
            // ////////////////////

            for (Object object : result.getAllErrors()) {
                if (object instanceof FieldError) {
                    FieldError fieldError = (FieldError) object;

                    logger.error("Error on field::" + fieldError.getField()
                            + " || error type ::" + fieldError.getCode());
                }

            }
            model.put("smessage", "There was an error");
            return "teachersmasterInsert";
        }
        logger.info("Attemped saving!");
        teacher=schoolMasterService.add(teacher);
        model.put("teacher", teacher);
        model.put("smessage", "teacher second instance inserted successfully");
        return "teachersmasterInsert";

        // List myList=testDaoService.findAllTeachers();
        // for(Teachermaster t:myList){logger.info("Got::"+t.getId());}

    }

Is this the correct way to do it? Otherwise
how can I achieve this incremental save?
Please suggest!
thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别挽留 2024-11-06 08:10:03

在基于注释的控制器中实现向导的典型方法是将部分构造的对象存储在会话中,并仅在最后一步之后保存它:

@Controller
// Model attribute with name "aopTeacherMaster" is transparently stored in the session
@SessionAttribute("aopTeacherMaster")
public class TeacherController {
    ...

    @RequestMapping(value = "/insertteacher2.html", method = RequestMethod.POST)
    public String testEm2(@Valid AopTeacherMaster teacher, BindingResult result, Map model) { 
        ...
        // No need to save teacher here
    }

    @RequestMapping(value = "/insertteacherLast.html", method = RequestMethod.POST)
    public String testEmLast(@Valid AopTeacherMaster teacher, BindingResult result, 
        Map model, SessionStatus status) { 
        ...
        // Save teacher at the last step
        teacher=schoolMasterService.add(teacher); 
        // Remove it from the session
        status.setComplete();
    }
}

或者,如果由于某种原因确实需要增量保存,则可以加载实体的当前状态从数据库中手动复制字段以及模型对象中的数据。

The typical way to implement wizards in annotation based controller is to store partially constructed object in the session, and save it only after the last step:

@Controller
// Model attribute with name "aopTeacherMaster" is transparently stored in the session
@SessionAttribute("aopTeacherMaster")
public class TeacherController {
    ...

    @RequestMapping(value = "/insertteacher2.html", method = RequestMethod.POST)
    public String testEm2(@Valid AopTeacherMaster teacher, BindingResult result, Map model) { 
        ...
        // No need to save teacher here
    }

    @RequestMapping(value = "/insertteacherLast.html", method = RequestMethod.POST)
    public String testEmLast(@Valid AopTeacherMaster teacher, BindingResult result, 
        Map model, SessionStatus status) { 
        ...
        // Save teacher at the last step
        teacher=schoolMasterService.add(teacher); 
        // Remove it from the session
        status.setComplete();
    }
}

Alternatively, if you really need incremental save for some reason, you can load the current state of the entity from the database and copy fields with data from the model object manually.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文