Example usage for org.hibernate Session persist

List of usage examples for org.hibernate Session persist

Introduction

In this page you can find the example usage for org.hibernate Session persist.

Prototype

void persist(Object object);

Source Link

Document

Make a transient instance persistent.

Usage

From source file:com.entity.getSession.java

public void signUp(PersonControl aThis) {
    Session session = getSess();
    session.getTransaction().begin();/*w  w  w. ja va  2 s.  com*/
    Person2 person = new Person2();
    person.setId(aThis.getId());
    person.setName(aThis.getName());
    person.setEmail(aThis.getEmail());
    person.setPassword(aThis.getPassword());
    person.setCredit(aThis.getCredit().toString());
    person.setBirthdate(aThis.getBirthdate());
    System.out.println("" + person);

    session.persist(person);
    session.getTransaction().commit();
    System.out.println("success");

}

From source file:com.espe.distribuidas.examen.examdistribuidasquimbiulco.Starter.java

public static void main(String[] args) {
    System.out.println("ejemplo de hibernate");
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = sf.openSession();

    System.out.println("Listado de alumnos---------------");
    List<Alumno> alumnos = session.createQuery("SELECT obj FROM Alumno obj").list();
    for (Alumno objeto : alumnos) {
        System.out.println(objeto.getIdAlumno() + "]" + objeto.getNombre() + "]" + objeto.getFechaNacimiento());
    }/*ww  w.  j a  v a 2  s.  co  m*/

    System.out.println("Listado de Asignaturas---------------");
    List<Asignatura> asignaturas = session.createQuery("SELECT obj FROM Asignatura obj").list();
    for (Asignatura objeto : asignaturas) {
        System.out.println(objeto.getIdAsignatura() + "]" + objeto.getNombre() + "]" + objeto.getCreditos()
                + "]" + objeto.getDocente().getNombre());
    }

    System.out.println("Ingreso de alumno------------------------");

    Scanner sc = new Scanner(System.in);
    System.out.println("Ingrese el Alumno: ");
    String codigoAlumno = sc.nextLine();

    System.out.println("Ingrese la asignatura: ");
    Integer codigoAsignatura = sc.nextInt();

    System.out.println("Ingrese la nota: ");
    double nota = sc.nextDouble();

    AsignaturaAlumnos asigAlumnos = new AsignaturaAlumnos();
    asigAlumnos.setIdAsignatura(codigoAsignatura);
    asigAlumnos.setIdAlumno(codigoAlumno);
    asigAlumnos.setNota(new BigDecimal(nota));
    asigAlumnos.setFechaRegistro(new Date());

    session.persist(asigAlumnos);

    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        session.persist(asigAlumnos);
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
    }

    System.out.println("Alumnos de una asignatura------------------------");

    String idAsignatura;

    //        List<Asignatura> asignaturas2 = session.createCriteria(Asignatura.class).add(Restrictions.like(idAsignatura)).list();
    //        for (Asignatura objeto : asignaturas2) {
    //            System.out.println(objeto);
    //        }

}

From source file:com.evolveum.midpoint.repo.sql.data.common.dictionary.ExtItemDictionary.java

License:Apache License

private void addExtItemAttempt(RExtItem item) {
    Session session = null;
    try {/* www . j a  va2  s.  c o  m*/
        session = baseHelper.beginTransaction();
        session.persist(item);
        session.getTransaction().commit();
    } catch (RuntimeException ex) {
        baseHelper.handleGeneralException(ex, session, null);
    } finally {
        baseHelper.cleanupSessionAndResult(session, null);
    }
}

From source file:com.example.test.HibernateBookRepositoryTest.java

License:Apache License

