0

我对 JAVA JPA 中的 @Embeddable 有一些问题。我有一个名为“作者”的实体类:

@Entity

    @Table(name = "author")
    @XmlRootElement
    @NamedQueries({
        @NamedQuery(name = "Author.findAll", query = "SELECT a FROM Author a"),
       ...})


    public class Author implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @Basic(optional = false)
        @Column(name = "aID")
        private Integer aID;
        @Column(name = "aName")
        private String aName;
        @Column(name = "aSurname")
        private String aSurname;
        @Column(name = "aPhone")
        private Integer aPhone;


        @Embedded 
        @AttributeOverrides({

         @AttributeOverride(name="city",column=@Column(name="Address")),
         @AttributeOverride(name="street",column=@Column(table="Address")),
         @AttributeOverride(name="number",column=@Column(table="Address"))
         }) private Address address;

    // set and get methods.
    }

我还有一个名为“Address”的可嵌入类:

@Embeddable
    @Table(name = "Address")
    @XmlRootElement
    public class Address implements Serializable 
    {
       private static final long serialVersionUID=1L;
        @Column(name="city")
        private String city;
        @Column(name="street")
        private String street;
        @Column(name="number")
        private int number;

    // get and set methods.
}

在我的主类中,我想将此值插入数据库。(我使用 mySQL)但我在这一行遇到错误:em.getTransaction.commit();

    public class CreateAuthor extends javax.swing.JFrame {

        private static final String PERSISTENCE_UNIT_NAME = "Project";
        private static EntityManagerFactory emf;

        public void CreateAuthor() {
            initComponents();
        }


        private void ekleButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
            emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
            EntityManager em = emf.createEntityManager();


            em.getTransaction().begin();


            Author author = new Author();
            author.setAID(3);
            author.setAName("Sheldon");
            author.setASurname("Smith");
            author.setAPhone(768987);
            Address adr = new Address();



             adr.setCity("Paris");
             adr.setStreet("cinar");
             adr.setNumber(12);
             author.setAddress(adr);



            em.persist(author);

            em.getTransaction().commit();  /// error occured

            em.close();       

    }
}

在我的数据库方面,我有 Author 表 (aID(pk),aName,aSurname,aPhone)

地址表(城市、街道、号码)

你知道为什么会发生错误吗?

4

1 回答 1

1

Embeddable 的目标是将对象(地址)的字段存储在与实体表(作者->作者)相同的表中。

如果要将它们保存在另一个表中,则 Address 本身应该是一个实体,并且 Author 和 Address 之间应该存在 OneToOne 或 ManyToOne 关联。照原样,映射没有任何意义。

于 2013-08-02T05:40:45.527 回答