Para ello se especificaran 2 clases:
- src.main.java,org,ximodante.entities.Party
- src.main.java,org,ximodante.persistence.testEntityManager
package src.main.java.org.ximodante.entities; import java.io.Serializable; import javax.persistence.*; /** * Entity implementation class for Entity: party * */ @Entity @Table(name = "elecparty", schema="myschema") public class Party implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "initial") private String initial; @Column(name = "name") private String name; public Party() { super(); } // Autogenerated getters and setters public Party(String initial, String name) { super(); this.initial = initial; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getInitial() { return initial; } public void setInitial(String initial) { this.initial = initial; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static long getSerialversionuid() { return serialVersionUID; } }
Ahora vamos a crear la calse manejadora de persistencia
package src.main.java,org.ximodante.persistence; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import src.main.java.org.ximodante.entities.Party; public class testEntityManager { /** * @param args */ EntityManagerFactory emf = null; EntityManager em = null; public static void main(String[] args) { // TODO Auto-generated method stub EntityManagerFactory emf = Persistence.createEntityManagerFactory("postgres"); EntityManager em = emf.createEntityManager(); persistSomeData(em); em.close(); emf.close(); } private static void persistSomeData (EntityManager em ) { em.getTransaction().begin(); em.persist (new Party("PSPV-PSOE","Partit Socialista del Pais Valencià")); em.persist (new Party("PP" ,"Partit Popular")); em.persist (new Party("EUPV" ,"Esquerra Unida del Pais Valencià")); em.persist (new Party("UPyD" ,"Unión Progreso y Democracia")); em.persist (new Party("Bloc" ,"Compromis Bloc")); em.persist (new Party("ERC" ,"Esquerra Republicana de Catalunya")); em.getTransaction().commit(); } }
Si ejecutamos podemos comprobar que:
- Si la BBDD o el esquema no están creado en Postgres, entonce da error. Por tanto las BBDD y los esquemas si se utilizan, se deben crear previamente.
- Se creará la tabla elecparty dentro del esquema myschema.