private void persistBooks(Supplier<AbstractBook> bookSupplier) throws Exception {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override//from ww  w  .j  a v  a 2 s . co  m
        protected void doInTransactionWithoutResult(TransactionStatus ts) {
            Session session = getCurrentSession();

            Category softwareDevelopment = new Category();
            softwareDevelopment.setName("Software development");
            session.persist(softwareDevelopment);

            Category systemDesign = new Category();
            systemDesign.setName("System design");
            session.persist(systemDesign);

            Author martinFowler = new Author();
            martinFowler.setFullName("Martin Fowler");
            session.persist(martinFowler);

            AbstractBook poeaa = bookSupplier.get();
            poeaa.setIsbn("007-6092019909");
            poeaa.setTitle("Patterns of Enterprise Application Architecture");
            poeaa.setPublicationDate(Date.from(Instant.parse("2002-11-15T00:00:00.00Z")));
            poeaa.setAuthors(asList(martinFowler));
            poeaa.setCategories(asList(softwareDevelopment, systemDesign));
            session.persist(poeaa);

            Author gregorHohpe = new Author();
            gregorHohpe.setFullName("Gregor Hohpe");
            session.persist(gregorHohpe);

            Author bobbyWoolf = new Author();
            bobbyWoolf.setFullName("Bobby Woolf");
            session.persist(bobbyWoolf);

            AbstractBook eip = bookSupplier.get();
            eip.setIsbn("978-0321200686");
            eip.setTitle("Enterprise Integration Patterns");
            eip.setPublicationDate(Date.from(Instant.parse("2003-10-20T00:00:00.00Z")));
            eip.setAuthors(asList(gregorHohpe, bobbyWoolf));
            eip.setCategories(asList(softwareDevelopment, systemDesign));
            session.persist(eip);

            Category objectOrientedSoftwareDesign = new Category();
            objectOrientedSoftwareDesign.setName("Object-Oriented Software Design");
            session.persist(objectOrientedSoftwareDesign);

            Author ericEvans = new Author();
            ericEvans.setFullName("Eric Evans");
            session.persist(ericEvans);

            AbstractBook ddd = bookSupplier.get();
            ddd.setIsbn("860-1404361814");
            ddd.setTitle("Domain-Driven Design: Tackling Complexity in the Heart of Software");
            ddd.setPublicationDate(Date.from(Instant.parse("2003-08-01T00:00:00.00Z")));
            ddd.setAuthors(asList(ericEvans));
            ddd.setCategories(asList(softwareDevelopment, systemDesign, objectOrientedSoftwareDesign));
            session.persist(ddd);

            Category networkingCloudComputing = new Category();
            networkingCloudComputing.setName("Networking & Cloud Computing");
            session.persist(networkingCloudComputing);

            Category databasesBigData = new Category();
            databasesBigData.setName("Databases & Big Data");
            session.persist(databasesBigData);

            Author pramodSadalage = new Author();
            pramodSadalage.setFullName("Pramod J. Sadalage");
            session.persist(pramodSadalage);

            AbstractBook nosql = bookSupplier.get();
            nosql.setIsbn("978-0321826626");
            nosql.setTitle("NoSQL Distilled: A Brief Guide to the Emerging World of Polyglot Persistence");
            nosql.setPublicationDate(Date.from(Instant.parse("2012-08-18T00:00:00.00Z")));
            nosql.setAuthors(asList(pramodSadalage, martinFowler));
            nosql.setCategories(asList(networkingCloudComputing, databasesBigData));
            session.persist(nosql);
        }
    });
    System.out.println("##################################################");
}

From source file:com.gemstone.gemfire.modules.HibernateJUnitTest.java

License:Apache License

