Example usage for javax.persistence EntityManager persist

List of usage examples for javax.persistence EntityManager persist

Introduction

In this page you can find the example usage for javax.persistence EntityManager persist.

Prototype

public void persist(Object entity);

Source Link

Document

Make an instance managed and persistent.

Usage

From source file:org.rhq.enterprise.server.content.test.RepoManagerBeanTest.java

@Test(enabled = ENABLED)
public void createDeleteRepoGroup() throws Exception {
    // Setup/*  ww w  .  j  a  va 2s.  c  o  m*/
    EntityManager entityManager = getEntityManager();

    RepoGroupType groupType = new RepoGroupType("testCreateDeleteRepoGroupType");
    entityManager.persist(groupType);
    entityManager.flush();

    String groupName = "testCreateDeleteRepoGroup";
    RepoGroup group = repoManager.getRepoGroupByName(groupName);
    assert group == null;

    // Test
    group = new RepoGroup(groupName);
    group.setRepoGroupType(groupType);
    group = repoManager.createRepoGroup(overlord, group);

    // Verify
    int id = group.getId();
    group = repoManager.getRepoGroup(overlord, id);
    assert group != null;
    assert group.getName().equals(groupName);

    // Cleanup
    repoManager.deleteRepoGroup(overlord, id);
    group = repoManager.getRepoGroup(overlord, id);
    assert group == null;

    entityManager.remove(groupType);
}

From source file:org.rhq.enterprise.server.content.test.RepoManagerBeanTest.java

@Test(enabled = ENABLED)
public void getRepoGroupTypeByName() throws Exception {
    // Setup/*from w  ww.  j  av  a2 s.  c  o m*/
    EntityManager entityManager = getEntityManager();
    String name = "test-repo-type";

    RepoGroupType groupType = new RepoGroupType(name);
    entityManager.persist(groupType);
    entityManager.flush();

    // Test
    RepoGroupType type = repoManager.getRepoGroupTypeByName(overlord, name);
    assert type != null;
    assert type.getName().equals(name);

    // Cleanup
    type = entityManager.find(RepoGroupType.class, type.getId());
    entityManager.remove(type);
    entityManager.flush();
}

From source file:org.rhq.enterprise.server.content.test.RepoManagerBeanTest.java

@Test(enabled = ENABLED)
public void createDuplicateRepoGroup() throws Exception {
    // Setup//from w w w.j  a  v  a 2  s.  c  o m
    EntityManager entityManager = getEntityManager();

    RepoGroupType groupType = new RepoGroupType("testCreateDuplicateRepoGroup");
    entityManager.persist(groupType);
    entityManager.flush();

    String groupName = "testCreateDuplicateRepoGroup";

    RepoGroup existing = new RepoGroup(groupName);
    existing.setRepoGroupType(groupType);
    repoManager.createRepoGroup(overlord, existing);

    existing = repoManager.getRepoGroupByName(groupName);
    assert existing != null;

    // Test
    RepoGroup duplicate = new RepoGroup(groupName);
    duplicate.setRepoGroupType(groupType);

    try {
        repoManager.createRepoGroup(overlord, existing);
        assert false;
    } catch (RepoException e) {
        // Expected
    }

    // Cleanup
    repoManager.deleteRepoGroup(overlord, existing.getId());
    existing = repoManager.getRepoGroup(overlord, existing.getId());
    assert existing == null;

    entityManager.remove(groupType);
}

From source file:com.chiralbehaviors.CoRE.agency.Agency.java

@Override
public void link(Relationship r, Agency child, Agency updatedBy, Agency inverseSoftware, EntityManager em) {
    assert r != null : "Relationship cannot be null";
    assert child != null;
    assert updatedBy != null;
    assert em != null;

    AgencyNetwork link = new AgencyNetwork(this, r, child, updatedBy);
    em.persist(link);
    AgencyNetwork inverse = new AgencyNetwork(child, r.getInverse(), this, inverseSoftware);
    em.persist(inverse);/*from  w  ww  .  j  av  a  2  s .  c o m*/
}

From source file:com.chiralbehaviors.CoRE.attribute.unit.Unit.java

@Override
public void link(Relationship r, Unit child, Agency updatedBy, Agency inverseSoftware, EntityManager em) {
    assert r != null : "Relationship cannot be null";
    assert child != null;
    assert updatedBy != null;
    assert em != null;

    UnitNetwork link = new UnitNetwork(this, r, child, updatedBy);
    em.persist(link);
    UnitNetwork inverse = new UnitNetwork(child, r.getInverse(), this, inverseSoftware);
    em.persist(inverse);//from  w ww. j  a v  a 2 s.c o  m
}

From source file:com.bitplan.vzjava.TestVZJPA.java

/**
 * test importing power VAlues in XML Format
 * //from w  w w. j  a  v a 2s  .  c  o m
 * @throws Exception
 */
