em.getTransaction()。commit();使用JPA @Embeddable注释

时间:2013-08-02 05:28:17

标签: jpa embeddable

我在JAVA JPA中遇到@Embeddable问题。 我有一个名为“Author”的实体类:

@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类:

@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();       

    }
}

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

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

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

1 个答案:

答案 0 :(得分:1)

Embeddable的目标是将对象(Address)的字段存储在与实体表(Author - > author)相同的表中。

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