Vamos a crear varias entidades. Como ahora hay movida con las elecciones locales, vamos a crear una tabla de partidos políticos.
package org.ximodante.entities.elections; import java.io.Serializable; import javax.persistence.*; /** * Entity implementation class for Entity: party * */ @Entity @Table(name = "elecparty") 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; } }
package org.ximodante.test; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.ximodante.entities.elections.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("Derby-v11"); 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(); } }
Y podemos comprobar que:
- Se ha creado la BBDD base01
- Se ha creado nuestro esquema USER
- Se ha creado la tabla ELECPARTY
- Se han dado de altas los 6 partidos políticos.
Si queremos podemos decirle que cree el esquema si en la anotación de la tabla se lo decimos con
@Table (name = "elecparty", schema="myschema")