我有:
@Entity
public class EmailAndName {
...
}
和
@Entity
public class MessageDetails {
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "MessageDetails_to")
public Set<EmailAndName> getTo() {
return to;
}
}
当我
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表。我该怎么办?我不想写本机查询。谢谢。
答案 0 :(得分:5)
您尚未通读hibernate-doc无状态会话
它明确指出:
Operations performed using a stateless session never cascade to associated instances. Collections are ignored by a stateless session.
您正在尝试添加Set<EmailAndName>
。无状态会话是较低级别的抽象,更接近底层JDBC。所以如果你真的想让你的代码工作并填充MessageDetails_to ..你需要去Session。您需要为POJO定义equals和hashCode方法:)
所以修改后的代码将是:
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();
}
你必须总是附上一个try catch,这样你就可以识别异常(如果有的话)并使它工作:)
答案 1 :(得分:0)
首先,您确定交易是否已提交?
其次,您使用的是Set
。您确定equals
类的hashCode
和EmailAndName
方法定义明确吗?
答案 2 :(得分:0)
好吧,我认为你的代码不工作的主要原因是由于使用无状态会话,但无论如何我会建议你在实现1-N和NM关系时定义反向的关系并更新双方。
另外,不要让外部类直接操作集合,因为它打破了封装。不要为集合公开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);
}
}
代码的另一部分应该是:
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();