Example usage for javax.persistence Persistence createEntityManagerFactory

List of usage examples for javax.persistence Persistence createEntityManagerFactory

Introduction

In this page you can find the example usage for javax.persistence Persistence createEntityManagerFactory.

Prototype

public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName) 

Source Link

Document

Create and return an EntityManagerFactory for the named persistence unit.

Usage

From source file:Main.java

  public static void main(String[] a) throws Exception {
  JPAUtil util = new JPAUtil();

  EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
  EntityManager em = emf.createEntityManager();
  ProfessorService service = new ProfessorService(em);

  em.getTransaction().begin();/*www  .jav  a2s.c o  m*/

  service.findAll();
    
    
  util.checkData("select * from Professor");
  util.checkData("select * from Department");

    
  em.getTransaction().commit();
  em.close();
  emf.close();
}

From source file:es.us.isa.ideas.utilities.PopulateDatabase.java

public static void main(String[] args) {

    ApplicationContext ctx;//from  ww w. j a v  a2s .  c o m
    EntityManagerFactory emf;
    EntityManager em;
    EntityTransaction et;

    ctx = new ClassPathXmlApplicationContext("utilities/PopulateDatabase.xml");

    emf = Persistence.createEntityManagerFactory("persistenceUnit");
    em = emf.createEntityManager();
    et = em.getTransaction();

    et.begin();
    try {
        for (Entry<String, Object> entry : ctx.getBeansWithAnnotation(Entity.class).entrySet()) {
            em.persist(entry.getValue());
            System.out.println(String.format("Persisting (%s, %s@%d)", entry.getKey(),
                    entry.getValue().getClass().getName(), entry.getValue().hashCode()));
        }
        et.commit();
    } catch (Exception oops) {
        oops.printStackTrace();
        et.rollback();
        oops.printStackTrace();
    } finally {
        if (em.isOpen())
            em.close();
        if (emf.isOpen())
            emf.close();
        ((ClassPathXmlApplicationContext) ctx).close();
    }
}

From source file:pt.souplesse.spark.Server.java

public static void main(String[] args) {
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("guestbook");
    EntityManager manager = factory.createEntityManager();
    JinqJPAStreamProvider streams = new JinqJPAStreamProvider(factory);
    get("/messages", (req, rsp) -> {
        rsp.type("application/json");
        return gson.toJson(streams.streamAll(manager, Message.class).collect(Collectors.toList()));
    });//from  w w w. j  av a  2s .c  o m
    post("/messages", (req, rsp) -> {
        try {
            Message msg = gson.fromJson(req.body(), Message.class);
            if (StringUtils.isBlank(msg.getMessage()) || StringUtils.isBlank(msg.getName())) {
                halt(400);
            }
            manager.getTransaction().begin();
            manager.persist(msg);
            manager.getTransaction().commit();
        } catch (JsonSyntaxException e) {
            halt(400);
        }
        rsp.type("application/json");
        return gson.toJson(streams.streamAll(manager, Message.class).collect(Collectors.toList()));
    });
    get("/comments", (req, rsp) -> {
        rsp.type("application/json");
        Map<String, List<Body>> body = new HashMap<>();
        try (CloseableHttpClient client = create().build()) {
            String url = String.format("https://api.github.com/repos/%s/events", req.queryMap("repo").value());
            log.info(url);
            body = client.execute(new HttpGet(url), r -> {
                List<Map<String, Object>> list = gson.fromJson(EntityUtils.toString(r.getEntity()), List.class);
                Map<String, List<Body>> result = new HashMap<>();
                list.stream().filter(m -> m.getOrDefault("type", "").equals("IssueCommentEvent"))
                        .map(m -> new Body(((Map<String, String>) m.get("actor")).get("login"),
                                ((Map<String, Map<String, String>>) m.get("payload")).get("comment")
                                        .get("body")))
                        .forEach(b -> result.compute(b.getLogin(), (k, v) -> v == null ? new ArrayList<>()
                                : Lists.asList(b, v.toArray(new Body[v.size()]))));
                return result;
            });
        } catch (IOException e) {
            log.error(null, e);
            halt(400, e.getMessage());
        }
        return gson.toJson(body);
    });
}

From source file:utilities.PopulateDatabase.java

public static void main(String[] args) throws Throwable {
    ApplicationContext applicationContext;
    EntityManagerFactory entityManagerFactory;
    EntityManager entityManager;//from www  . jav a2  s.  c  o m
    EntityTransaction entityTransaction;

    applicationContext = new ClassPathXmlApplicationContext("classpath:PopulateDatabase.xml");

    entityManagerFactory = Persistence.createEntityManagerFactory(PersistenceUnit);
    entityManager = entityManagerFactory.createEntityManager();
    entityTransaction = entityManager.getTransaction();

    initialise(entityManagerFactory, entityManager);

    entityTransaction.begin();
    try {
        for (Entry<String, Object> entry : applicationContext.getBeansWithAnnotation(Entity.class).entrySet()) {
            String beanName;
            DomainEntity entity;

            beanName = entry.getKey();
            entity = (DomainEntity) entry.getValue();
            entityManager.persist(entity);
            System.out.println(String.format("Persisting (%s, %s, %d)", beanName, entity.getClass().getName(),
                    entity.getId()));
        }
        entityTransaction.commit();
    } catch (Exception oops) {
        oops.printStackTrace();
        entityTransaction.rollback();
    } finally {
        if (entityManager.isOpen())
            entityManager.close();
        if (entityManagerFactory.isOpen())
            entityManagerFactory.close();
    }
}

From source file:com.impetus.kvapps.runner.AppRunner.java

/**
 * main runner method//from   w w  w  . j av  a 2s. c  o  m
 * @param args takes excel data file as input argument args[0].
 */
