I'm using Spring with Hibernate as a JPA provider and are trying to get a @OneToMany (a contact having many phonenumbers) to save the foreign key in the phone numbers table. From my form i get a Contact object that have a list of Phone(numbers) in it. The Contact get persisted properly (Hibernate fetches an PK from the specified sequence). The list of Phone(numbers) also gets persisted with a correct PK, but there's no FK to the Contacts table.

我正在使用Spring with Hibernate作为JPA提供程序,并且正在尝试获取@OneToMany(具有许多phonenumbers的联系人)以将外键保存在电话号码表中。从我的表单中我得到一个Contact对象,其中包含Phone(数字)列表。 Contact得到了正确的持久化(Hibernate从指定的序列中获取PK)。电话号码(号码)也会以正确的PK保留,但联系人表格中没有FK。

public class Contact implements Serializable {

    @OneToMany(mappedBy = "contactId", cascade = CascadeType.ALL, fetch=FetchType.EAGER)
    private List<Phone> phoneList;

}

public class Phone implements Serializable {

    @JoinColumn(name = "contact_id", referencedColumnName = "contact_id")
    @ManyToOne
    private Contact contactId;

}

@Repository("contactDao")
@Transactional(readOnly = true)
public class ContactDaoImpl implements ContactDao {

    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void save(Contact c) {
        em.persist(c);
        em.flush();
    }
}


@Controller
public class ContactController {
    @RequestMapping(value = "/contact/new", method = RequestMethod.POST)
    public ModelAndView newContact(Contact c) {
        ModelAndView mv = new ModelAndView("contactForm");
        contactDao.save(c);
        mv.addObject("contact", c);
        return mv;
    }
}

Hopefully I got all of the relevant bits above, otherwise please let me know.

希望我得到上面的所有相关内容,否则请告诉我。

4 个解决方案

#1


You have to manage the Java relationships yourself. For this kind of thing you need something like:

您必须自己管理Java关系。对于这种事情你需要这样的东西:

@Entity
public class Contact {
  @Id
  private Long id;

  @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "contact")
  private List<Phone> phoneNumbers;

  public void addPhone(PhoneNumber phone) {
     if (phone != null) {
        if (phoneNumbers == null) {
            phoneNumbers = new ArrayList<Phone>();          
        }
        phoneNumbers.add(phone);
        phone.setContact(this);
     }
  }

  ...
}

@Entity
public class PhoneNumber {
  @Id
  private Long id;

  @ManyToOne
  private Contact contact;

  ...
}

更多相关文章

  1. 字体图标的引入和通过媒体查询改变导航样式
  2. HTML样式和常用选择器
  3. 字体图标的引用和自定义样式/媒体查询的使用
  4. 数据库的CURD操作、PDO本质与原理的学习
  5. CSS之伪类选择器和简单盒子简单案例
  6. 伪类选择器与盒模型常用属性
  7. 伪类选择器-结构伪类、根据位置选择匹配
  8. 7.4——常用标签与应用场景之表格与单元格
  9. css伪类选择器和盒模型

随机推荐

  1. IE 10和11中的灰度?
  2. 如何让代码等待好/取消按钮选择?
  3. jquery刷新iframe页面的方法
  4. jQuery - 加载gif的延迟显示
  5. 使用类似$(“。someClass”)的JQuery确定元
  6. jquery和jsDom的区别和转换
  7. jQuery 基础 (笔记源于runoob)
  8. Struts2 使用Jquery+ajax 文件上传
  9. 推荐web 前端代码的编辑分享平台——RunJ
  10. JQuery标签输入插件ASP.NET不工作