如何使用JPA / EclipseLink级联持久化

时间:2010-07-07 18:20:11

标签: mysql jpa eclipselink

我在父实体上执行级联持久操作时遇到问题。当子实体被持久化时,父实体的引用(生成的id)为null。我怎样才能让它持续正确?

实体:

@Entity
public class Contact {

        @Id @GeneratedValue(strategy=GenerationType.TABLE, generator="contact_gen")
        @TableGenerator(name="contact_gen",
            table="id_gen", pkColumnName="gen_name", 
            valueColumnName="gen_val", pkColumnValue="cont_gen")
        @Column(name="contact_id")
        private Long id;

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

        @OneToMany(mappedBy="contact", cascade=CascadeType.PERSIST)
        private List<Address> addresses = new ArrayList<Address>();

        public void addAddress(Address address) {
             addresses.add(address);
        }

        ...
}

@Entity
public class Address {

        @Id @GeneratedValue(strategy=GenerationType.TABLE, generator="address_gen")
        @TableGenerator(name="address_gen",
            table="id_gen", pkColumnName="gen_name", 
            valueColumnName="gen_val", pkColumnValue="addr_gen")
        @Column(name="address_id")
        private Long id;

        @Column(name="full_address")
        private String fullAddress;

        @ManyToOne
        @JoinColumn(name="contact_id")
        private Contact contact;

        ...
}

服务:

@Stateless
public class ContactService {

    @PersistenceContext
    private EntityManager em;

    public void createContact() {   
        Contact contact = new Contact();
        contact.setName("Michael Scott");
        contact.addAddress(new Address("1725 Slough Avenue");
        em.persist(contact);        
    }

}

MySQL Tables&amp;插入:

CREATE TABLE `contact` (
  `contact_id` int(11) NOT NULL,
  `name` varchar(45) NOT NULL
  PRIMARY KEY (`contact_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `address` (
  `address_id` int(11) NOT NULL,
  `full_address` varchar(100) NOT NULL,
  `contact_id` int(11) NOT NULL,
  PRIMARY KEY (`address_id`),
  KEY `FK_ADDRESS_contact_id` (`contact_id`),
  CONSTRAINT `FK_ADDRESS_contact_id` FOREIGN KEY (`contact_id`) REFERENCES `contact` (`contact_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE id_gen (
    gen_name VARCHAR(80),
    gen_val INT,
    PRIMARY KEY (gen_name)
);
INSERT INTO id_gen (gen_name, gen_val) VALUES ('cont_gen', 0);
INSERT INTO id_gen (gen_name, gen_val) VALUES ('addr_gen', 0);

1 个答案:

答案 0 :(得分:13)

可悲的是,你没有展示addAddress的内容。由于您的关联是双向的,您是否在此方法中设置“链接的两侧”?像这样:

@Entity
public class Contact {

    ...

    @OneToMany(mappedBy="contact", cascade=CascadeType.PERSIST)
    private List<Address> addresses = new ArrayList<Address>();

    public void addToAddresses(Address address) {
        address.setContact(this);
        this.addresses.add(address);
    }
}