Java Code Examples for org.hibernate.Session#merge()

The following examples show how to use org.hibernate.Session#merge() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HibernateMergeExample.java    From journaldev with MIT License 6 votes vote down vote up
public static void main(String[] args) {

		// Prep Work
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		Employee emp = (Employee) session.load(Employee.class, new Long(101));
		System.out.println("Employee object loaded. " + emp);
		tx.commit();

		 //merge example - data already present in tables
		 emp.setSalary(25000);
		 Transaction tx8 = session.beginTransaction();
		 Employee emp4 = (Employee) session.merge(emp);
		 System.out.println(emp4 == emp); // returns false
		 emp.setName("Test");
		 emp4.setName("Kumar");
		 System.out.println("15. Before committing merge transaction");
		 tx8.commit();
		 System.out.println("16. After committing merge transaction");

		// Close resources
		sessionFactory.close();

	}
 
Example 2
Source File: Main.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Demonstrates detached object support
 */
public void changeUserDetails(User user) throws Exception {
	System.out.println("Changing user details for: " + user.getId() );

	Session s = factory.openSession();
	Transaction tx=null;
	try {
		tx = s.beginTransaction();

		s.merge(user);

		tx.commit();
	}
	catch (Exception e) {
		if (tx!=null) tx.rollback();
		throw e;
	}
	finally {
		s.close();
	}
}
 
Example 3
Source File: MergeTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testNoExtraUpdatesOnMergeWithCollection() throws Exception {
	Session s = openSession();
       s.beginTransaction();
	Node parent = new Node( "parent" );
	Node child = new Node( "child" );
	parent.getChildren().add( child );
	child.setParent( parent );
	s.persist( parent );
	s.getTransaction().commit();
	s.close();

	clearCounts();

	// parent is now detached, but we have made no changes.  so attempt to merge it
	// into this new session; this should cause no updates...
	s = openSession();
	s.beginTransaction();
	parent = ( Node ) s.merge( parent );
	s.getTransaction().commit();
	s.close();

	assertUpdateCount( 0 );
	assertInsertCount( 0 );

	///////////////////////////////////////////////////////////////////////
	// as a control measure, now update the node while it is detached and
	// make sure we get an update as a result...
	( ( Node ) parent.getChildren().iterator().next() ).setDescription( "child's new description" );
	parent.getChildren().add( new Node( "second child" ) );
	s = openSession();
	s.beginTransaction();
	parent = ( Node ) s.merge( parent );
	s.getTransaction().commit();
	s.close();
	assertUpdateCount( 1 );
	assertInsertCount( 1 );
	///////////////////////////////////////////////////////////////////////

	cleanup();
}
 
Example 4
Source File: EmbeddedCompositeIdTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testMerge() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Course uc =  new UniversityCourse("mat2000", "Monash", "second year maths", 0);
	Course c =  new Course("eng5000", "BHS", "grade 5 english");
	s.persist(uc);
	s.persist(c);
	t.commit();
	s.close();
	
	c.setDescription("Grade 5 English");
	uc.setDescription("Second year mathematics");
	
	s = openSession();
	t = s.beginTransaction();
	s.merge(c);
	s.merge(uc);
	t.commit();
	s.close();
	
	s = openSession();
	t = s.beginTransaction();
	s.delete(c);
	s.delete(uc);
	t.commit();
	s.close();
}
 
Example 5
Source File: MergeTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testMergeTreeWithGeneratedId() {

		clearCounts();

		Session s = openSession();
		Transaction tx = s.beginTransaction();
		NumberedNode root = new NumberedNode("root");
		NumberedNode child = new NumberedNode("child");
		root.addChild(child);
		s.persist(root);
		tx.commit();
		s.close();

		assertInsertCount(2);
		clearCounts();

		root.setDescription("The root node");
		child.setDescription("The child node");

		NumberedNode secondChild = new NumberedNode("second child");

		root.addChild(secondChild);

		s = openSession();
		tx = s.beginTransaction();
		s.merge(root);
		tx.commit();
		s.close();

		assertInsertCount(1);
		assertUpdateCount(2);

		cleanup();
	}
 
Example 6
Source File: HibernateLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Object saveOrUpdate(Object feature) throws LayerException {
	// force the srid value
	enforceSrid(feature);
	Session session = getSessionFactory().getCurrentSession();
	// using merge to allow detached objects, although Geomajas avoids them
	return session.merge(feature);
}
 
