Java 类org.hibernate.classic.Session 实例源码
项目:Equella
文件:AddLastActionDate.java
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
{
Query query = session
.createQuery("select i.id, i.moderation.id from Item i where moderating = true or status = 'rejected'");
ScrollableResults results = query.scroll();
while( results.next() )
{
Query upQuery = session
.createQuery("update ModerationStatus m set lastAction = "
+ "(select max(h.date) from Item i join i.history h where i.id = ? and h.type in ('approved','rejected', 'comment') group by i.id) "
+ "where m.id = ?");
upQuery.setParameter(0, results.get(0));
upQuery.setParameter(1, results.get(1));
upQuery.executeUpdate();
}
}
项目:Equella
文件:ReIndexMigration.java
@Override
public void migrate(MigrationResult status) throws Exception
{
runInTransaction(hibernateService.createConfiguration(CurrentDataSource.get(), getDomainClasses())
.getSessionFactory(), new HibernateCall()
{
@SuppressWarnings("nls")
@Override
public void run(Session session) throws Exception
{
session.createSQLQuery("update item set date_for_index = ?").setParameter(0, new Date())
.executeUpdate();
}
});
}
项目:Equella
文件:HibernateMigrationHelper.java
public Collection<? extends String> getAddIndexesRawIfRequired(Session session, String tableName,
String[]... indexes)
{
List<String> sqlStrings = new ArrayList<String>();
final Table table = findTable(tableName);
Map<Set<String>, String> revIndexMap = getExistingIndexes(table, session);
for( String[] index : indexes )
{
Index indexObj = new Index();
indexObj.setTable(table);
indexObj.setName(index[0]);
for( int i = 1; i < index.length; i++ )
{
Column col = new Column(index[i]);
indexObj.addColumn(col);
}
processIndex(table, indexObj, revIndexMap, sqlStrings);
}
return sqlStrings;
}
项目:Equella
文件:ConstraintToAvoidDuplicateNotificationsMigration.java
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
{
// Find dupes and kill them (keep the latest one)
final ScrollableResults dupes = session.createQuery(getDupesFrom() + " ORDER BY n.date DESC").scroll(
ScrollMode.FORWARD_ONLY);
final Set<String> visited = Sets.newHashSet();
while( dupes.next() )
{
final FakeNotification dupe = (FakeNotification) dupes.get(0);
final String key = dupe.itemid + dupe.reason + dupe.userTo + dupe.institution.id;
// Ignore the most recent notification, we'll keep this one
if( !visited.contains(key) )
{
visited.add(key);
}
else
{
session.delete(dupe);
session.flush();
session.clear();
}
result.incrementStatus();
}
}
项目:Equella
文件:IntegrationSessionPrivMigration.java
@SuppressWarnings("unchecked")
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
throws Exception
{
List<FakeAccessExpression> qr = session.createQuery("from AccessExpression where expression = :expression")
.setParameter("expression", SecurityConstants.getRecipient(Recipient.EVERYONE)).list();
FakeAccessExpression everyone = qr.isEmpty() ? createEveryoneExpression(session) : qr.get(0);
List<FakeInstitution> institutions = session.createQuery("FROM Institution").list();
for( FakeInstitution inst : institutions )
{
FakeAccessEntry aclEntry = makeAclEntry(everyone, inst, "INTEGRATION_SELECTION_SESSION");
session.save(aclEntry);
result.incrementStatus();
}
session.flush();
session.clear();
}
项目:Equella
文件:ConvertOauthClientsMigration.java
@SuppressWarnings("unchecked")
private Map<String, String> getLtiRoleConfig(Session session, long institute)
{
List<FakeConfigurationProperty> ltiProps = session
.createQuery(
"FROM ConfigurationProperty WHERE key.institutionId = :inst AND (key.property LIKE :create OR key.property LIKE :instructor OR key.property LIKE :other)")
.setParameter("inst", institute).setParameter("create", PROPERTY_LTI_CREATE_USERS)
.setParameter("instructor", PROPERTY_ROLE_INSTRUCTOR).setParameter("other", PROPERTY_ROLE_OTHER).list();
if( !Check.isEmpty(ltiProps) )
{
Map<String, String> configMap = new HashMap<String, String>();
ltiProps.stream().forEach(c -> configMap.put(c.key.property, c.value));
return configMap;
}
return null;
}
项目:Equella
文件:CALAddNullConstraints.java
@SuppressWarnings("nls")
@Override
public void migrate(MigrationResult status) throws Exception
{
status.setCanRetry(true);
HibernateMigrationHelper helper = createMigrationHelper();
List<String> sql = new ArrayList<String>();
Session session = helper.getFactory().openSession();
ExtendedDialect extDialect = helper.getExtDialect();
if( !extDialect.supportsModifyWithConstraints() )
{
sql.addAll(helper.getDropConstraintsSQL("cal_portion", "item_id"));
sql.addAll(helper.getDropConstraintsSQL("cal_section", "portion_id"));
}
sql.addAll(helper.getAddNotNullSQLIfRequired(session, "cal_portion", "item_id"));
sql.addAll(helper.getAddNotNullSQLIfRequired(session, "cal_section", "portion_id"));
if( !extDialect.supportsModifyWithConstraints() )
{
sql.addAll(helper.getAddIndexesAndConstraintsForColumns("cal_portion", "item_id"));
sql.addAll(helper.getAddIndexesAndConstraintsForColumns("cal_section", "portion_id"));
}
session.close();
runSqlStatements(sql, helper.getFactory(), status, AbstractCreateMigration.KEY_STATUS);
}
项目:LibrarySystem
文件:TestAdmin.java
@Test
public void testSaveAdmin2(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Admin admin = new Admin();
admin.setName("cairou");
admin.setUsername("admin");
admin.setPwd("admin");
Authorization authorization = new Authorization();
authorization.setSuperSet(1);
authorization.setAdmin(admin);
admin.setAuthorization(authorization);
session.save(admin);
transaction.commit();
session.close();
}
项目:Equella
文件:RemoveHierarchyColumnsMigration.java
@SuppressWarnings("unchecked")
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
{
Query query = session.createQuery("FROM HierarchyTopic WHERE key_resources_section_name_id IS NOT NULL"); //$NON-NLS-1$
List<FakeHierarchyTopic> hts = query.list();
for( FakeHierarchyTopic ht : hts )
{
session.delete(ht.keyResourcesSectionName);
ht.keyResourcesSectionName = null;
}
session.flush();
session.clear();
}
项目:Equella
文件:ReplaceDeletedControlsDatabaseMigration.java
@SuppressWarnings("unchecked")
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
throws Exception
{
final List<FakeItemDefinition> itemDefs = session.createQuery("FROM ItemDefinition").list();
final XStream x = ReplaceDeletedControlsXmlMigration.createXStream(xmlHelper);
for( FakeItemDefinition itemDef : itemDefs )
{
final FakeItemdefBlobs blob = itemDef.getSlow();
final String wizXml = blob.getWizard();
final XmlDocument xml = new XmlDocument(wizXml);
final Node wizardNode = xml.node("//slow/wizard");
if( ReplaceDeletedControlsXmlMigration.replaceAllObsoleteControls(xml, wizardNode, x) )
{
blob.setWizard(xml.toString());
session.save(blob);
}
result.incrementStatus();
}
}
项目:Equella
文件:MigrateNotifications2.java
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
{
ScrollableResults scroll = session.createQuery("from Notification").scroll();
while( scroll.next() )
{
FakeNotification note = (FakeNotification) scroll.get(0);
if( note.reason.equals("review") )
{
session.delete(note);
}
else
{
note.itemidOnly = note.itemid;
note.processed = true;
note.batched = false;
session.save(note);
}
session.flush();
session.clear();
result.incrementStatus();
}
}
项目:Equella
文件:AbstractHibernateMigration.java
protected void executeSqlStatements(MigrationResult result, Session session, List<String> sqlStatements)
{
for( String statement : sqlStatements )
{
try
{
session.createSQLQuery(statement).executeUpdate();
result.addLogEntry(new MigrationStatusLog(statement, false));
result.incrementStatus();
}
catch( Exception e )
{
result.setMessage("Error running SQL: '" + statement + "' "); //$NON-NLS-1$ //$NON-NLS-2$
result.addLogEntry(new MigrationStatusLog(statement, true));
throw e;
}
}
}
项目:Equella
文件:ConvertOauthClientsMigration.java
private void convertOauthClientACLs(Session session)
{
@SuppressWarnings("unchecked")
List<FakeAccessEntry> qr = session.createQuery("FROM AccessEntry where privilege LIKE '%OAUTH_CLIENT'").list();
for( FakeAccessEntry entry : qr )
{
FakeAccessEntry newEntry = new FakeAccessEntry();
newEntry.privilege = entry.privilege.replace(OAUTH_PRIVILEGE, LTI_PRIVILEGE);
newEntry.expression = entry.expression;
newEntry.targetObject = entry.targetObject;
newEntry.institution = entry.institution;
newEntry.aclOrder = entry.aclOrder;
newEntry.grantRevoke = entry.grantRevoke;
newEntry.aclPriority = Math.abs(entry.aclPriority) == SecurityConstants.PRIORITY_INSTITUTION
? entry.aclPriority : entry.aclPriority < 0 ? (entry.aclOrder - 4) : (entry.aclPriority + 4);
String aggregateOrdering = String.format("%04d %04d %c",
(newEntry.aclPriority + SecurityConstants.PRIORITY_MAX), newEntry.aclOrder, newEntry.grantRevoke);
newEntry.aggregateOrdering = aggregateOrdering;
session.save(newEntry);
}
}
项目:LibrarySystem
文件:TestBook.java
@Test
public void testSaveBook(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Book book = new Book();
book.setBookName("1111");
BookType type = new BookType();
type.setTypeId(1);
book.setBookType(type);
session.save(book);
transaction.commit();
session.close();
}
项目:LibrarySystem
文件:TestReader.java
@Test
public void getReader(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
String hql= "from Reader r where r.readerId=123 and r.state=1";
List createQuery = session.createQuery(hql).list();
Reader reader = (Reader) createQuery.get(0);
System.out.println(reader);
}
项目:Equella
文件:AddOAuthTokenUniqueConstraintMigration.java
/**
* Syntax OK for Oracle, PostGres SqlServer ...
*/
@Override
public void migrate(MigrationResult status) throws Exception
{
status.setCanRetry(false);
runInTransaction(hibernateService.createConfiguration(CurrentDataSource.get(), getDomainClasses())
.getSessionFactory(), new HibernateCall()
{
@Override
public void run(Session session) throws Exception
{
// Most likely unnecessary, but check for and delete any rows duplicated on user_id + client_id
//@formatter:off
session.createSQLQuery(
"Delete From OAuth_Token Where id in (" +
" Select Oat.id From OAuth_Token Oat " +
" Join OAuth_Token chaff on (" +
" oat.client_id = chaff.client_id and oat.user_id = chaff.user_id)" +
" Where Oat.id <> chaff.id)"
).executeUpdate();
session.createSQLQuery(
"Alter Table OAuth_Token Add Constraint UNIQ_USERID_CLIENTID Unique(user_id, client_id)")
.executeUpdate();
//@formatter:on
}
});
}
项目:Equella
文件:ConvertVarcharDatabaseMigration.java
@Override
protected int countDataMigrations(final HibernateMigrationHelper helper, Session session)
{
final int[] ctr = new int[]{0};
session.doWork(new Work()
{
@Override
public void execute(Connection connection) throws SQLException
{
final DatabaseMetaData metaData = connection.getMetaData();
final String defaultCatalog = helper.getDefaultCatalog();
final String defaultSchema = helper.getDefaultSchema();
final ResultSet tableSet = metaData.getTables(defaultCatalog, defaultSchema, null,
new String[]{"TABLE"});
try
{
while( tableSet.next() )
{
ctr[0]++;
}
}
finally
{
tableSet.close();
}
}
});
return ctr[0];
}
项目:Equella
文件:AddThumbColumnMigration.java
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
{
Query query = session.createQuery("UPDATE Item SET thumb = :value");
query.setParameter("value", "initial");
query.executeUpdate();
}
项目:Equella
文件:AddCommentsSectionToItemSummarySections.java
@SuppressWarnings("unchecked")
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
throws Exception
{
final List<FakeItemdefBlobs> idbs = session.createQuery("FROM ItemdefBlobs").list();
for( FakeItemdefBlobs idb : idbs )
{
addSummarySection(idb, session, result);
}
}
项目:Equella
文件:AddPushToLMSACLMigration.java
private FakeAccessExpression createEveryoneExpression(Session session)
{
FakeAccessExpression everyone = new FakeAccessExpression();
everyone = new FakeAccessExpression();
everyone.dynamic = false;
everyone.expression = "*";
session.save(everyone);
return everyone;
}
项目:Equella
文件:AddPushToLMSACLMigration.java
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
throws Exception
{
@SuppressWarnings("unchecked")
List<FakeAccessExpression> qr = session.createQuery("from AccessExpression where expression = '*'").list();
FakeAccessExpression everyone = qr.isEmpty() ? createEveryoneExpression(session) : qr.get(0);
@SuppressWarnings("unchecked")
List<FakeInstitution> institutions = session.createQuery("FROM Institution").list();
for( FakeInstitution inst : institutions )
{
FakeAccessEntry aclEntry = new FakeAccessEntry();
aclEntry.grantRevoke = SecurityConstants.GRANT;
aclEntry.privilege = ConnectorConstants.PRIV_EXPORT_TO_LMS_ITEM;
aclEntry.targetObject = SecurityConstants.TARGET_EVERYTHING;
aclEntry.aclPriority = -SecurityConstants.PRIORITY_ALL_COLLECTIONS;
aclEntry.aclOrder = 0;
aclEntry.expression = everyone;
aclEntry.institution = inst;
String aggregateOrdering = String.format("%04d %04d %c",
(aclEntry.aclPriority + SecurityConstants.PRIORITY_MAX), aclEntry.aclOrder, aclEntry.grantRevoke);
aclEntry.aggregateOrdering = aggregateOrdering;
session.save(aclEntry);
result.incrementStatus();
}
session.flush();
session.clear();
}
项目:Equella
文件:RemoveUnusedSystemSettingsPrivilegesDatabaseMigration.java
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
throws Exception
{
session
.createQuery(
"DELETE FROM AccessEntry a WHERE a.targetObject IN ('C:attachmentFileTypes', 'C:proxy', 'C:sif')")
.executeUpdate();
}
项目:Equella
文件:IncreaseColumnForEncryptionMigration.java
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
throws Exception
{
session.createQuery("UPDATE OAuthClient SET tempClientSecret = clientSecret").executeUpdate();
session.createQuery("UPDATE LtiConsumer SET tempConsumerSecret = consumerSecret").executeUpdate();
}
项目:LibrarySystem
文件:TestBack.java
@Test
public void testSaveBack(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
BackInfo backInfo = new BackInfo();
BorrowInfo borrowInfo = new BorrowInfo();
borrowInfo.setBorrowId(1);
backInfo.setBorrowInfo(borrowInfo);
backInfo.setBorrowId(1);
session.save(backInfo);
transaction.commit();
session.close();
}
项目:Equella
文件:AddInstitutionFileWarningColumn.java
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
throws Exception
{
Query q = session.createQuery("UPDATE Institution SET quota = :value");
q.setParameter("value", 0.0);
q.executeUpdate();
}
项目:Equella
文件:CreateWorkflowTables.java
@Override
@SuppressWarnings({"unchecked", "nls"})
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
{
ClassLoader classLoader = getClass().getClassLoader();
XStream xstream = xmlService.createDefault(classLoader);
xstream.aliasPackage("com.tle.beans.entity.workflow", "com.tle.common.old.workflow");
MigrateWorkflow migrator = new MigrateWorkflow();
Map<Long, Map<String, WorkflowNode>> workflowMap = new HashMap<Long, Map<String, WorkflowNode>>();
Query allWorkflows = session.createQuery("from Workflow");
List<Workflow> workflows = allWorkflows.list();
for( Workflow workflow : workflows )
{
List<WorkflowNode> newNodes = migrator.convertNodes((WorkflowTreeNode) xstream.fromXML(workflow.root));
for( WorkflowNode newNode : newNodes )
{
newNode.setWorkflow(workflow);
session.save(newNode);
session.flush();
}
result.incrementStatus();
workflowMap.put(workflow.id, workflow.getAllTasksAsMap());
}
session.clear();
int badModStatus = 0;
Query allStatuses = session.createQuery("from WorkflowNodeStatus");
List<WorkflowNodeStatus> statuses = allStatuses.list();
for( WorkflowNodeStatus status : statuses )
{
String nodeId = status.nodeId;
Query statusQuery = session.createQuery("select s from ModerationStatus s join s.statuses st where st = ?");
statusQuery.setParameter(0, status);
ModerationStatus modStatus = (ModerationStatus) statusQuery.uniqueResult();
if( modStatus != null )
{
FakeItem item = modStatus.item;
if( item != null )
{
Map<String, WorkflowNode> map = workflowMap.get(item.itemDefinition.workflowId);
WorkflowNode linkedNode = map != null ? map.get(nodeId) : null;
if( linkedNode != null )
{
status.setNode(linkedNode);
status.setModStatus(modStatus);
if( status instanceof WorkflowItemStatus)
{
WorkflowItemStatus itemStatus = (WorkflowItemStatus) status;
itemStatus.setAcceptedUsers((Set<String>) xstream.fromXML(itemStatus.oldAccepted));
}
session.save(status);
}
else
{
modStatus.statuses.remove(status);
session.save(modStatus);
}
}
else
{
badModStatus++;
session.delete(modStatus);
}
}
result.incrementStatus();
session.flush();
}
session.clear();
int numDeleted = session.createQuery("delete from WorkflowNodeStatus where node is null").executeUpdate();
if( numDeleted > 0 )
{
LOGGER.warn("Found " + numDeleted + " orphaned WorkflowNodeStatus objects");
}
if( badModStatus > 0 )
{
LOGGER.warn("Found " + badModStatus + " orphaned ModerationStatus objects");
}
session.createQuery("update ModerationStatus set needsReset = false").executeUpdate();
}
项目:Equella
文件:ConvertOauthClientsMigration.java
@Override
protected int countDataMigrations(HibernateMigrationHelper helper, Session session)
{
return count(session
.createQuery(
"SELECT COUNT(*) FROM OauthClient oc LEFT JOIN oc.attributes attb WHERE attb.key = :flow AND attb.value = :oauthone")
.setParameter("flow", OAuthServiceImpl.KEY_OAUTH_FLOW).setParameter("oauthone", OAUTH_ONE_ID));
}
项目:Equella
文件:ConvertXsltTemplateFileToString.java
@Override
protected int countDataMigrations(HibernateMigrationHelper helper, Session session)
{
Query countQry = session
.createQuery("SELECT COUNT(*) FROM ItemDefinition WHERE slow.itemSummarySections LIKE :query");
countQry.setParameter("query", "%xsltSection%");
return count(countQry);
}
项目:Equella
文件:MigrateNotifications.java
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
{
Date convertDate = new Date();
Query query = session.createSQLQuery("SELECT i.uuid, i.version, i.institution_id,"
+ " un.element FROM item_users_notified un INNER JOIN item i ON i.id = un.item_id");
ScrollableResults results = query.scroll();
while( results.next() )
{
Object[] oldnote = results.get();
ItemId itemId = new ItemId((String) oldnote[0], ((Number) oldnote[1]).intValue());
Institution inst = new Institution();
inst.setDatabaseId(((Number) oldnote[2]).longValue());
FakeNotification notification = new FakeNotification();
notification.reason = FakeNotification.REASON_WENTLIVE;
notification.date = convertDate;
notification.itemid = itemId.toString();
notification.institution = inst;
notification.userTo = (String) oldnote[3];
session.save(notification);
session.flush();
session.clear();
}
}
项目:Equella
文件:AbstractCombinedSchemaMigration.java
@Override
protected int countDataMigrations(HibernateMigrationHelper helper, Session session)
{
List<AbstractHibernateSchemaMigration> migrations = getMigrations();
int count = 0;
for( AbstractHibernateSchemaMigration migration : migrations )
{
count += migration.countDataMigrations(helper, session);
}
return count;
}
项目:Equella
文件:AbstractCombinedSchemaMigration.java
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
throws Exception
{
for( AbstractHibernateSchemaMigration migration : getMigrations() )
{
migration.executeDataMigration(helper, result, session);
}
}
项目:Equella
文件:InitialSchema.java
@Override
protected HibernateCreationFilter getFilter(HibernateMigrationHelper helper)
{
AllDataHibernateMigrationFilter filter = new AllDataHibernateMigrationFilter();
Session session = helper.getFactory().openSession();
if( helper.tableExists(session, SystemConfig.TABLE_NAME) )
{
filter.setIncludeGenerators(false);
}
session.close();
return filter;
}
项目:Equella
文件:EntityDisabledFieldMigration.java
@Override
protected int countDataMigrations(HibernateMigrationHelper helper, Session session)
{
Query query = session
.createQuery(
"SELECT COUNT(*) FROM BaseEntity be LEFT JOIN be.attributes att WHERE att.key = :archived AND att.value = :true")
.setParameter("archived", KEY_ARCHIVED).setParameter("true", "true");
return 1 + count(query);
}
项目:Equella
文件:EntityDisabledFieldMigrationPart2.java
@Override
protected boolean migrationIsRequired(HibernateMigrationHelper helper)
{
Session session = helper.getFactory().openSession();
try
{
CheckColumnWork work = new CheckColumnWork(helper);
session.doWork(work);
return work.isColumnExists();
}
finally
{
session.close();
}
}
项目:Equella
文件:DenyGuestPortletCreationMigration.java
@SuppressWarnings("unchecked")
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
throws Exception
{
LOGGER.debug("Running com.tle.core.portal.migration.v64.DenyGuestPortletCreationMigration");
FakeAccessExpression expr = null;
final List<FakeAccessEntry> qr = session
.createQuery("FROM AccessEntry where privilege = 'CREATE_PORTLET' and targetObject = '*'").list();
LOGGER.debug("Found " + qr.size() + " potential CREATE_PORTLET privs to convert");
for( FakeAccessEntry entry : qr )
{
LOGGER.debug("Entry expression is " + entry.expression.expression);
if( entry.expression.expression.trim().equals(EVERYONE_EXPRESSION) )
{
LOGGER.debug("Entry matches Everyone expression, converting to " + LOGGED_IN_USER_ROLE_EXPRESSION);
if( expr == null )
{
expr = getExpression(session);
}
entry.expression = expr;
createAccessExpressionP(session, expr);
session.save(entry);
}
}
session.flush();
session.clear();
}
项目:LibrarySystem
文件:TestAdmin.java
@Test
public void testSaveAdmin(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Admin admin = new Admin();
admin.setName("cairou");
admin.setUsername("admin");
admin.setPwd(Md5Utils.md5("admin"));
session.save(admin);
transaction.commit();
session.close();
}
项目:LibrarySystem
文件:TestReader.java
@Test
public void testSaveReader(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Reader reader = new Reader();
// reader.setReaderId("123");
reader.setName("菜肉");
reader.setPwd("123");
//reader.setReaderType(1);
session.save(reader);
transaction.commit();
session.close();
}
项目:Equella
文件:AddExtraRemoteRepoColumns.java
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
{
Query setDenyQuery = session.createQuery("UPDATE ItemDefinition SET denyDirectContribution = :value");
setDenyQuery.setParameter("value", false);
Query setDisabledQuery = session.createQuery("UPDATE FederatedSearch SET disabled = :value");
setDisabledQuery.setParameter("value", false);
setDenyQuery.executeUpdate();
setDisabledQuery.executeUpdate();
}
项目:Equella
文件:ReIndexActivationsMigration.java
@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session)
throws Exception
{
session
.createSQLQuery(
"update item set date_for_index = ? where id in (select ar.item_id from activate_request ar)")
.setParameter(0, new Date()).executeUpdate();
}
项目:LibrarySystem
文件:TestBookType.java
@Test
public void testFindBookType(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
String hql= "from BookType";
List createQuery = session.createQuery(hql).list();
BookType bookType = (BookType) createQuery.get(0);
System.out.println(bookType);
// Set<Book> books = bookType.getBooks();
// System.out.println(books.size());
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
public boolean apply(Object obj, String name, Object value) {
if(obj instanceof Set||name.equals("books")){
return true;
}else{
return false;
}
}
});
String json = JSONArray.fromObject(createQuery,jsonConfig).toString();//List------->JSONArray
System.out.println(json);
}