@Test
public void testSomething() throws Exception {
    java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.ALL);
    log.info("SWAP:creating session factory In hibernateTestCase");

    Session session = getSessionFactory(null).openSession();
    log.info("SWAP:session opened");
    // session.setFlushMode(FlushMode.COMMIT);
    session.beginTransaction();/*  ww w .j  a v a  2 s .c  o m*/
    Event theEvent = new Event();
    theEvent.setTitle("title");
    theEvent.setDate(new Date());
    //session.save(theEvent);
    session.persist(theEvent);
    Long id = theEvent.getId();
    session.getTransaction().commit();
    log.info("commit complete...doing load");
    session.beginTransaction();
    Event ev = (Event) session.load(Event.class, id);
    log.info("load complete: " + ev);
    log.trace("SWAP");
    ev.setTitle("newTitle");
    session.save(ev);
    log.info("commit");
    session.getTransaction().commit();
    log.info("save complete " + ev);

    session.beginTransaction();
    ev = (Event) session.load(Event.class, id);
    log.info("load complete: " + ev);
    ev.setTitle("newTitle2");
    session.save(ev);
    log.info("commit");
    session.getTransaction().commit();
    log.info("save complete " + ev);

    ev = (Event) session.load(Event.class, id);
    log.info("second load " + ev);
    session.flush();
    session.close();
    log.info("flush complete session:" + session);

    for (int i = 0; i < 5; i++) {
        session = getSessionFactory(null).openSession();
        log.info("doing get " + id);
        // ev = (Event) session.load(Event.class, id);
        ev = (Event) session.get(Event.class, id);
        log.info("third load " + ev);
    }
    printExistingDB();
    Iterator it = GemFireCacheImpl.getInstance().rootRegions().iterator();
    while (it.hasNext()) {
        Region r = (Region) it.next();
        System.out.println("Region:" + r);
        Iterator enIt = r.entrySet().iterator();
        while (enIt.hasNext()) {
            Region.Entry re = (Entry) enIt.next();
            System.out.println("key:" + re.getKey() + " value:" + re.getValue());
        }
    }
    Thread.sleep(3000);
    //System.in.read();
    // try direct data

}

From source file:com.github.shyiko.rook.it.h4com.IntegrationTest.java

License:Apache License

private void testQueryCacheEviction(final boolean enableQCS, final String ignoredTable, int expectedEvents)
        throws Exception {
    ExecutionContext masterContext = ExecutionContextHolder.get("master");
    ExecutionContext slaveContext = ExecutionContextHolder.get("slave");
    HashSet<String> ignoredTables = new HashSet<String>() {
        {/*  w  w  w  . j  a v  a2s  .  c o m*/
            add(ignoredTable);
        }
    };
    replicationStream.setIgnoredTables(ignoredTables);
    if (enableQCS) {
        replicationStream.registerListener(new QueryCacheSynchronizer(
                new SynchronizationContext(slaveContext.getConfiguration(), slaveContext.getSessionFactory())));
    }
    CountDownReplicationListener countDownReplicationListener = new CountDownReplicationListener();
    replicationStream.registerListener(countDownReplicationListener);
    slaveContext.execute(new Callback<Session>() {

        @Override
        public void execute(Session session) {
            assertEquals(session.createQuery("from RootEntity").setCacheable(true).list().size(), 0);
            assertEquals(session.createQuery("from IgnoredEntity").setCacheable(true).list().size(), 0);
            assertEquals(session.createQuery("from CompositeKeyEntity").setCacheable(true).list().size(), 0);
        }
    });
    masterContext.execute(new Callback<Session>() {

        @Override
        public void execute(Session session) {
            final RootEntity rootEntity = new RootEntity("Slytherin");
            session.persist(rootEntity);
            final IgnoredEntity ignoredEntity = new IgnoredEntity("Gryffindor");
            session.persist(ignoredEntity);
            session.persist(new CompositeKeyEntity(rootEntity.getId(), ignoredEntity.getId()));
        }
    });
    countDownReplicationListener.waitFor(InsertRowsReplicationEvent.class, expectedEvents, DEFAULT_TIMEOUT);
    slaveContext.execute(new Callback<Session>() {

        @Override
        public void execute(Session session) {
            assertEquals(session.createQuery("from RootEntity").setCacheable(true).list().size(),
                    enableQCS ? 1 : 0);
            assertEquals(session.createQuery("from CompositeKeyEntity").setCacheable(true).list().size(),
                    enableQCS ? 1 : 0);
            assertEquals(session.createQuery("from IgnoredEntity").setCacheable(true).list().size(),
                    (enableQCS && (ignoredTable == null)) ? 1 : 0);
        }
    });
}

