1

I have two entities parent and child:
Group_Email_History.java(Parent)

@Entity
@Table(name = "Group_Email_History")
public class Group_Email_History implements Serializable, Cloneable{

@Id
@GeneratedValue()
@Column(name = "ID")
private Integer id;

@ManyToOne
@JoinColumn(name = "GroupId", nullable = false)
private Groups groups;

@OneToMany(cascade=CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name="GROUP_EMAIL_HISTORY_ID",nullable=true)
@JsonIgnore
private Set<AttachmentInfo> attachmentInfo = new HashSet<AttachmentInfo>(0);



@ManyToOne
@JoinColumn(name = "UserId", nullable = false)
private Users users;

@NotEmpty

@Column(name = "EmailId")
private String emailId;

@Column(name = "Subject")
private String subject;

@Column(name = "EmailText")
private String emailText;
@NotEmpty

@Column(name = "EmailSentDate")
private String emailSentDate;

@Column(name = "isEmailSent")
private boolean isEmailSent;


@Transient
private String attachedFileName;

@Transient
private List<MultipartFile> alist;
//setters and getters  

AttachmentInfo.java(child) :

@Entity
@Table(name="AttachmentInfo")
public class AttachmentInfo implements Serializable{
/**
 * 
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Integer attachment_Id;

@Column(name="attachedFileName")
private String attachedFileName;

@Column(name="attachedFileSize")
private Long attachedFileSize;

@Column(name="attachedFile")
@Lob
private byte[] attachedFile;


@Column(name="attachedFileType")
private String attachedFileType;


@Transient
private String attachedFilePath;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "UserId", nullable = false)
private Users users;



@ManyToOne(fetch=FetchType.EAGER,cascade = CascadeType.ALL)
@JoinColumn(name = "GROUP_EMAIL_HISTORY_ID",nullable=true,insertable=false,updatable=false)
private Group_Email_History group_Email_History;


@ManyToOne(fetch=FetchType.EAGER,cascade = CascadeType.ALL)
@JoinColumn(name = "SCHEDULE_ID",nullable=true)
private Schedule_Email schedule_Email;

now i am saving Parent entity..it will also saving child entity by calling :

sessionFactory.getCurrentSession().save(parent);

after calling above save(), the console is :

i am saving multiple attachments in attachment table..
BUT the problem is the attachment table having groupemailhisory table primarykey like :

attachment_id    group_email_history_id    ........
1                            1             ........etc  

first it is updating group_email_history_id to 1.
after that save() is calling and updating group_email_history_id value to latest value available in Object. i.e

attachment_id    group_email_history_id    ........  
1                         2                ........
2                         2                ........

Note : it is happening for if multiple group_email_history_id's are saving in group_Email_History table within one save()..
how to resolv this problem? please help me.....

my controller code is :

@RequestMapping(value= "/groupEmail",method = RequestMethod.POST)
public String doGroupEmail(@ModelAttribute("email") @Valid  Group_Email_History email,BindingResult result) {
  try{
    //date object creation
    Date date = new Date();
    //formating the date
    SimpleDateFormat df2 = new SimpleDateFormat("dd/MMM/yyyy HH:mm");
    String formattedDate = df2.format(date);
    email.setEmailSentDate(formattedDate);

    HashSet<AttachmentInfo> hs = new HashSet<AttachmentInfo>();

    List<MultipartFile> alist = files;

    long size =0;






    // creates Mime message Object
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper messageHelper = new MimeMessageHelper(message, true,"UTF-8");

    messageHelper.setSubject(email.getSubject());
    messageHelper.setText(email.getEmailText());

    String[] emailids = email.getEmailId().split(",");

    //iterating for mail Ids
    for(MultipartFile mpf : alist){
        final MultipartFile mp = mpf;
        size+=mp.getSize();

         InputStreamSource iss = new InputStreamSource() {
             @Override
             public InputStream getInputStream() throws IOException {
                 // provide fresh InputStream
                 return mp.getInputStream();
             }
         };
         messageHelper.addAttachment(mp.getOriginalFilename(), iss);
    }
    for(String mailid : emailids)
    {

        if(mailid != ""){
            final Integer userid = iGroupEmailService.getUserId(mailid);

            for(MultipartFile mpf : alist){
                final MultipartFile mp = mpf;
                size+=mp.getSize();


                hs.add(new AttachmentInfo(){

                {
                    setAttachedFile(mp.getBytes());
                    setAttachedFileName(mp.getOriginalFilename());
                    setAttachedFileSize(mp.getSize());
                    setAttachedFileType(mp.getContentType());
                    setUsers(new Users(){{
                        setUserId(userid);
                    }});

                }});
            }
            email.setAttachmentInfo(hs);
        Group_Email_History  email2 = (Group_Email_History)email.clone();
        email2.setEmailId(mailid);
        email2.setUsers(new Users(){{
            setUserId(userid);
        }});

        iGroupEmailService.saveEmailSendingInformation(email2);

        messageHelper.setTo(mailid);
     // sends the e-mail
        mailSender.send(message);
        }

    }
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

0

First of all, I find it really problematic to understand your post. What I have understand, though, is that you are having some troubles with unwanted update statements. You should try changing this part:

@OneToMany(cascade=CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name="GROUP_EMAIL_HISTORY_ID",nullable=true)
@JsonIgnore
private Set<AttachmentInfo> attachmentInfo = new HashSet<AttachmentInfo>(0);

into this:

@OneToMany(mappedBy = group_Email_History, cascade=CascadeType.ALL,
           fetch = FetchType.EAGER)
@JsonIgnore
private Set<AttachmentInfo> attachmentInfo = new HashSet<AttachmentInfo>(0);

And, accordingly, on the Child Entity, your code should look like this:

@ManyToOne(fetch=FetchType.EAGER,cascade = CascadeType.ALL)
@JoinColumn(name = "GROUP_EMAIL_HISTORY_ID",nullable=true)
private Group_Email_History group_Email_History;

It is common for @ManyToOne to be the owner of the relationship and is annotated with @JoinColumn. Hence, @OneToMany gets mappedBy attribute. Read more here.

Your code responsible for persisting should look like this:

attachmentInfo.add(attachement1);
attachmentInfo.add(attachement2);
group_Email_History.setAttachementInfo(attachmentInfo);
attachement1.setGroup_Email_History(group_Email_History);
attachement2.setGroup_Email_History(group_Email_History);
...
sessionFactory.getCurrentSession().save(group_Email_History);

EDIT: Try changing this part:

hs.add(new AttachmentInfo(){
{
    //you need to set Group_Email_History object 
    //to every AttachmentInfo Object as well
    setGroup_Email_History(email);

    setAttachedFile(mp.getBytes());
    setAttachedFileName(mp.getOriginalFilename());
    setAttachedFileSize(mp.getSize());
    setAttachedFileType(mp.getContentType());
    setUsers(new Users(){{
    setUserId(userid);
}});
}});
Community
  • 1
  • 1
mmalik
  • 185
  • 2
  • 11
  • it is not saving forignkey in child table... GROUP_EMAIL_HISTORY_ID is always saving null. – Tatisetti Ramanjaneyulu Jun 29 '15 at 06:19
  • Did you check out my suggestion, especially thle last part? It seems to me that you may be trying to persist group_Email_History object that has attachmentInfos collection set properly, but the attachmentInfo objects don't have the group_Email_History set. Could you post that part of your code? – mmalik Jun 29 '15 at 08:04
  • yes, attachmentInfo is HashSet type.. i am adding this hashset to Group_Email_History object. – Tatisetti Ramanjaneyulu Jun 29 '15 at 10:05
  • I know, but does every entity in this HashSet has Group_Email_History object assigned? They should point to the same object, specifically to the one that has the HashSet assigned to itself. – mmalik Jun 29 '15 at 10:11
  • may i know your skype id...by that i will show exact code – Tatisetti Ramanjaneyulu Jun 29 '15 at 10:38
  • For the consistency of your question, It would be better if you post the code here. I mean, just edit your post. – mmalik Jun 29 '15 at 10:40
  • no luck. i got exception userId cant be null. it is trying to insert 2 querys in Group_Email_History. for second query it is getting that exception – Tatisetti Ramanjaneyulu Jun 29 '15 at 11:43