Example 7
Source File: BackrefCompositeMapKeyTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testOrphanDeleteOnMerge() {
	Session session = openSession();
	Transaction t = session.beginTransaction();
	Product prod = new Product( "Widget" );
	Part part = new Part( "Widge", "part if a Widget" );
	MapKey mapKey = new MapKey( "Top" );
	prod.getParts().put( mapKey, part );
	Part part2 = new Part( "Get", "another part if a Widget" );
	prod.getParts().put( new MapKey("Bottom"), part2 );
	session.persist( prod );
	t.commit();
	session.close();

	prod.getParts().remove( mapKey );

	session = openSession();
	t = session.beginTransaction();
	session.merge(prod);
	t.commit();
	session.close();

	session = openSession();
	t = session.beginTransaction();
	assertNull( session.get(Part.class, "Widge") );
	assertNotNull( session.get(Part.class, "Get") );
	session.delete( session.get(Product.class, "Widget") );
	t.commit();
	session.close();
}
 
Example 8
Source File: CoreDBServiceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Object merge(E e) {
	try {
		Session session = getCurrentSession();
		Object o = (Object) session.merge(e);
		session.flush();
		session.evict(e);
		return o;
	} catch (Exception ex) {
		logger.error("Merge failed", ex);
		throw new HibernateException("Merge failed");
	}

}
 
Example 9
Source File: AlarmSqlImpl.java    From monasca-thresh with Apache License 2.0 5 votes vote down vote up
private BinaryId insertMetricDimensionSet(Session session, Map<String, String> dimensions) {
  final byte[] dimensionSetId = calculateDimensionSHA1(dimensions);
  for (final Map.Entry<String, String> entry : dimensions.entrySet()) {

    final MetricDimensionDb metricDimension = new MetricDimensionDb(dimensionSetId, entry.getKey(), entry.getValue());

    if (session.get(MetricDimensionDb.class, metricDimension.getId()) == null) {
      session.merge(metricDimension);
    }

  }

  return new BinaryId(dimensionSetId);
}
 
Example 10
Source File: AlarmSqlImpl.java    From monasca-thresh with Apache License 2.0 5 votes vote down vote up
private MetricDefinitionDimensionsDb insertMetricDefinitionDimension(final Session session,
                                                                     final MetricDefinitionAndTenantId mdtId) {
  final MetricDefinitionDb metricDefinition = this.insertMetricDefinition(session, mdtId);
  final BinaryId metricDimensionSetId = this.insertMetricDimensionSet(session, mdtId.metricDefinition.dimensions);
  final byte[] definitionDimensionsIdSha1Hash = DigestUtils.sha(
      metricDefinition.getId().toHexString() + metricDimensionSetId.toHexString()
  );
  final MetricDefinitionDimensionsDb metricDefinitionDimensions = new MetricDefinitionDimensionsDb(
      definitionDimensionsIdSha1Hash,
      metricDefinition,
      metricDimensionSetId
  );
  return (MetricDefinitionDimensionsDb) session.merge(metricDefinitionDimensions);
}
 
Example 11
Source File: AbsSupportDao.java    From jeesupport with MIT License 5 votes vote down vote up
@Override
public < T > void updateAll( String _db , List< T > _list , int _flush ) {
	Session session = _get_session( _db );

	int exnum = 0;
	int monum = _flush - 1;

	for ( T e : _list ) {
		session.merge( e );
		if ( ++exnum % _flush == monum ) _flush_session( session );
	}

	_flush_session( session );
}
 
Example 12
Source File: MergeTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testMergeManyToManyWithCollectionDeference() throws Exception {
	// setup base data...
	Session s = openSession();
	Transaction tx = s.beginTransaction();
	Competition competition = new Competition();
	competition.getCompetitors().add( new Competitor( "Name" ) );
	competition.getCompetitors().add( new Competitor() );
	competition.getCompetitors().add( new Competitor() );
	s.persist( competition );
	tx.commit();
	s.close();

	// the competition graph is now detached:
	//   1) create a new List reference to represent the competitors
	s = openSession();
	tx = s.beginTransaction();
	List newComp = new ArrayList();
	Competitor originalCompetitor = ( Competitor ) competition.getCompetitors().get( 0 );
	originalCompetitor.setName( "Name2" );
	newComp.add( originalCompetitor );
	newComp.add( new Competitor() );
	//   2) set that new List reference unto the Competition reference
	competition.setCompetitors( newComp );
	//   3) attempt the merge
	Competition competition2 = ( Competition ) s.merge( competition );
	tx.commit();
	s.close();

	assertFalse( competition == competition2 );
	assertFalse( competition.getCompetitors() == competition2.getCompetitors() );
	assertEquals( 2, competition2.getCompetitors().size() );

	s = openSession();
	tx = s.beginTransaction();
	competition = ( Competition ) s.get( Competition.class, competition.getId() );
	assertEquals( 2, competition.getCompetitors().size() );
	s.delete( competition );
	tx.commit();
	s.close();

	cleanup();
}
 