From source file:com.github.shyiko.rook.it.h4com.IntegrationTest.java

License:Apache License

private void testSecondLevelCacheEviction(final boolean enableSLCS) throws Exception {
    ExecutionContext masterContext = ExecutionContextHolder.get("master");
    ExecutionContext slaveContext = ExecutionContextHolder.get("slave");
    if (enableSLCS) {
        replicationStream.registerListener(new SecondLevelCacheSynchronizer(
                new SynchronizationContext(slaveContext.getConfiguration(), slaveContext.getSessionFactory())));
    }//from  w w w  .  j  a v a  2s .c o  m
    CountDownReplicationListener countDownReplicationListener = new CountDownReplicationListener();
    replicationStream.registerListener(countDownReplicationListener);
    final AtomicReference<Serializable> rootEntityId = new AtomicReference<Serializable>(),
            ignoredEntityId = new AtomicReference<Serializable>();
    masterContext.execute(new Callback<Session>() {

        @Override
        public void execute(Session session) {
            rootEntityId.set(session.save(new RootEntity("Slytherin", new OneToOneEntity("Severus Snape"),
                    new HashSet<OneToManyEntity>(Arrays.asList(new OneToManyEntity("Draco Malfoy"),
                            new OneToManyEntity("Vincent Crabbe"), new OneToManyEntity("Gregory Goyle"))))));
            ignoredEntityId.set(session.save(new IgnoredEntity("Hufflepuff")));
            session.persist(new CompositeKeyEntity((Long) rootEntityId.get(), (Long) ignoredEntityId.get()));
        }
    });
    slaveContext.execute(new Callback<Session>() {

        @Override
        public void execute(Session session) {
            RootEntity rootEntity = (RootEntity) session.get(RootEntity.class, rootEntityId.get());
            assertEquals(rootEntity.getName(), "Slytherin");
            assertEquals(rootEntity.getCompositeRelations().size(), 1);
        }
    });
    masterContext.execute(new Callback<Session>() {

        @Override
        public void execute(Session session) {
            RootEntity rootEntity = (RootEntity) session.get(RootEntity.class, rootEntityId.get());
            rootEntity.setName("Slytherin House");
            rootEntity.getCompositeRelations().clear();
            session.merge(rootEntity);
        }
    });
    countDownReplicationListener.waitFor(UpdateRowsReplicationEvent.class, 1, DEFAULT_TIMEOUT);
    countDownReplicationListener.waitFor(DeleteRowsReplicationEvent.class, 1, DEFAULT_TIMEOUT);
    slaveContext.execute(new Callback<Session>() {

        @Override
        public void execute(Session session) {
            RootEntity rootEntity = (RootEntity) session.get(RootEntity.class, rootEntityId.get());
            assertEquals(rootEntity.getName(), enableSLCS ? "Slytherin House" : "Slytherin");
            assertEquals(rootEntity.getCompositeRelations().size(), enableSLCS ? 0 : 1);
        }
    });
    masterContext.execute(new Callback<Session>() {

        @Override
        public void execute(Session session) {
            session.delete(session.get(RootEntity.class, rootEntityId.get()));
        }
    });
    countDownReplicationListener.waitFor(DeleteRowsReplicationEvent.class, 2, DEFAULT_TIMEOUT);
    slaveContext.execute(new Callback<Session>() {

        @Override
        public void execute(Session session) {
            RootEntity rootEntity = (RootEntity) session.get(RootEntity.class, rootEntityId.get());
            assertTrue(enableSLCS == (rootEntity == null));
        }
    });
}

From source file:com.github.shyiko.rook.it.h4com.IntegrationTest.java

