简体   繁体   中英

Save ManyToMany collection with stateless session

I have:

@Entity
public class EmailAndName {
...
}

and

@Entity
public class MessageDetails {
    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "MessageDetails_to")
    public Set<EmailAndName> getTo() {
        return to;
    }
}

when I

public static void main(String []a)
{
    StatelessSession sess = HibernateUtils.getSessionFactory().openStatelessSession();
    sess.beginTransaction();
    MessageDetails messageDetails = new MessageDetails();
    messageDetails.setTo(new HashSet<EmailAndName>());
    EmailAndName emailAndName = (EmailAndName) sess.get(EmailAndName.class, 1L);
    if (emailAndName == null ) throw new RuntimeException();
    messageDetails.getTo().add(emailAndName);
    sess.insert(messageDetails);
    sess.getTransaction().commit();
}

MessageDetails_to table is not populated. What should I do? I don't want to write native queries. Thank you.

You havent read through hibernate-doc for stateless session

It clearly states that:

Operations performed using a stateless session never cascade to associated instances. Collections are ignored by a stateless session.

And you are trying to add a Set<EmailAndName> . A stateless session is a lower-level abstraction, much closer to the underlying JDBC. SO if you really want make your code work and populate MessageDetails_to.. You need to go for Session. You will need to define the equals and hashCode methods for your POJO's :)

so your modified code will be:

public static void main(String []a)
{
   try{
    Session sess = HibernateUtils.getSessionFactory().openSession();
    sess.beginTransaction();
    MessageDetails messageDetails = new MessageDetails();
    messageDetails.setTo(new HashSet<EmailAndName>());
    EmailAndName emailAndName = (EmailAndName) sess.get(EmailAndName.class, 1L);
    if (emailAndName == null ) throw new RuntimeException();
    messageDetails.getTo().add(emailAndName);
    sess.save(messageDetails);
    sess.getTransaction().commit();
 }
catch(HibernateException e)
 {
   sess.getTransaction.rollback();
   e.printStackTrace();
 }
  finally{
       sess.close();
  }

You must always have a try catch enclosed, so that you can identify the exceptions(if any) and make it work :)

First, are you sure that the transaction is commited?

Second, you are using a Set . Do you have sure that the equals and hashCode method of the EmailAndName class are well-defined?

Well, I think that the main reason your code is not working is due to the use of a stateless session, but in any case I would recommend you that when you implement 1-N and NM relationships define the inverse side of the relationship and update both sides.

In addition, don't let external classes to manipulate a set directly, because it breaks encapsulation. Don't expose a set method for your collections, it may cause very nasty exceptions hard to debug. Use an add and a remove method to update your set.

@Entity
public class MessageDetails {

    private Set<EmailAndName> to = new HashSet<EmailAndName>();

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "MessageDetails_to", 
       joinColumns = {@JoinColumn(name = "MESSAGE_DETAILS_ID"},
       inverseJoinColumns = {@JoinColumn(name = "EMAIL_AND_ADDRESS_ID")})
    public Set<EmailAndName> getTo() {
        return Collections.unmodifiableSet(to);
    }

    public void addEmaiAndName(EmailAndName emailAndName) {
       emailAndName.setMessageDetails(this);
       to.add(emailAndName);
    }

    public void removeEmailAndName(EmailAndName emailAndName) {
       emailAndName.setMessageDetails(null);
       to.remove(emailAndName);
    }

}

The other part of the code should be something like:

Session sess = HibernateUtils.getSessionFactory().openSession();
sess.beginTransaction();
MessageDetails messageDetails = new MessageDetails();
EmailAndName emailAndName = (EmailAndName) sess.get(EmailAndName.class, 1L);
if (emailAndName == null ) throw new RuntimeException();
messageDetails.addEmailAndName(emailAndName);
sess.save(messageDetails);
sess.getTransaction().commit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM