下面列出了怎么用org.hibernate.FetchMode的API类实例代码及写法,或者点击链接到github查看源代码。
private static void bindFetchProfile(FetchProfile fetchProfileAnnotation, MetadataBuildingContext context) {
for ( FetchProfile.FetchOverride fetch : fetchProfileAnnotation.fetchOverrides() ) {
org.hibernate.annotations.FetchMode mode = fetch.mode();
if ( !mode.equals( org.hibernate.annotations.FetchMode.JOIN ) ) {
throw new MappingException( "Only FetchMode.JOIN is currently supported" );
}
context.getMetadataCollector().addSecondPass(
new VerifyFetchProfileReferenceSecondPass(
fetchProfileAnnotation.name(),
fetch,
context
)
);
}
}
@SuppressWarnings("unchecked")
public List<User> getUsers() {
final Session session = openSession();
session.getTransaction().begin();
final List<User> users = session
.createCriteria( User.class )
.setFetchMode( "communityMemberships", FetchMode.SELECT ) // not necessary (default)
.list();
// init
users.get( 0 ).getCommunityMemberships().size();
users.get( 1 ).getCommunityMemberships().size();
session.getTransaction().commit();
return users;
}
/**
* {@inheritDoc}
*/
@Override
public WallItemComment getWallItemComment(final long wallItemCommentId) {
final HibernateCallback<List<WallItemComment>> hcb = session -> session.createCriteria(WallItemComment.class)
.add(Restrictions.eq(ID, wallItemCommentId))
.setFetchMode("wallItem", FetchMode.JOIN)
.list();
final List<WallItemComment> comments = getHibernateTemplate().execute(hcb);
if (comments.size() > 0) {
return comments.get(0);
} else {
return null;
}
}
/**
* Determine the appropriate associationType of join (if any) to use to fetch the
* given association.
*
* @param associationType The association associationType.
* @param config The metadata-defined fetch mode.
* @param path The path to the association
* @param lhsTable The owner table
* @param lhsColumns The owner join columns
* @param nullable Is the association nullable.
* @param currentDepth Current join depth
* @param cascadeStyle The metadata-defined cascade style.
*
* @return type of join to use ({@link org.hibernate.sql.JoinType#INNER_JOIN},
* {@link org.hibernate.sql.JoinType#LEFT_OUTER_JOIN}, or -1 to indicate no joining.
*
* @throws MappingException ??
*/
protected JoinType getJoinType(
AssociationType associationType,
FetchMode config,
PropertyPath path,
String lhsTable,
String[] lhsColumns,
boolean nullable,
int currentDepth,
CascadeStyle cascadeStyle) throws MappingException {
if ( !isJoinedFetchEnabled( associationType, config, cascadeStyle ) ) {
return JoinType.NONE;
}
if ( isTooDeep( currentDepth ) || ( associationType.isCollectionType() && isTooManyCollections() ) ) {
return JoinType.NONE;
}
if ( isDuplicateAssociation( lhsTable, lhsColumns, associationType ) ) {
return JoinType.NONE;
}
return getJoinType( nullable, currentDepth );
}
/**
* Does the mapping, and Hibernate default semantics, specify that
* this association should be fetched by outer joining
*/
protected boolean isJoinedFetchEnabledInMapping(FetchMode config, AssociationType type)
throws MappingException {
if ( !type.isEntityType() && !type.isCollectionType() ) {
return false;
}
else {
if ( config == FetchMode.JOIN ) {
return true;
}
if ( config == FetchMode.SELECT ) {
return false;
}
if ( type.isEntityType() ) {
//TODO: look at the owning property and check that it
// isn't lazy (by instrumentation)
EntityType entityType = (EntityType) type;
EntityPersister persister = getFactory().getEntityPersister( entityType.getAssociatedEntityName() );
return !persister.hasProxy();
}
else {
return false;
}
}
}
@Override
protected JoinType getJoinType(
AssociationType associationType,
FetchMode config,
PropertyPath path,
String lhsTable,
String[] lhsColumns,
boolean nullable,
int currentDepth,
CascadeStyle cascadeStyle) throws MappingException {
return getJoinType(
null,
path,
-1,
associationType,
config,
cascadeStyle,
lhsTable,
lhsColumns,
nullable,
currentDepth
);
}
/**
* getSyllabiForSyllabusItem returns the collection of syllabi
* @param syllabusItem
*/
public Set getSyllabiForSyllabusItem(final SyllabusItem syllabusItem)
{
if (syllabusItem == null)
{
throw new IllegalArgumentException("Null Argument");
}
else
{
HibernateCallback<Set> hcb = session -> {
// get syllabi in an eager fetch mode
Criteria crit = session.createCriteria(SyllabusItemImpl.class)
.add(Expression.eq(SURROGATE_KEY, syllabusItem.getSurrogateKey()))
.setFetchMode(SYLLABI, FetchMode.EAGER);
SyllabusItem syllabusItem1 = (SyllabusItem) crit.uniqueResult();
if (syllabusItem1 != null){
return syllabusItem1.getSyllabi();
}
return new TreeSet();
};
return getHibernateTemplate().execute(hcb);
}
}
public BaselineAttributeInformation(
boolean lazy,
boolean insertable,
boolean updateable,
ValueGeneration valueGenerationStrategy,
boolean nullable,
boolean dirtyCheckable,
boolean versionable,
CascadeStyle cascadeStyle,
FetchMode fetchMode) {
this.lazy = lazy;
this.insertable = insertable;
this.updateable = updateable;
this.valueGenerationStrategy = valueGenerationStrategy;
this.nullable = nullable;
this.dirtyCheckable = dirtyCheckable;
this.versionable = versionable;
this.cascadeStyle = cascadeStyle;
this.fetchMode = fetchMode;
}
public List<JobUsage> getUsage(final String userName, final Date startDate, final Date endDate) {
return executeReadOnlyTransaction(session -> {
if (startDate == null || endDate == null) {
throw new DatabaseManagerException("Start and end dates can't be null.");
}
Criteria criteria = session.createCriteria(JobData.class);
criteria.setFetchMode("tasks", FetchMode.JOIN);
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
if (userName != null) {
criteria.add(Restrictions.eq("owner", userName));
}
// exclude killed but not started jobs
criteria.add(Restrictions.gt("startTime", -1L));
criteria.add(Restrictions.and(Restrictions.ge("finishedTime", startDate.getTime()),
Restrictions.le("finishedTime", endDate.getTime())));
List<JobData> jobsList = criteria.list();
return jobsList.stream().map(JobData::toJobUsage).collect(Collectors.toList());
});
}
public void testWhere() {
Session s = openSession();
s.getTransaction().begin();
File parent = new File("parent", null);
s.persist( parent );
s.persist( new File("child", parent) );
File deletedChild = new File("deleted child", parent);
deletedChild.setDeleted(true);
s.persist( deletedChild );
File deletedParent = new File("deleted parent", null);
deletedParent.setDeleted(true);
s.persist( deletedParent );
s.flush();
s.clear();
parent = (File) s.createCriteria(File.class)
.setFetchMode("children", FetchMode.JOIN)
.add( Restrictions.isNull("parent") )
.uniqueResult();
assertEquals( parent.getChildren().size(), 1 );
s.clear();
parent = (File) s.createQuery("from File f left join fetch f.children where f.parent is null")
.uniqueResult();
assertEquals( parent.getChildren().size(), 1 );
s.getTransaction().commit();
s.close();
}
@SuppressWarnings("unchecked")
public List<User> getUsers() {
final Session session = openSession();
session.getTransaction().begin();
// Note: Can use multiple associations with JOIN fetch mode if they are *not*, but results in a cartesian product!
final List<User> users = session
.createCriteria( User.class )
.setFetchMode( "projectsSubmitted", FetchMode.JOIN )
// .setFetchMode( "projectsOrganized", FetchMode.JOIN )
.list();
session.getTransaction().commit();
return users;
}
public void testNonlazyCollection() throws Exception {
Session s = openSession();
Baz baz = new Baz();
s.save(baz);
s.flush();
s.connection().commit();
s.close();
s = openSession();
baz = (Baz) s.createCriteria(Baz.class)
//.setComment("criteria test")
.setFetchMode("stringDateMap", FetchMode.EAGER)
.uniqueResult();
assertTrue( Hibernate.isInitialized( baz.getFooToGlarch() ) );
assertTrue( Hibernate.isInitialized( baz.getFooComponentToFoo() ) );
assertTrue( !Hibernate.isInitialized( baz.getStringSet() ) );
assertTrue( Hibernate.isInitialized( baz.getStringDateMap() ) );
s.delete(baz);
s.flush();
s.connection().commit();
s.close();
}
public SortedSet getStudentGradesForGradebook(final Gradebook gradebook)
throws IllegalArgumentException {
if (gradebook == null) {
throw new IllegalArgumentException("Null Argument");
} else {
HibernateCallback hcb = session -> {
// get syllabi in an eager fetch mode
Criteria crit = session.createCriteria(Gradebook.class).add(
Expression.eq(ID, gradebook.getId())).setFetchMode(STUDENTS,
FetchMode.EAGER);
Gradebook grades = (Gradebook) crit.uniqueResult();
if (grades != null) {
return grades.getStudents();
}
return new TreeSet();
};
return (SortedSet) getHibernateTemplate().execute(hcb);
}
}
/**
*/
protected void bindManyToOneValues(org.grails.datastore.mapping.model.types.Association property, ManyToOne manyToOne) {
PropertyConfig config = getPropertyConfig(property);
if (config != null && config.getFetchMode() != null) {
manyToOne.setFetchMode(config.getFetchMode());
}
else {
manyToOne.setFetchMode(FetchMode.DEFAULT);
}
manyToOne.setLazy(getLaziness(property));
if (config != null) {
manyToOne.setIgnoreNotFound(config.getIgnoreNotFound());
}
// set referenced entity
manyToOne.setReferencedEntityName(property.getAssociatedEntity().getName());
}
/**
* {@inheritDoc}
*/
@Override
public WallItemComment getWallItemComment(final long wallItemCommentId) {
final HibernateCallback<List<WallItemComment>> hcb = session -> session.createCriteria(WallItemComment.class)
.add(Restrictions.eq(ID, wallItemCommentId))
.setFetchMode("wallItem", FetchMode.JOIN)
.list();
final List<WallItemComment> comments = getHibernateTemplate().execute(hcb);
if (comments.size() > 0) {
return comments.get(0);
} else {
return null;
}
}
/**
* Find all the groups that need to be end dated.
* @return A List of groups to be end dated.
*/
@SuppressWarnings("unchecked")
public List<TargetGroup> findEndedGroups() {
return getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session aSession) throws HibernateException, SQLException {
List<TargetGroup> results = aSession.createCriteria(TargetGroup.class)
.add(Restrictions.ne("state", TargetGroup.STATE_ACTIVE))
.add(Restrictions.lt("toDate", new Date()))
.setFetchMode("schedules", FetchMode.JOIN)
.setFetchMode("parents", FetchMode.JOIN)
.setFetchMode("children", FetchMode.JOIN)
.list();
log.debug("Found " + results.size() + " groups that need to be unscheduled");
return results;
}
});
}
/**
* The @GET annotation causes this method to be invoked whenever an HTTP GET request is received for
* the registered URL.
*/
@GET
public App getAppData( @PathParam("appId") Long appId ) {
// Start a Hibernate session, using the Hibernate SessionFactory created by MasterNodeInitializer or SlaveNodeInitializer.
String mode = (String) context.getAttribute("mode");
Session session = mode.equals("master") ? MasterNodeInitializer.openSession() : SlaveNodeInitializer.openSession();
session.beginTransaction();
// Fetch an App for the given ID, using eager fetching. The conversion to JSON happens after the
// Hibernate Session is closed... so if lazy fetching were used, then the JSON converter would fail
// when trying to access associated objects.
Criteria criteria = session.createCriteria(App.class);
criteria.add( Restrictions.eq("id", appId) );
criteria.setFetchMode("supportedDevices", FetchMode.SELECT);
criteria.setFetchMode("customerReviews", FetchMode.SELECT);
App app = (App) criteria.uniqueResult();
// Cleanup Hibernate
session.getTransaction().commit();
session.clear();
session.close();
return app;
}
/**
* Get the join type (inner, outer, etc) or -1 if the
* association should not be joined. Override on
* subclasses.
*/
protected int getJoinType(
AssociationType type,
FetchMode config,
String path,
String lhsTable,
String[] lhsColumns,
boolean nullable,
int currentDepth,
CascadeStyle cascadeStyle)
throws MappingException {
if ( !isJoinedFetchEnabled(type, config, cascadeStyle) ) return -1;
if ( isTooDeep(currentDepth) || ( type.isCollectionType() && isTooManyCollections() ) ) return -1;
final boolean dupe = isDuplicateAssociation(lhsTable, lhsColumns, type);
if (dupe) return -1;
return getJoinType(nullable, currentDepth);
}
/**
* Does the mapping, and Hibernate default semantics, specify that
* this association should be fetched by outer joining
*/
protected boolean isJoinedFetchEnabledInMapping(FetchMode config, AssociationType type)
throws MappingException {
if ( !type.isEntityType() && !type.isCollectionType() ) {
return false;
}
else {
if (config==FetchMode.JOIN) return true;
if (config==FetchMode.SELECT) return false;
if ( type.isEntityType() ) {
//TODO: look at the owning property and check that it
// isn't lazy (by instrumentation)
EntityType entityType =(EntityType) type;
EntityPersister persister = getFactory().getEntityPersister( entityType.getAssociatedEntityName() );
return !persister.hasProxy();
}
else {
return false;
}
}
}
public Set getSyllabusAttachmentsForSyllabusData(final SyllabusData syllabusData)
{
if (syllabusData == null)
{
throw new IllegalArgumentException("Null Argument");
}
else
{
HibernateCallback<Set<SyllabusAttachment>> hcb = session -> {
Criteria crit = session.createCriteria(SyllabusDataImpl.class)
.add(Expression.eq(SYLLABUS_DATA_ID, syllabusData.getSyllabusId()))
.setFetchMode(ATTACHMENTS, FetchMode.EAGER);
SyllabusData syllabusData1 = (SyllabusData) crit.uniqueResult();
if (syllabusData1 != null){
return syllabusData1.getAttachments();
}
return new TreeSet();
};
return getHibernateTemplate().execute(hcb);
}
}
/**
* The @GET annotation causes this method to be invoked whenever an HTTP GET request is received for
* the registered URL.
*/
@GET
public App getAppData( @PathParam("appId") Long appId ) {
// Initialize Hibernate
Session session = StartupDataLoader.openSession();
session.beginTransaction();
// Fetch an App for the given ID, using eager fetching. The conversion to JSON happens after the
// Hibernate Session is closed... so if lazy fetching were used, then the JSON converter would fail
// when trying to access associated objects.
Criteria criteria = session.createCriteria(App.class);
criteria.add( Restrictions.eq("id", appId) );
criteria.setFetchMode("supportedDevices", FetchMode.SELECT);
criteria.setFetchMode("customerReviews", FetchMode.SELECT);
App app = (App) criteria.uniqueResult();
// Cleanup Hibernate
session.getTransaction().commit();
session.clear();
session.close();
return app;
}
@SuppressWarnings("unchecked")
public Mpp getInfos(MppId medecinePackageID) {
log.debug("Getting infos for Mpp " + medecinePackageID);
Session sess = getSessionFactory().getCurrentSession();
Criteria c = sess.createCriteria(Mpp.class);
c.add(Restrictions.eq("id", medecinePackageID));
c.setFetchMode("mp", FetchMode.JOIN);
List<Mpp> result = c.list();
if (result.size() == 0) {
return null;
}
Validate.isTrue(result.size() == 1, "More than One Mpp found!");
return result.get(0);
}
public void testUnconstrainedOuterJoinFetch() {
Session session = openSession();
Transaction tx = session.beginTransaction();
Person p = new Person("gavin");
p.setEmployeeId("123456");
session.persist(p);
tx.commit();
session.close();
getSessions().evict(Person.class);
session = openSession();
tx = session.beginTransaction();
p = (Person) session.createCriteria(Person.class)
.setFetchMode("employee", FetchMode.JOIN)
.add( Restrictions.idEq("gavin") )
.uniqueResult();
assertNull( p.getEmployee() );
p.setEmployee( new Employee("123456") );
tx.commit();
session.close();
getSessions().evict(Person.class);
session = openSession();
tx = session.beginTransaction();
p = (Person) session.createCriteria(Person.class)
.setFetchMode("employee", FetchMode.JOIN)
.add( Restrictions.idEq("gavin") )
.uniqueResult();
assertTrue( Hibernate.isInitialized( p.getEmployee() ) );
assertNotNull( p.getEmployee() );
session.delete(p);
tx.commit();
session.close();
}
public static FetchMode getFetchMode(FetchType fetch) {
if ( fetch == FetchType.EAGER ) {
return FetchMode.JOIN;
}
else {
return FetchMode.SELECT;
}
}
/**
* Search the Permissions.
* @param aPermissionCriteria The criteria to use to search the permissions.
* @return A Pagination of permission records.
*/
public Pagination searchPermissions(final PermissionCriteria aPermissionCriteria) {
return (Pagination) getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session) {
Criteria query = session.createCriteria(Permission.class);
Criteria cntQuery = session.createCriteria(Permission.class);
if(!nullOrEmpty(aPermissionCriteria.getSiteName())) {
query.createCriteria("site")
.add(Restrictions.ilike("title", aPermissionCriteria.getSiteName(), MatchMode.START));
cntQuery.createCriteria("site")
.add(Restrictions.ilike("title", aPermissionCriteria.getSiteName(), MatchMode.START));
}
if(!nullOrEmpty(aPermissionCriteria.getUrlPattern())) {
query.createCriteria("urls")
.add(Restrictions.ilike("pattern", aPermissionCriteria.getUrlPattern(), MatchMode.START));
cntQuery.createCriteria("urls")
.add(Restrictions.ilike("pattern", aPermissionCriteria.getUrlPattern(), MatchMode.START));
}
if(aPermissionCriteria.getAgencyOid() != null) {
query.createCriteria("owningAgency")
.add(Restrictions.eq("oid", aPermissionCriteria.getAgencyOid()));
cntQuery.createCriteria("owningAgency")
.add(Restrictions.eq("oid", aPermissionCriteria.getAgencyOid()));
}
query.setFetchMode("permissions", FetchMode.JOIN);
cntQuery.setFetchMode("permissions", FetchMode.JOIN);
cntQuery.setProjection(Projections.rowCount());
return new Pagination(cntQuery, query, aPermissionCriteria.getPageNumber(), Constants.GBL_PAGE_SIZE);
}
}
);
}
public void testManyToManyCriteriaJoin() {
Session s = openSession();
Transaction t = s.beginTransaction();
Parent p = new Parent("foo");
p.getChildren().add( new Child("foo1") );
p.getChildren().add( new Child("foo2") );
Parent q = new Parent("bar");
q.getChildren().add( new Child("bar1") );
q.getChildren().add( new Child("bar2") );
q.getMoreChildren().addAll( p.getChildren() );
s.persist(p);
s.persist(q);
t.commit();
s.close();
s = openSession();
t = s.beginTransaction();
List parents = s.createCriteria(Parent.class)
.createCriteria("moreChildren")
.createCriteria("friends")
.addOrder( Order.desc("name") )
.list();
parents = s.createCriteria(Parent.class)
.setFetchMode("moreChildren", FetchMode.JOIN)
.setFetchMode("moreChildren.friends", FetchMode.JOIN)
.addOrder( Order.desc("name") )
.list();
s.delete( parents.get(0) );
s.delete( parents.get(1) );
t.commit();
s.close();
}
protected JoinType getJoinType(
OuterJoinLoadable persister,
PropertyPath path,
int propertyNumber,
AssociationType associationType,
FetchMode metadataFetchMode,
CascadeStyle metadataCascadeStyle,
String lhsTable,
String[] lhsColumns,
boolean nullable,
int currentDepth) throws MappingException {
// NOTE : we override this form here specifically to account for
// fetch profiles.
// TODO : how to best handle criteria queries?
if ( lockOptions.getLockMode().greaterThan( LockMode.READ ) ) {
return JoinType.NONE;
}
if ( isTooDeep( currentDepth )
|| ( associationType.isCollectionType() && isTooManyCollections() ) ) {
return JoinType.NONE;
}
if ( !isJoinedFetchEnabledInMapping( metadataFetchMode, associationType )
&& !isJoinFetchEnabledByProfile( persister, path, propertyNumber ) ) {
return JoinType.NONE;
}
if ( isDuplicateAssociation( lhsTable, lhsColumns, associationType ) ) {
return JoinType.NONE;
}
return getJoinType( nullable, currentDepth );
}
@SuppressWarnings("unchecked")
public Set<SyllabusData> findPublicSyllabusData() {
HibernateCallback<List<SyllabusData>> hcb = session -> {
Criteria crit = session.createCriteria(SyllabusDataImpl.class)
.add(Expression.eq(VIEW, "yes"))
.setFetchMode(ATTACHMENTS, FetchMode.EAGER);
return crit.list();
};
return new HashSet<>(getHibernateTemplate().execute(hcb));
}
protected JoinType getJoinType(
OuterJoinLoadable persister,
PropertyPath path,
int propertyNumber,
AssociationType associationType,
FetchMode metadataFetchMode,
CascadeStyle metadataCascadeStyle,
String lhsTable,
String[] lhsColumns,
boolean nullable,
int currentDepth) throws MappingException {
JoinType joinType = super.getJoinType(
persister,
path,
propertyNumber,
associationType,
metadataFetchMode,
metadataCascadeStyle,
lhsTable,
lhsColumns,
nullable,
currentDepth
);
//we can use an inner join for the many-to-many
if ( joinType==JoinType.LEFT_OUTER_JOIN && path.isRoot() ) {
joinType=JoinType.INNER_JOIN;
}
return joinType;
}
/**
* Constructs NonIdentifierProperty instances.
*
* @param name The name by which the property can be referenced within
* its owner.
* @param type The Hibernate Type of this property.
* @param lazy Should this property be handled lazily?
* @param insertable Is this property an insertable value?
* @param updateable Is this property an updateable value?
* @param valueGenerationStrategy How (if) values for this attribute are generated
* @param nullable Is this property a nullable value?
* @param checkable Is this property a checkable value?
* @param versionable Is this property a versionable value?
* @param cascadeStyle The cascade style for this property's value.
* @param fetchMode Any fetch mode defined for this property
*/
public StandardProperty(
String name,
Type type,
boolean lazy,
boolean insertable,
boolean updateable,
ValueGeneration valueGenerationStrategy,
boolean nullable,
boolean checkable,
boolean versionable,
CascadeStyle cascadeStyle,
FetchMode fetchMode) {
super(
null,
null,
-1,
name,
type,
new BaselineAttributeInformation.Builder()
.setLazy( lazy )
.setInsertable( insertable )
.setUpdateable( updateable )
.setValueGenerationStrategy( valueGenerationStrategy )
.setNullable( nullable )
.setDirtyCheckable( checkable )
.setVersionable( versionable )
.setCascadeStyle( cascadeStyle )
.setFetchMode( fetchMode )
.createInformation()
);
}