License:Apache License

@Test
public void testReplicationEventsComeGroupedByStatement() throws Exception {
    CountDownReplicationListener countDownReplicationListener = new CountDownReplicationListener();
    replicationStream.registerListener(countDownReplicationListener);
    ExecutionContext masterContext = ExecutionContextHolder.get("master");
    masterContext.execute(new Callback<Session>() {

        @Override// ww w .j  a  v  a2 s. c  o  m
        public void execute(Session session) {
            session.persist(new RootEntity("Slytherin"));
            session.persist(new RootEntity("Hufflepuff"));
            session.persist(new RootEntity("Ravenclaw"));
        }
    });
    countDownReplicationListener.waitFor(InsertRowsReplicationEvent.class, 3, DEFAULT_TIMEOUT);
    masterContext.execute(new Callback<Session>() {

        @Override
        public void execute(Session session) {
            session.createQuery("update RootEntity set name = '~'").executeUpdate();
        }
    });
    masterContext.execute(new Callback<Session>() {

        @Override
        public void execute(Session session) {
            session.createQuery("delete RootEntity where name = 'Ravenclaw'").executeUpdate();
        }
    });
    countDownReplicationListener.waitFor(UpdateRowsReplicationEvent.class, 1, DEFAULT_TIMEOUT);
}

From source file:com.github.shyiko.rook.it.h4ftiom.IntegrationTest.java

License:Apache License

private void testFullTextIndexUpdateOnInsert(ExecutionContext masterContext, ExecutionContext slaveContext,
        final boolean enableFTIS) throws TimeoutException, InterruptedException {
    masterContext.execute(new Callback<Session>() {

        @Override/*  w  w  w.  j ava  2s  .co  m*/
        public void execute(Session session) {
            session.persist(new RootEntity("Slytherin"));
            session.persist(new RootEntity("Gryffindor"));
        }
    });
    countDownReplicationListener.waitFor(InsertRowsReplicationEvent.class, 2, DEFAULT_TIMEOUT);
    slaveContext.execute(new Callback<Session>() {

        @Override
        public void execute(Session session) {
            assertTrue(enableFTIS == (searchRootEntityUsingFTI(session, "name", "Slytherin") != null));
        }
    });
}

From source file:com.griddynamics.jagger.engine.e1.aggregator.session.GeneralNodeInfoAggregator.java

License:Open Source License

public Map<NodeId, GeneralNodeInfo> getGeneralNodeInfo(String sessionId, Coordinator coordinator) {
    final String localSessionId = sessionId;
    Set<NodeId> nodes = new HashSet<NodeId>();
    Map<NodeId, GeneralNodeInfo> result = new HashMap<NodeId, GeneralNodeInfo>();
    nodes.addAll(coordinator.getAvailableNodes(NodeType.KERNEL));
    nodes.addAll(coordinator.getAvailableNodes(NodeType.AGENT));

    for (NodeId node : nodes) {
        try {//from  www  .  j  av  a  2  s  . co  m
            final GeneralNodeInfo generalNodeInfo = coordinator.getExecutor(node).runSyncWithTimeout(
                    new GetGeneralNodeInfo(sessionId), Coordination.<GetGeneralNodeInfo>doNothing(),
                    nodeCollectInfoTime);
            generalNodeInfo.setNodeId(node.toString());
            log.info("Got node info from node {}:\n {}", node, generalNodeInfo.toString());

            getHibernateTemplate().execute(new HibernateCallback<Void>() {
                @Override
                public Void doInHibernate(Session session) throws HibernateException, SQLException {
                    session.persist(new NodeInfoEntity(localSessionId, generalNodeInfo));
                    session.flush();
                    return null;
                }
            });

            result.put(node, generalNodeInfo);
        } catch (Throwable e) {
            log.error("Get node info failed for node " + node + "\n" + Throwables.getStackTraceAsString(e));
        }
    }

    return result;
}