Example 13
Source File: CascadeToComponentCollectionTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testMergingOriginallyNullComponent() {
	// step1, we create a definition with one value, but with a null component
	Session session = openSession();
	session.beginTransaction();
	Definition definition = new Definition();
	Value value1 = new Value( definition );
	session.persist( definition );
	session.getTransaction().commit();
	session.close();

	// step2, we verify that the definition has one value; then we detach it
	session = openSession();
	session.beginTransaction();
	definition = ( Definition ) session.get( Definition.class, definition.getId() );
	assertEquals( 1, definition.getValues().size() );
	session.getTransaction().commit();
	session.close();

	// step3, we add a new value during detachment
	( ( Value ) definition.getValues().iterator().next() ).getLocalizedStrings().addString( new Locale( "en_US" ), "hello" );
	Value value2 = new Value( definition );
	value2.getLocalizedStrings().addString( new Locale( "es" ), "hola" );

	// step4 we merge the definition
	session = openSession();
	session.beginTransaction();
	session.merge( definition );
	session.getTransaction().commit();
	session.close();

	// step5, final test
	session = openSession();
	session.beginTransaction();
	definition = ( Definition ) session.get( Definition.class, definition.getId() );
	assertEquals( 2, definition.getValues().size() );
	Iterator values = definition.getValues().iterator();
	while ( values.hasNext() ) {
		assertEquals( 1, ( ( Value ) values.next() ).getLocalizedStrings().getStringsCopy().size() );
	}
	session.getTransaction().commit();
	session.close();
}
 
Example 14
Source File: MergeTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testNoExtraUpdatesOnMergeVersionedWithCollection() throws Exception {
Session s = openSession();
      s.beginTransaction();
VersionedEntity parent = new VersionedEntity( "parent", "parent" );
VersionedEntity child = new VersionedEntity( "child", "child" );
parent.getChildren().add( child );
child.setParent( parent );
s.persist( parent );
s.getTransaction().commit();
s.close();

clearCounts();

// parent is now detached, but we have made no changes.  so attempt to merge it
// into this new session; this should cause no updates...
s = openSession();
s.beginTransaction();
VersionedEntity mergedParent = ( VersionedEntity ) s.merge( parent );
s.getTransaction().commit();
s.close();

assertUpdateCount( 0 );
assertInsertCount( 0 );
assertEquals( "unexpected parent version increment", parent.getVersion(), mergedParent.getVersion() );
VersionedEntity mergedChild = ( VersionedEntity ) mergedParent.getChildren().iterator().next();
assertEquals( "unexpected child version increment", child.getVersion(), mergedChild.getVersion() );

///////////////////////////////////////////////////////////////////////
// as a control measure, now update the node while it is detached and
// make sure we get an update as a result...
mergedParent.setName( "new name" );
mergedParent.getChildren().add( new VersionedEntity( "child2", "new child" ) );
s = openSession();
s.beginTransaction();
parent = ( VersionedEntity ) s.merge( mergedParent );
s.getTransaction().commit();
s.close();
assertUpdateCount( 1 );
assertInsertCount( 1 );
///////////////////////////////////////////////////////////////////////

cleanup();
  }
 
Example 15
Source File: CollectionTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testMerge() throws HibernateException, SQLException {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	User u = new User( "gavin" );
	u.getPermissions().add( new Permission( "obnoxiousness" ) );
	u.getPermissions().add( new Permission( "pigheadedness" ) );
	s.persist( u );
	t.commit();
	s.close();

	s = openSession();
	t = s.beginTransaction();
	User u2 = ( User ) s.createCriteria( User.class ).uniqueResult();
	u2.setPermissions( null ); //forces one shot delete
	s.merge( u );
	t.commit();
	s.close();

	u.getPermissions().add( new Permission( "silliness" ) );

	s = openSession();
	t = s.beginTransaction();
	s.merge( u );
	t.commit();
	s.close();

	s = openSession();
	t = s.beginTransaction();
	u2 = ( User ) s.createCriteria( User.class ).uniqueResult();
	assertEquals( u2.getPermissions().size(), 3 );
	assertEquals( ( ( Permission ) u2.getPermissions().get( 0 ) ).getType(), "obnoxiousness" );
	assertEquals( ( ( Permission ) u2.getPermissions().get( 2 ) ).getType(), "silliness" );
	t.commit();
	s.close();

	s = openSession();
	t = s.beginTransaction();
	s.delete( u2 );
	s.flush();
	t.commit();
	s.close();

}
 