public static void main(String[] args) {

    // Override CQL version while instantiating entity manager factory.

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("twissandra,twingo,twirdbms");
    EntityManager em = emf.createEntityManager();

    try {

        //populate user set from excel sheet.
        Set<User> users = UserBroker.brokeUserList(args[0]);

        for (Iterator<User> iterator = users.iterator(); iterator.hasNext();) {
            User user = (User) iterator.next();

            // on Persist
            ExecutorService.onPersist(em, user);

            // on find by id.
            ExecutorService.findByKey(em, "BigDataUser");

            List<User> fetchedUsers = ExecutorService.onQueryByEmail(em, user);

            if (fetchedUsers != null && fetchedUsers.size() > 0) {
                logger.info(user.toString());
            }

            logger.info("");
            System.out.println("#######################Querying##########################################");
            logger.info("");
            logger.info("");

        }

        // Execute wild search query.
        String query = "Select u from User u";
        logger.info(query);
        ExecutorService.findByQuery(em, query);

        // // Execute native CQL. Fetch tweets for given user.
        logger.info("");
        System.out.println("#######################Querying##########################################");
        logger.info("");
        logger.info("");

        query = "Select * from tweets where user_id='RDBMSUser'";
        logger.info(query);
        ExecutorService.findByNativeQuery(em, query);
    } finally {
        onDestroyDBResources(emf, em);
    }
}

From source file:Professor.java

  public static void main(String[] a) throws Exception {
  JPAUtil util = new JPAUtil();

  EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
  EntityManager em = emf.createEntityManager();
  ProfessorService service = new ProfessorService(em);

  em.getTransaction().begin();/*from w  w w .j  av a 2 s.  c om*/
  Professor emp = service.createProfessor("AAA", 45000);
  em.getTransaction().commit();
  System.out.println("Persisted " + emp);

  util.checkData("select * from Professor");

    
  em.close();
  emf.close();
}

From source file:ContractProfessor.java

  public static void main(String[] a) throws Exception {
  JPAUtil util = new JPAUtil();

  EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
  EntityManager em = emf.createEntityManager();
  ProfessorService service = new ProfessorService(em);

  em.getTransaction().begin();//from w w  w. j  a v a2  s. c o  m

  Professor emp = null;
  emp = new ContractProfessor();

  emp.setId(1);
  emp.setName("name");
  service.createProfessor(emp);

  System.out.println("Professors: ");
  for (Professor emp1 : service.findAllProfessors()) {
    System.out.print(emp1);
  }

  util.checkData("select * from EMP");

  em.getTransaction().commit();
  em.close();
  emf.close();
}

From source file:Professor.java

public static void main(String[] a) throws Exception {
        JPAUtil util = new JPAUtil();

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
        EntityManager em = emf.createEntityManager();
        ProfessorService service = new ProfessorService(em);

        em.getTransaction().begin();/*  w ww  .  ja v a2s  .  co  m*/

        service.findAllProfessors();

        util.checkData("select * from Professor");

        em.getTransaction().commit();
        em.close();
        emf.close();
    }

From source file:com.medicaid.mmis.util.CodeMappingLoader.java

/**
 * Reads the code mapping xls and inserts any unmapped row to the legacy mapping table.
 * @throws InvalidFormatException if the input file is not recognized 
 *//*from  w  ww .ja  va2s.  c  om*/
@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException, PortalServiceException, InvalidFormatException {
    PropertyConfigurator.configure("log4j.properties");
    logger = Logger.getLogger(CodeMappingLoader.class);
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("cms-data-load");
    EntityManager em = emf.createEntityManager();

    Workbook workbook = WorkbookFactory.create(new File("mapping/CodeMapping.xlsx"));
    SequenceGeneratorBean sequence = new SequenceGeneratorBean();
    sequence.setEm(em);

    try {
        em.getTransaction().begin();
        List<LegacySystemMapping> rs = em.createQuery("Select l from LegacySystemMapping l").getResultList();
        for (LegacySystemMapping mapping : rs) {
            em.remove(mapping);
        }
        importSheet(em, sequence, workbook, "ENROLLMENT_STATUS");
        importSheet(em, sequence, workbook, "RISK_LEVEL");
        importSheet(em, sequence, workbook, "SPECIALTY_CODE");
        importSheet(em, sequence, workbook, "LICENSE_TYPE");
        importSheet(em, sequence, workbook, "ISSUING_BOARD");
        importSheet(em, sequence, workbook, "PROVIDER_TYPE");
        importSheet(em, sequence, workbook, "COUNTY_CODE");
        importSheet(em, sequence, workbook, "BEN_OWNER_TYPE");
        importSheet(em, sequence, workbook, "LICENSE_STATUS");
        importSheet(em, sequence, workbook, "COS");
        em.getTransaction().commit();
    } catch (Throwable t) {
        em.getTransaction().rollback();
        logger.error("Could not complete import", t);
        throw new PortalServiceException("Error during import", t);
    }
}

From source file:Professor.java

  public static void main(String[] a) throws Exception {
  JPAUtil util = new JPAUtil();

  EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
  EntityManager em = emf.createEntityManager();
  ProfessorService service = new ProfessorService(em);

  em.getTransaction().begin();/*from   w ww.  j a  v  a2s . c o m*/
  Professor emp = service.createProfessor(158, "AAA", 45000,ProfessorType.CONTRACT_EMPLOYEE);
  em.getTransaction().commit();
  System.out.println("Persisted " + emp);

  util.checkData("select * from Professor");

  // remove an employee
  em.getTransaction().begin();
  service.removeProfessor(158);
  em.getTransaction().commit();
  System.out.println("Removed Professor 158");

  util.checkData("select * from Professor");
    
  em.close();
  emf.close();
}