下面列出了org.hibernate.Session#persist ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public long persistData() {
final Project project = new Project();
project.setName( "Foo Project" );
final User user = new User();
user.setName( "Brett Meyer" );
final Skill skill = new Skill();
skill.setName( "Hibernate ORM" );
user.getSkills().add( skill );
user.getProjects().add( project );
project.setAssignee( user );
final Session s = openSession();
s.getTransaction().begin();
s.persist(skill);
s.persist(user);
s.persist(project);
s.getTransaction().commit();
s.close();
return project.getId();
}
public void testPersistOutsideTransactionCascadedToManyToOne() {
long initialInsertCount = sfi().getStatistics().getEntityInsertCount();
Session s = openSession();
MyEntity myEntity = new MyEntity( "test-persist");
myEntity.setSibling( new MySibling( "test-persist-sibling-out" ) );
s.persist( myEntity );
assertEquals( "persist on identity column not delayed", initialInsertCount, sfi().getStatistics().getEntityInsertCount() );
assertNull( myEntity.getId() );
s.flush();
assertEquals( "delayed persist insert not executed on flush", initialInsertCount + 2, sfi().getStatistics().getEntityInsertCount() );
s.close();
s = openSession();
s.beginTransaction();
s.createQuery( "delete MyEntity" ).executeUpdate();
s.createQuery( "delete MySibling" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
public void testImplicitJoin() throws Exception {
Session session = openSession();
Transaction t = session.beginTransaction();
Animal a = new Animal();
a.setBodyWeight(0.5f);
a.setBodyWeight(1.5f);
Animal b = new Animal();
Animal mother = new Animal();
mother.setBodyWeight(10.0f);
mother.addOffspring(a);
mother.addOffspring(b);
session.persist(a);
session.persist(b);
session.persist(mother);
List list = session.createQuery("from Animal a where a.mother.bodyWeight < 2.0 or a.mother.bodyWeight > 9.0").list();
assertEquals( list.size(), 2 );
list = session.createQuery("from Animal a where a.mother.bodyWeight > 2.0 and a.mother.bodyWeight > 9.0").list();
assertEquals( list.size(), 2 );
session.delete(b);
session.delete(a);
session.delete(mother);
t.commit();
session.close();
}
public void testOrphanDeleteAfterPersist() {
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 );
prod.getParts().remove( mapKey );
t.commit();
session.close();
session = openSession();
t = session.beginTransaction();
session.delete( session.get(Product.class, "Widget") );
t.commit();
session.close();
}
private Continent fillDb(Session s) {
Continent europe = new Continent();
europe.setName("Europe");
Country france = new Country();
france.setName("France");
europe.setCountries( new HashSet() );
europe.getCountries().add(france);
s.persist(france);
s.persist(europe);
return europe;
}
/**
* Insert skill.
*
* @param skill the skill
* @throws SQLException the SQL exception
*/
private static void insertSkill(Skill skill) throws SQLException {
Session session = openSession();
session.getTransaction().begin();
session.persist( skill );
session.getTransaction().commit();
}
public void testNoExtraUpdatesOnMergeVersioned() throws Exception {
Session s = openSession();
s.beginTransaction();
VersionedEntity entity = new VersionedEntity( "entity", "entity" );
s.persist( entity );
s.getTransaction().commit();
s.close();
clearCounts();
// entity 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 mergedEntity = ( VersionedEntity ) s.merge( entity );
s.getTransaction().commit();
s.close();
assertUpdateCount( 0 );
assertInsertCount( 0 );
assertEquals( "unexpected version increment", entity.getVersion(), mergedEntity.getVersion() );
///////////////////////////////////////////////////////////////////////
// as a control measure, now update the node while it is detached and
// make sure we get an update as a result...
entity.setName( "new name" );
s = openSession();
s.beginTransaction();
entity = ( VersionedEntity ) s.merge( entity );
s.getTransaction().commit();
s.close();
assertUpdateCount( 1 );
assertInsertCount( 0 );
///////////////////////////////////////////////////////////////////////
cleanup();
}
public void testMerging() {
// Test HHH-799
Session s = openSession();
Transaction t = s.beginTransaction();
Course course = new Course( "EN-101", "BA", "preparatory english" );
s.persist( course );
t.commit();
s.close();
String newDesc = "basic preparatory english";
course.setDescription( newDesc );
s = openSession();
t = s.beginTransaction();
Course c = (Course) s.merge( course );
assertEquals( "description not merged", newDesc, c.getDescription() );
t.commit();
s.close();
s = openSession();
t = s.beginTransaction();
Course cid = new Course( "EN-101", "BA", null );
course = ( Course ) s.get( Course.class, cid );
assertEquals( "description not merged", newDesc, course.getDescription() );
s.delete( course );
t.commit();
s.close();
}
public void testManyToOneGeneratedIds() {
// NOTES: Child defines a many-to-one back to its Parent. This
// association does not define persist cascading (which is natural;
// a child should not be able to create its parent).
try {
Session s = openSession();
s.beginTransaction();
Parent p = new Parent( "parent" );
Child c = new Child( "child" );
c.setParent( p );
s.persist( c );
try {
s.getTransaction().commit();
fail( "expecting TransientObjectException on flush" );
}
catch( TransientObjectException e ) {
// expected result
log.trace( "handled expected exception", e );
s.getTransaction().rollback();
}
finally {
s.close();
}
}
finally {
cleanupData();
}
}
public void testSelectClauseImplicitJoinWithIterate() {
Session s = openSession();
Transaction t = s.beginTransaction();
Zoo zoo = new Zoo();
zoo.setName("The Zoo");
zoo.setMammals( new HashMap() );
zoo.setAnimals( new HashMap() );
Mammal plat = new Mammal();
plat.setBodyWeight( 11f );
plat.setDescription( "Platypus" );
plat.setZoo(zoo);
plat.setSerialNumber("plat123");
zoo.getMammals().put("Platypus", plat);
zoo.getAnimals().put("plat123", plat);
s.persist( plat );
s.persist(zoo);
s.flush();
s.clear();
Query q = s.createQuery("select distinct a.zoo from Animal a where a.zoo is not null");
Type type = q.getReturnTypes()[0];
assertTrue( type instanceof ManyToOneType );
assertEquals( ( (ManyToOneType) type ).getAssociatedEntityName(), "org.hibernate.test.hql.Zoo" );
zoo = (Zoo) q
.iterate().next();
assertEquals( zoo.getMammals().size(), 1 );
assertEquals( zoo.getAnimals().size(), 1 );
s.clear();
s.delete(plat);
s.delete(zoo);
t.commit();
s.close();
}
public void testMergeBidiPrimayKeyOneToOne() throws Exception {
Session s = openSession();
s.beginTransaction();
Person p = new Person( "steve" );
new PersonalDetails( "I have big feet", p );
s.persist( p );
s.getTransaction().commit();
s.close();
clearCounts();
p.getDetails().setSomePersonalDetail( p.getDetails().getSomePersonalDetail() + " and big hands too" );
s = openSession();
s.beginTransaction();
p = ( Person ) s.merge( p );
s.getTransaction().commit();
s.close();
assertInsertCount( 0 );
assertUpdateCount( 1 );
assertDeleteCount( 0 );
s = openSession();
s.beginTransaction();
s.delete( p );
s.getTransaction().commit();
s.close();
}
@Transactional
@Override
public void setCourse(Tblstudentgrades enrolledCourse) {
Session session = this.sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.persist(enrolledCourse);
transaction.commit();
session.close();
}
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();
}
public void testCollectionVersion() throws Exception {
Session s = openSession();
Transaction t = s.beginTransaction();
User steve = new User( "steve" );
s.persist( steve );
Group admin = new Group( "admin" );
s.persist( admin );
t.commit();
s.close();
byte[] steveTimestamp = steve.getTimestamp();
s = openSession();
t = s.beginTransaction();
steve = ( User ) s.get( User.class, steve.getId() );
admin = ( Group ) s.get( Group.class, admin.getId() );
steve.getGroups().add( admin );
admin.getUsers().add( steve );
t.commit();
s.close();
assertFalse( "owner version not incremented", Hibernate.BINARY.isEqual( steveTimestamp, steve.getTimestamp() ) );
steveTimestamp = steve.getTimestamp();
s = openSession();
t = s.beginTransaction();
steve = ( User ) s.get( User.class, steve.getId() );
steve.getGroups().clear();
t.commit();
s.close();
assertFalse( "owner version not incremented", Hibernate.BINARY.isEqual( steveTimestamp, steve.getTimestamp() ) );
s = openSession();
t = s.beginTransaction();
s.delete( s.load( User.class, steve.getId() ) );
s.delete( s.load( Group.class, admin.getId() ) );
t.commit();
s.close();
}
@Test
public void testBiDirManyToOneInsertUpdateFalse() throws Exception {
final Session session = openSession();
Transaction tx = session.beginTransaction();
Beer hoegaarden = new Beer();
Brewery hoeBrewery = new Brewery();
hoeBrewery.getBeers().add( hoegaarden );
hoegaarden.setBrewery( hoeBrewery );
session.persist( hoeBrewery );
tx.commit();
session.clear();
tx = session.beginTransaction();
hoegaarden = get( session, Beer.class, hoegaarden.getId() );
assertThat( hoegaarden ).isNotNull();
assertThat( hoegaarden.getBrewery() ).isNotNull();
assertThat( hoegaarden.getBrewery().getBeers() )
.hasSize( 1 )
.containsOnly( hoegaarden );
Beer citron = new Beer();
hoeBrewery = hoegaarden.getBrewery();
hoeBrewery.getBeers().remove( hoegaarden );
hoeBrewery.getBeers().add( citron );
citron.setBrewery( hoeBrewery );
session.delete( hoegaarden );
tx.commit();
session.clear();
tx = session.beginTransaction();
citron = get( session, Beer.class, citron.getId() );
assertThat( citron.getBrewery().getBeers() )
.hasSize( 1 )
.containsOnly( citron );
hoeBrewery = citron.getBrewery();
citron.setBrewery( null );
hoeBrewery.getBeers().clear();
session.delete( citron );
session.delete( hoeBrewery );
tx.commit();
session.close();
checkCleanCache();
}
public void testPolymorphism() {
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();
s = openSession();
t = s.beginTransaction();
Course ucid = new Course("mat2000", "Monash", null);
Course cid = new Course("eng5000", "BHS", null);
Course luc = (Course) s.load(Course.class, ucid);
Course lc = (Course) s.load(Course.class, cid);
assertFalse( Hibernate.isInitialized(luc) );
assertFalse( Hibernate.isInitialized(lc) );
assertEquals( UniversityCourse.class, Hibernate.getClass(luc) );
assertEquals( Course.class, Hibernate.getClass(lc) );
assertSame( ( (HibernateProxy) lc ).getHibernateLazyInitializer().getImplementation(), cid );
assertEquals( c.getCourseCode(), "eng5000" );
assertEquals( uc.getCourseCode(), "mat2000" );
t.commit();
s.close();
s = openSession();
t = s.beginTransaction();
ucid = new Course("mat2000", "Monash", null);
cid = new Course("eng5000", "BHS", null);
luc = (Course) s.get(Course.class, ucid);
lc = (Course) s.get(Course.class, cid);
assertTrue( Hibernate.isInitialized(luc) );
assertTrue( Hibernate.isInitialized(lc) );
assertEquals( UniversityCourse.class, Hibernate.getClass(luc) );
assertEquals( Course.class, Hibernate.getClass(lc) );
assertSame( lc, cid );
assertEquals( c.getCourseCode(), "eng5000" );
assertEquals( uc.getCourseCode(), "mat2000" );
t.commit();
s.close();
s = openSession();
t = s.beginTransaction();
List list = s.createQuery("from Course order by courseCode").list();
assertTrue( list.get(0) instanceof Course );
assertTrue( list.get(1) instanceof UniversityCourse );
c = (Course) list.get(0);
uc = (UniversityCourse) list.get(1);
assertEquals( c.getCourseCode(), "eng5000" );
assertEquals( uc.getCourseCode(), "mat2000" );
t.commit();
s.close();
c.setDescription("Grade 5 English");
uc.setDescription("Second year mathematics");
s = openSession();
t = s.beginTransaction();
s.saveOrUpdate(c);
s.saveOrUpdate(uc);
t.commit();
s.close();
s = openSession();
t = s.beginTransaction();
s.delete(c);
s.delete(uc);
t.commit();
s.close();
}
public void testComponentPropertyRef() {
Person p = new Person();
p.setIdentity( new Identity() );
Account a = new Account();
a.setNumber("123-12345-1236");
a.setOwner(p);
p.getIdentity().setName("Gavin");
p.getIdentity().setSsn("123-12-1234");
Session s = openSession();
Transaction tx = s.beginTransaction();
s.persist(p);
s.persist(a);
s.flush();
s.clear();
a = (Account) s.createQuery("from Account a left join fetch a.owner").uniqueResult();
assertTrue( Hibernate.isInitialized( a.getOwner() ) );
assertNotNull( a.getOwner() );
assertEquals( "Gavin", a.getOwner().getIdentity().getName() );
s.clear();
a = (Account) s.get(Account.class, "123-12345-1236");
assertFalse( Hibernate.isInitialized( a.getOwner() ) );
assertNotNull( a.getOwner() );
assertEquals( "Gavin", a.getOwner().getIdentity().getName() );
assertTrue( Hibernate.isInitialized( a.getOwner() ) );
s.clear();
getSessions().evict(Account.class);
getSessions().evict(Person.class);
a = (Account) s.get(Account.class, "123-12345-1236");
assertTrue( Hibernate.isInitialized( a.getOwner() ) );
assertNotNull( a.getOwner() );
assertEquals( "Gavin", a.getOwner().getIdentity().getName() );
assertTrue( Hibernate.isInitialized( a.getOwner() ) );
s.delete( a );
s.delete( a.getOwner() );
tx.commit();
s.close();
}
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();
}
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();
}
public void testConcurrentCachedQueries() throws Exception {
DummyTransactionManager.INSTANCE.begin();
Session s = openSession();
Map foo = new HashMap();
foo.put( "name", "Foo" );
foo.put( "description", "a big foo" );
s.persist( "Item", foo );
Map bar = new HashMap();
bar.put( "name", "Bar" );
bar.put( "description", "a small bar" );
s.persist( "Item", bar );
DummyTransactionManager.INSTANCE.commit();
synchronized ( this ) {
wait( 1000 );
}
getSessions().getStatistics().clear();
getSessions().evictEntity( "Item" );
DummyTransactionManager.INSTANCE.begin();
Session s4 = openSession();
Transaction tx4 = DummyTransactionManager.INSTANCE.suspend();
DummyTransactionManager.INSTANCE.begin();
Session s1 = openSession();
List r1 = s1.createCriteria( "Item" ).addOrder( Order.asc( "description" ) )
.setCacheable( true ).list();
assertEquals( r1.size(), 2 );
Transaction tx1 = DummyTransactionManager.INSTANCE.suspend();
DummyTransactionManager.INSTANCE.begin();
Session s2 = openSession();
List r2 = s2.createCriteria( "Item" ).addOrder( Order.asc( "description" ) )
.setCacheable( true ).list();
assertEquals( r2.size(), 2 );
DummyTransactionManager.INSTANCE.commit();
assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 2 );
assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 );
assertEquals( getSessions().getStatistics().getEntityLoadCount(), 2 );
assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 );
assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 1 );
assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 1 );
assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 1 );
assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 1 );
DummyTransactionManager.INSTANCE.resume( tx1 );
tx1.commit();
DummyTransactionManager.INSTANCE.begin();
Session s3 = openSession();
s3.createCriteria( "Item" ).addOrder( Order.asc( "description" ) )
.setCacheable( true ).list();
DummyTransactionManager.INSTANCE.commit();
assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 4 );
assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 );
assertEquals( getSessions().getStatistics().getEntityLoadCount(), 2 );
assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 );
assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 1 );
assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 1 );
assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 2 );
assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 1 );
DummyTransactionManager.INSTANCE.resume( tx4 );
List r4 = s4.createCriteria( "Item" ).addOrder( Order.asc( "description" ) )
.setCacheable( true ).list();
assertEquals( r4.size(), 2 );
tx4.commit();
assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 6 );
assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 );
assertEquals( getSessions().getStatistics().getEntityLoadCount(), 2 );
assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 );
assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 1 );
assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 1 );
assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 3 );
assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 1 );
DummyTransactionManager.INSTANCE.begin();
s = openSession();
s.createQuery( "delete from Item" ).executeUpdate();
DummyTransactionManager.INSTANCE.commit();
}