// https://github.com/WolfgangFahl/com.bitplan.vzjava/issues/5
@Test
public void testImportXml() throws Exception {
    // open the testdatabase
    VZDB vzdb = new VZDB("demo");
    // get the power values from the XML file
    File powerValueXmlFile = new File("src/test/data/vzdb/powervalues.xml");
    String xml = FileUtils.readFileToString(powerValueXmlFile);
    PowerValueManagerDao pvm = (PowerValueManagerDao) PowerValueManagerDao.getFactoryStatic().fromXML(xml);
    List<PowerValue> powerValues = pvm.getElements();
    // there should be 74669 power values in this test set
    assertEquals("xml import should have new Color(0x of records", 74669, powerValues.size());
    // delete existing data from the test database
    EntityManager em = vzdb.getEntityManager();
    em.getTransaction().begin();
    Query dquery = em.createNativeQuery("delete from data");
    dquery.executeUpdate();
    em.getTransaction().commit();

    String from = "2017-01-31 20:00:00";
    String to = "2017-03-24 14:00:00";
    em.getTransaction().begin();
    for (PowerValue powerValue : powerValues) {
        em.persist(powerValue);
    }
    em.getTransaction().commit();
    int channel = 4;
    ChannelMode channelMode = ChannelMode.Power;
    pvm.setVzdb(vzdb);
    List<PowerValue> dbPowerValues = pvm.get(from, to, channel, channelMode);
    assertTrue(String.format("database should have more than 74400 of imported records but has %5d",
            dbPowerValues.size()), dbPowerValues.size() > 74400);
}

From source file:de.berlios.jhelpdesk.dao.jpa.TicketCategoryDAOJpa.java

@Transactional(readOnly = false)
public void insertRootCategory(final TicketCategory rootCategory) {
    this.jpaTemplate.execute(new JpaCallback() {
        public Object doInJpa(EntityManager em) throws PersistenceException {
            Query getMaxTRightQuery = em.createNativeQuery("SELECT max(t_right) FROM ticket_category",
                    Long.class);
            final Long maxTRight = (Long) getMaxTRightQuery.getSingleResult();

            rootCategory.setLeft(new Long(maxTRight.longValue() + 1));
            rootCategory.setRight(new Long(maxTRight.longValue() + 2));
            rootCategory.setDepth(0);//from   ww w . j a  v a2  s.  c  om
            em.persist(rootCategory);
            return null;
        }
    });
}

From source file:org.drools.semantics.lang.dl.DL_9_CompilationTest.java

private void persist(Object o, EntityManager em) {
    em.getTransaction().begin();
    em.persist(o);
    em.getTransaction().commit();
    em.clear();
}

From source file:org.SRV.testServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    double value1 = Double.parseDouble(request.getParameter("val1"));
    double value2 = Double.parseDouble(request.getParameter("val2"));

    UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String username = user.getUsername();
    //com.seostella_springsecuritybasics_war_1.0.0-BUILD-SNAPSHOTPU
    entityManagerFactory = Persistence.createEntityManagerFactory("org.SRV_war_1.0.0-BUILD-SNAPSHOTPU");

    double result = 0;
    switch (request.getParameter("operation").charAt(0)) {
    case '+':
        result = value1 + value2;/* ww w.ja va 2s  .  com*/
        break;
    case '-':
        result = value1 - value2;
        break;
    case '*':
        result = value1 * value2;
        break;
    case '/':
        result = value1 / value2;
        break;
    default:
        break;
    }

    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
    Date date = new Date();
    Essence essence = new Essence();
    essence.setLogin(username);
    essence.setDate(date);
    essence.setValue1(Double.toString(value1));
    essence.setValue2(Double.toString(value2));
    essence.setOperation(request.getParameter("operation"));
    essence.setResult(Double.toString(result));
    entityManager.persist(essence);
    entityManager.getTransaction().commit();
    entityManager.clear();
    entityManager.close();
    entityManagerFactory.close();
    JSONObject obj;
    obj = new JSONObject();
    obj.put("result", result);
    //response.getOutputStream().print(obj.toString());
    response.getWriter().write(obj.toString());
}

From source file:edu.vt.middleware.gator.JpaConfigManager.java

/** {@inheritDoc}. */
@Transactional(propagation = Propagation.REQUIRED)
public void save(final ProjectConfig project) {
    final EntityManager em = getEntityManager();
    final Set<ClientConfig> removedClients = new HashSet<ClientConfig>();
    if (logger.isDebugEnabled()) {
        logger.debug("Saving " + project);
    }//from w w w.  j  a  v  a 2  s  . c o  m

    ProjectConfig liveProject;
    project.setModifiedDate(Calendar.getInstance());
    if (project.isNew()) {
        em.persist(project);
        liveProject = find(ProjectConfig.class, project.getId());
    } else {
        // Determine removed clients
        final ProjectConfig pDb = find(ProjectConfig.class, project.getId());
        for (ClientConfig client : pDb.getClients()) {
            if (project.getClient(client.getId()) == null) {
                removedClients.add(client);
            }
        }
        liveProject = em.merge(project);
    }

    // Touch all collections to lazy load dependent data so complete project
    // configuration is available to event handlers
    liveProject.getAppenders();
    liveProject.getCategories();
    liveProject.getClients();
    liveProject.getPermissions();

    // Fire events on a separate thread so we do not disrupt client thread
    // (e.g. avoid subscriber blocking)
    for (ConfigChangeListener listener : getConfigChangeListeners()) {
        eventExecutor.execute(new ProjectChangedEvent(listener, liveProject, removedClients));
    }
}