下面列出了javax.persistence.criteria.Order#org.hibernate.Session 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void updateSbiUserAttributes(SbiUserAttributes attribute) {
Session aSession = null;
Transaction tx = null;
try {
aSession = getSession();
tx = aSession.beginTransaction();
aSession.saveOrUpdate(attribute);
aSession.flush();
tx.commit();
} catch (HibernateException he) {
if (tx != null)
tx.rollback();
throw new SpagoBIDAOException("Error while update user attribute " + attribute, he);
} finally {
if (aSession != null) {
if (aSession.isOpen())
aSession.close();
}
}
}
@Before
public void setUp() throws Exception {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure()
.build();
try {
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(new Event("Event 1"));
session.save(new Event("Event 2"));
session.getTransaction().commit();
session.close();
} catch (Exception e) {
fail(e);
StandardServiceRegistryBuilder.destroy(registry);
}
}
/**
* Gets the Component Id from Component Name.
*
* @param compName
* @return
*/
private static int getComponentIdFromCompName(String compName){
Session session = HibernateConfig.getSessionFactory().getCurrentSession();
Transaction txn = session.beginTransaction();
Criteria componentCriteria = session.createCriteria(ComponentEntity.class);
componentCriteria.add(Restrictions.eq("componentName",compName));
componentCriteria.add(Restrictions.eq("delInd", 0));
componentCriteria.setMaxResults(1);
ComponentEntity com =(ComponentEntity) componentCriteria.uniqueResult();
int compId = 0;
if(com != null){
compId = com.getComponentId();
}
txn.commit();
return compId;
}
@SuppressWarnings("unchecked")
public List<User> getUsers() {
final Session session = openSession();
session.getTransaction().begin();
final List<User> users = session
.createCriteria( User.class )
.add( Restrictions.gt( "id", 0 ) )
.list();
// init (#skills uses @Fetch(SUBSELECT))
users.get( 0 ).getSkills().size();
// NOTE: All skills, for all returned Users, will be initialized automatically!!!
session.getTransaction().commit();
return users;
}
@Override
public List<SbiProductType> loadAllProductType() {
logger.debug("IN");
Session aSession = null;
Transaction tx = null;
try {
aSession = getSession();
tx = aSession.beginTransaction();
String q = "from SbiProductType";
Query query = aSession.createQuery(q);
ArrayList<SbiProductType> result = (ArrayList<SbiProductType>) query.list();
return result;
} catch (HibernateException he) {
logger.error(he.getMessage(), he);
if (tx != null)
tx.rollback();
throw new SpagoBIRuntimeException("Error getting product types", he);
} finally {
logger.debug("OUT");
if (aSession != null) {
if (aSession.isOpen())
aSession.close();
}
}
}
/**
* Load by id.
*
* @param id
* the id
*
* @return the sbi paruse
*
* @throws EMFUserError
* the EMF user error
*
* @see it.eng.spagobi.behaviouralmodel.analyticaldriver.dao.IParameterUseDAO#loadById(java.lang.Integer)
*/
@Override
public SbiParuse loadById(Integer id) throws EMFUserError {
SbiParuse toReturn = null;
Session aSession = null;
Transaction tx = null;
try {
aSession = getSession();
tx = aSession.beginTransaction();
toReturn = (SbiParuse) aSession.load(SbiParuse.class, id);
tx.commit();
} catch (HibernateException he) {
logException(he);
if (tx != null)
tx.rollback();
throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
} finally {
if (aSession != null) {
if (aSession.isOpen())
aSession.close();
}
}
return toReturn;
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public List<WarningData> findWarning(WarningData wd,PageInfo pageInfo) throws IOException, MyException {
//To change body of implemented methods use File | Settings | File Templates.
List<WarningData> warningDatas = new ArrayList<WarningData>();
Session session = getSession();
StringBuilder queryString = new StringBuilder("from WarningData as wd ");
if(!StringUtils.isNullOrEmpty(wd.getWdIpAddr())){
queryString.append("where wd.wdIpAddr like '%"+wd.getWdIpAddr()+"%'");
}
Query query = session.createQuery(queryString.toString());
pageInfo.setTotalCount(query.list().size());
query.setMaxResults(pageInfo.getNumPerPage());
query.setFirstResult((pageInfo.getPageNum()-1)*pageInfo.getNumPerPage());
warningDatas = query.list();
return warningDatas;
}
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 Collection<RMNodeData> getNodesByNodeSource(final String nodeSourceName) {
logger.debug(REQUEST_BUFFER_STRING + "retrieve node with node source name " + nodeSourceName +
IN_DATABASE_STRING);
rmdbManagerBuffer.debounceNodeUpdatesIfNeeded();
try {
logger.debug("Retrieve nodes from node source " + nodeSourceName + IN_DATABASE_STRING);
return executeReadTransaction(new SessionWork<Collection<RMNodeData>>() {
@Override
@SuppressWarnings("unchecked")
public Collection<RMNodeData> doInTransaction(Session session) {
Query query = session.getNamedQuery("getRMNodeDataByNodeSource").setParameter("name",
nodeSourceName);
return (Collection<RMNodeData>) query.list();
}
});
} catch (RuntimeException e) {
throw new RuntimeException("Exception occurred while getting node by node source name " + nodeSourceName,
e);
}
}
@Test
public void givenTransientEntity_whenSave_thenManaged() throws Exception {
SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
try (Session session = sessionFactory.openSession()) {
Transaction transaction = startTransaction(session);
FootballPlayer neymar = new FootballPlayer();
neymar.setName("Neymar");
session.save(neymar);
assertThat(getManagedEntities(session)).size().isEqualTo(1);
assertThat(neymar.getId()).isNotNull();
int count = queryCount("select count(*) from Football_Player where name='Neymar'");
assertThat(count).isEqualTo(0);
transaction.commit();
count = queryCount("select count(*) from Football_Player where name='Neymar'");
assertThat(count).isEqualTo(1);
transaction = startTransaction(session);
session.delete(neymar);
transaction.commit();
}
}
public void destroy()
{
logger.debug("Destroying HibernateServletFilter");
final Session session = HibernateUtil.getSessionFactory().getCurrentSession();
if (session.getTransaction().isActive())
{
logger.debug("Committing the final active transaction");
session.getTransaction().commit();
}
if (session.isOpen())
{
logger.debug("Closing the final open session");
session.close();
}
}
@Override
public String getNextVersionNumber(Session session, NodeDocument nDoc, NodeDocumentVersion nDocVer, int increment) {
String versionNumber = nDocVer.getName();
int nextVerNumber = Integer.parseInt(versionNumber);
Query q = session.createQuery(qs);
NodeDocumentVersion ndv = null;
do {
nextVerNumber++;
q.setString("parent", nDoc.getUuid());
q.setString("name", String.valueOf(nextVerNumber));
ndv = (NodeDocumentVersion) q.setMaxResults(1).uniqueResult();
} while (ndv != null);
return String.format(Config.VERSION_NUMERATION_FORMAT, nextVerNumber);
}
private List<SbiI18NMessages> getSbiI18NMessagesByLabel(SbiI18NMessages message, String tenant, Session curSession) {
logger.debug("IN");
List<SbiI18NMessages> toReturn = new ArrayList<SbiI18NMessages>();
try {
String hql = "from SbiI18NMessages m where m.label = :label and m.commonInfo.organization = :organization and m.languageCd != :languageCd";
Query query = curSession.createQuery(hql);
query.setString("label", message.getLabel());
query.setString("organization", tenant);
query.setInteger("languageCd", message.getLanguageCd());
toReturn = query.list();
} catch (HibernateException e) {
logException(e);
throw new RuntimeException();
}
logger.debug("OUT");
return toReturn;
}
/**
*
* @param hql传入的hql语句
* @param pageCode当前页
* @param pageSize每页显示大小
* @return
*/
public List doSplitPage(final String hql,final int pageCode,final int pageSize){
//调用模板的execute方法,参数是实现了HibernateCallback接口的匿名类,
return (List) this.getHibernateTemplate().execute(new HibernateCallback(){
//重写其doInHibernate方法返回一个object对象,
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
//创建query对象
Query query=session.createQuery(hql);
//返回其执行了分布方法的list
return query.setFirstResult((pageCode-1)*pageSize).setMaxResults(pageSize).list();
}
});
}
/**
* Update
*/
public static void updateRule(MailFilterRule fr) throws DatabaseException {
log.debug("updateRule({})", fr);
Session session = null;
Transaction tx = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
session.update(fr);
HibernateUtil.commit(tx);
} catch (HibernateException e) {
HibernateUtil.rollback(tx);
throw new DatabaseException(e.getMessage(), e);
} finally {
HibernateUtil.close(session);
}
log.debug("updateRule: void");
}
public static void optimize ()
{
HibernateDaoLocalSupport support = ApplicationContextProvider.getBean (
HibernateDaoLocalSupport.class);
support.getHibernateTemplate ().flush ();
support.getHibernateTemplate ().executeWithNativeSession (
new HibernateCallback<Void> ()
{
@Override
public Void doInHibernate (Session session) throws
HibernateException, SQLException
{
SQLQuery query = session.createSQLQuery ("CHECKPOINT DEFRAG");
query.executeUpdate ();
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;
}
});
}
private void migrateV1toV2() throws SQLException {
SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class);
Connection connection = session.getJdbcConnectionAccess().obtainConnection();
String programmingSubmissionTable = "sandalphon_submission_programming";
String newProgrammingSubmissionTable = "sandalphon_programming_submission";
String bundleSubmissionTable = "sandalphon_submission_bundle";
String newBundleSubmissionTable = "sandalphon_bundle_submission";
Statement statement = connection.createStatement();
statement.execute("ALTER TABLE " + programmingSubmissionTable + " CHANGE contestJid containerJid VARCHAR(255);");
statement.execute("ALTER TABLE " + bundleSubmissionTable + " CHANGE contestJid containerJid VARCHAR(255);");
statement.execute("DROP TABLE " + newProgrammingSubmissionTable + ";");
statement.execute("DROP TABLE " + newBundleSubmissionTable + ";");
statement.execute("RENAME TABLE " + programmingSubmissionTable + " TO " + newProgrammingSubmissionTable + ";");
statement.execute("RENAME TABLE " + bundleSubmissionTable + " TO " + newBundleSubmissionTable + ";");
}
/**
* Get value of failed login attemtpts counter from DB.
*
* @author Marco Libanori
*/
@Override
public int getFailedLoginAttempts(String userId) {
logger.debug("IN");
Session aSession = null;
Transaction tx = null;
try {
Integer result = 0;
if (isUserIdAlreadyInUse(userId) != null) {
aSession = getSession();
tx = aSession.beginTransaction();
ProjectionList projList = Projections.projectionList().add(Projections.property("failedLoginAttempts"), "failedLoginAttempts");
SimpleExpression eq = Restrictions.eq("userId", userId);
result = (Integer) aSession.createCriteria(SbiUser.class).add(eq).setProjection(projList).uniqueResult();
tx.commit();
}
return result;
} catch (HibernateException he) {
if (tx != null)
tx.rollback();
throw new SpagoBIDAOException("Error while reading failed login attempts counter for user " + userId, he);
} finally {
logger.debug("OUT");
if (aSession != null) {
if (aSession.isOpen())
aSession.close();
}
}
}
/**
* @return The set of article ids that are categorized under this category.
*/
public Set<Integer> getArticleIds() {
Session session = this.wiki.__getHibernateSession();
session.beginTransaction();
session.lock(hibernateCategory, LockMode.NONE);
Set<Integer> tmpSet = new HashSet<Integer>(hibernateCategory.getPages());
session.getTransaction().commit();
return tmpSet;
}
public List findBySpaceOnly(final String pageSpace, final String pageName)
{
long start = System.currentTimeMillis();
try
{
// there is no point in sorting by version, since there is only one
// version in
// this table.
// also using like is much slower than eq
HibernateCallback callback = new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException
{
return session.createCriteria(PagePresence.class).add(
Expression.eq("pagespace", pageSpace))
.add(
Expression.not(Expression.eq("pagename",
pageName))).addOrder(
Order.desc("lastseen")).list();
}
};
List l = (List) getHibernateTemplate().execute(callback);
log.info("Found " + l.size() + " in " + pageSpace + " : "
+ pageName);
return l;
}
finally
{
long finish = System.currentTimeMillis();
TimeLogger.printTimer("PagePresenceDaoImpl.findBySpaceOnly: "
+ pageSpace + " :" + pageName, start, finish);
}
}
@Test
public void testJDBCQuery() {
doInJPA(new JPATransactionFunction<Void>() {
@Override
public Void apply(EntityManager entityManager) {
Session session = entityManager.unwrap(Session.class);
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(
"SELECT * " +
"FROM Event e " +
"WHERE " +
" e.ip && ?::inet = true"
);
ps.setObject(1, "192.168.0.1/24");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
Long id = rs.getLong(1);
String ip = rs.getString(2);
assertEquals("192.168.0.123/24", ip);
}
} finally {
if (ps != null) {
ps.close();
}
}
}
});
return null;
}
});
}
private TrackerTypeReport handleRelationships( Session session, TrackerBundle bundle )
{
List<Relationship> relationships = bundle.getRelationships();
TrackerTypeReport typeReport = new TrackerTypeReport( TrackerType.RELATIONSHIP );
relationships.forEach( o -> bundleHooks.forEach( hook -> hook.preCreate( Relationship.class, o, bundle ) ) );
for ( int idx = 0; idx < relationships.size(); idx++ )
{
Relationship relationship = relationships.get( idx );
org.hisp.dhis.relationship.Relationship toRelationship = relationshipTrackerConverterService
.from( bundle.getPreheat(), relationship );
TrackerObjectReport objectReport = new TrackerObjectReport( TrackerType.EVENT, toRelationship.getUid(),
idx );
typeReport.addObjectReport( objectReport );
Date now = new Date();
if ( bundle.getImportStrategy().isCreate() )
{
toRelationship.setCreated( now );
}
toRelationship.setLastUpdated( now );
toRelationship.setLastUpdatedBy( bundle.getUser() );
session.persist( toRelationship );
typeReport.getStats().incCreated();
if ( FlushMode.OBJECT == bundle.getFlushMode() )
{
session.flush();
}
}
relationships.forEach( o -> bundleHooks.forEach( hook -> hook.postCreate( Relationship.class, o, bundle ) ) );
return typeReport;
}
@Override
public List<?> findByNamedQueryAndValueBean(final String queryName, final Object valueBean)
throws DataAccessException {
return executeWithNativeSession(new HibernateCallback<List<?>>() {
@Override
public List<?> doInHibernate(Session session) throws HibernateException {
Query queryObject = session.getNamedQuery(queryName);
prepareQuery(queryObject);
queryObject.setProperties(valueBean);
return queryObject.list();
}
});
}
@Override
public List<SbiTimespan> listDynTimespan() {
return list(new ICriterion<SbiTimespan>() {
@Override
public Criteria evaluate(Session session) {
Criteria c = session.createCriteria(SbiTimespan.class);
c.add(Restrictions.eq("staticFilter", false));
return c;
}
});
}
public Message recordGrade(int tid, int cid, int sid, double grade){
Session session = getSession();
if(session.createQuery("FROM TeacherCourse WHERE tid = (:tid) and cid = (:cid)")
.setParameter("tid",tid)
.setParameter("cid",cid).list().size()==0)
return new Message(-1,"您非此课程的授课教师,无法录入成绩");
Transaction tx = session.beginTransaction();
int row = session.createQuery("UPDATE CourseStudent SET grade = (:grade) WHERE cid = (:cid) and sid = (:sid)")
.setParameter("grade",grade)
.setParameter("cid",cid)
.setParameter("sid",sid)
.executeUpdate();
tx.commit();
return row>0?new Message(1,"ok"):new Message(-2,"录入成绩失败");
}
@Override
protected void afterInit() {
doInJPA(new JPATransactionFunction<Void>() {
@Override
public Void apply(EntityManager entityManager) {
entityManager.unwrap(Session.class).doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
Statement statement = null;
try {
statement = connection.createStatement();
statement.executeUpdate(
"ALTER TABLE event MOVE LOB (location) STORE AS (CACHE)"
);
statement.executeUpdate(
"ALTER TABLE participant MOVE LOB (ticket, metadata) STORE AS (CACHE)"
);
} finally {
if(statement != null) {
statement.close();
}
}
}
});
return null;
}
});
}
@SuppressWarnings("unchecked")
public List<Site> listSitesByTitle(final String aTitle) {
Object o = getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(final Session session) {
Query query = session.createQuery("from Site s where lower(s.title) = :siteTitle");
query.setString("siteTitle", aTitle);
return query.list();
}
});
return (List<Site>) o;
}
/**
* Lookup a crypto key by its id.
* @param keyId to lookup
* @param org who owns the key
* @return CryptoKey if found. Null if not
*/
public static CryptoKey lookupCryptoKeyById(Long keyId, Org org) {
Session session = null;
CryptoKey retval = null;
//look for Kickstart data by id
session = HibernateFactory.getSession();
retval = (CryptoKey) session.getNamedQuery("CryptoKey.findByIdAndOrg")
.setLong("key_id", keyId.longValue())
.setLong("org_id", org.getId().longValue())
.uniqueResult();
return retval;
}
@Override
public boolean deleteProgressThread(Integer progressThreadId) throws EMFUserError {
// logger.debug("IN");
boolean found = false;
Session aSession = null;
Transaction tx = null;
try {
aSession = getSession();
tx = aSession.beginTransaction();
Query hibPT = aSession.createQuery("from SbiProgressThread h where h.progressThreadId = ? ");
hibPT.setInteger(0, progressThreadId);
Object sbiProgressThreadO = hibPT.uniqueResult();
if (sbiProgressThreadO != null) {
SbiProgressThread pT = (SbiProgressThread) sbiProgressThreadO;
found = true;
aSession.delete(pT);
tx.commit();
}
} catch (HibernateException he) {
logger.error("Error while deletering Progress Thread with progressThreadId = " + progressThreadId, he);
if (tx != null)
tx.rollback();
throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
} finally {
if (aSession != null) {
if (aSession.isOpen())
aSession.close();
// logger.debug("OUT");
}
}
// logger.debug("OUT");
return found;
}