Example 16
Source File: MergeTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testMergeDeepTree() {

		clearCounts();

		Session s = openSession();
		Transaction tx = s.beginTransaction();
		Node root = new Node("root");
		Node child = new Node("child");
		Node grandchild = new Node("grandchild");
		root.addChild(child);
		child.addChild(grandchild);
		s.merge(root);
		tx.commit();
		s.close();

		assertInsertCount(3);
		assertUpdateCount(0);
		clearCounts();

		grandchild.setDescription("the grand child");
		Node grandchild2 = new Node("grandchild2");
		child.addChild( grandchild2 );

		s = openSession();
		tx = s.beginTransaction();
		s.merge(root);
		tx.commit();
		s.close();

		assertInsertCount(1);
		assertUpdateCount(1);
		clearCounts();

		Node child2 = new Node("child2");
		Node grandchild3 = new Node("grandchild3");
		child2.addChild( grandchild3 );
		root.addChild(child2);

		s = openSession();
		tx = s.beginTransaction();
		s.merge(root);
		tx.commit();
		s.close();

		assertInsertCount(2);
		assertUpdateCount(0);
		clearCounts();

		s = openSession();
		tx = s.beginTransaction();
		s.delete(grandchild);
		s.delete(grandchild2);
		s.delete(grandchild3);
		s.delete(child);
		s.delete(child2);
		s.delete(root);
		tx.commit();
		s.close();

	}
 
Example 17
Source File: MergeTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testMergeDeepTreeWithGeneratedId() {

		clearCounts();

		Session s = openSession();
		Transaction tx = s.beginTransaction();
		NumberedNode root = new NumberedNode("root");
		NumberedNode child = new NumberedNode("child");
		NumberedNode grandchild = new NumberedNode("grandchild");
		root.addChild(child);
		child.addChild(grandchild);
		root = (NumberedNode) s.merge(root);
		tx.commit();
		s.close();

		assertInsertCount(3);
		assertUpdateCount(0);
		clearCounts();

		child = (NumberedNode) root.getChildren().iterator().next();
		grandchild = (NumberedNode) child.getChildren().iterator().next();
		grandchild.setDescription("the grand child");
		NumberedNode grandchild2 = new NumberedNode("grandchild2");
		child.addChild( grandchild2 );

		s = openSession();
		tx = s.beginTransaction();
		root = (NumberedNode) s.merge(root);
		tx.commit();
		s.close();

		assertInsertCount(1);
		assertUpdateCount(1);
		clearCounts();

		getSessions().evict(NumberedNode.class);

		NumberedNode child2 = new NumberedNode("child2");
		NumberedNode grandchild3 = new NumberedNode("grandchild3");
		child2.addChild( grandchild3 );
		root.addChild(child2);

		s = openSession();
		tx = s.beginTransaction();
		root = (NumberedNode) s.merge(root);
		tx.commit();
		s.close();

		assertInsertCount(2);
		assertUpdateCount(0);
		clearCounts();

		s = openSession();
		tx = s.beginTransaction();
		s.createQuery("delete from NumberedNode where name like 'grand%'").executeUpdate();
		s.createQuery("delete from NumberedNode where name like 'child%'").executeUpdate();
		s.createQuery("delete from NumberedNode").executeUpdate();
		tx.commit();
		s.close();

	}
 
Example 18
Source File: AbsSupportDao.java    From jeesupport with MIT License 4 votes vote down vote up
@Override
public void update( String _db , Object _entity ) {
	Session ses = _get_session( _db );
	ses.merge( _entity );
}
 
Example 19
Source File: Main.java    From maven-framework-project with MIT License 3 votes vote down vote up
private static Employee update(Employee employee) {
	SessionFactory sf = HibernateUtil.getSessionFactory();
	Session session = sf.openSession();

	session.beginTransaction();

	session.merge(employee);
	
	session.getTransaction().commit();
	
	session.close();
	return employee;

}
 
Example 20
Source File: HibernateUtil.java    From AlgoTrader with GNU General Public License v2.0 2 votes vote down vote up
public static Object merge(SessionFactory sessionFactory, Object target) {

		Session session = sessionFactory.getCurrentSession();

		return session.merge(target);
	}