下面列出了org.hibernate.Session#save ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void add(){
Group p = new Group("group1");
// p.setGroupName("group1");
User u1 = new User();
User u2 = new User();
u1.setUserId("user1");
u1.setUserName("name1");
u1.setUserPassword("121");
u2.setUserId("user2");
u2.setUserName("name2");
u2.setUserPassword("122");
List<User> memberList = new ArrayList<User>();
memberList.add(u1);
memberList.add(u2);
p.setMemberList(memberList);
Session session = HibernateSessionFactory.getSession();
Transaction trans = session.beginTransaction();
session.save(u1);
session.save(u2);
session.save(p);
trans.commit();
session.close();
}
/**
* Create
*/
public static long create(Forum frm) throws DatabaseException {
log.debug("create({})", frm);
Session session = null;
Transaction tx = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
Long id = (Long) session.save(frm);
HibernateUtil.commit(tx);
log.debug("create: {}" + id);
return id;
} catch (HibernateException e) {
HibernateUtil.rollback(tx);
throw new DatabaseException(e.getMessage(), e);
} finally {
HibernateUtil.close(session);
}
}
private void writeTenantProductTypes(String tenantName, Session hibernateSession) throws Exception {
// create association tenant to product type
SbiTenant aTenant = findTenant(hibernateSession, tenantName);
for (SbiProductType aProductType : getProductTypes(hibernateSession)) {
if (aProductType != null) {
SbiOrganizationProductType association = new SbiOrganizationProductType();
association.setSbiProductType(aProductType);
association.setSbiOrganizations(aTenant);
SbiCommonInfo commonInfo = new SbiCommonInfo();
commonInfo.setUserIn("server");
commonInfo.setTimeIn(new Date());
commonInfo.setOrganization(tenantName);
association.setCommonInfo(commonInfo);
SbiOrganizationProductTypeId id = new SbiOrganizationProductTypeId();
id.setProductTypeId(aProductType.getProductTypeId());
id.setOrganizationId(aTenant.getId());
association.setId(id);
hibernateSession.save(association);
}
}
}
public static void main(String[] args) {
HibernateSimple hs = new HibernateSimple();
Session s = hs.getSessionFactory().getCurrentSession();
s.beginTransaction();
// read
Iterator<Region> regionIt = s.createQuery("from Region").iterate();
while (regionIt.hasNext()) {
Region r = regionIt.next();
System.out.println("Region iterator:" + r);
}
//insert
Region pskov = new Region("Pskov");
pskov.setRegionLeader("Turchak");
s.save(pskov);
s.getTransaction().commit();
}
@Test
public void hibernate_with_ignored_statement() {
SessionFactory sessionFactory = createSessionFactory(false,
Collections.singletonList("insert into Employee (id) values (?)"));
Session session = sessionFactory.openSession();
Employee employee = new Employee();
session.beginTransaction();
session.save(employee);
session.getTransaction().commit();
session.close();
sessionFactory.close();
assertNotNull(employee.id);
List<MockSpan> finishedSpans = mockTracer.finishedSpans();
assertEquals(8, finishedSpans.size());
checkSpans(finishedSpans, "hibernate");
assertNull(mockTracer.activeSpan());
}
private int saveChenFbkMaps(SurveyAnswer surveyAnswer,
Map<String, Object> chenFbkMaps, Session session) {
String surveyId=surveyAnswer.getSurveyId();
String surveyAnswerId=surveyAnswer.getId();
int answerQuCount=0;
if(chenFbkMaps!=null){
for (String key : chenFbkMaps.keySet()) {
String quId=key;
Map<String,Object> mapRows=(Map<String, Object>) chenFbkMaps.get(key);
for (String keyRow : mapRows.keySet()) {
String rowId=keyRow;
Map<String, Object> mapRow=(Map<String, Object>) mapRows.get(keyRow);
for (String keyCol : mapRow.keySet()) {
answerQuCount++;
String colId=keyCol;
String answerValue=mapRow.get(keyCol).toString();
AnChenFbk anChenFbk=new AnChenFbk(surveyId,surveyAnswerId,quId,rowId,colId,answerValue);
session.save(anChenFbk);
}
}
}
}
return answerQuCount;
}
/**
* Create
*/
public static long create(Report rp) throws DatabaseException {
log.debug("create({})", rp);
Session session = null;
Transaction tx = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
Long id = (Long) session.save(rp);
HibernateUtil.commit(tx);
log.debug("create: {}", id);
return id;
} catch (HibernateException e) {
HibernateUtil.rollback(tx);
throw new DatabaseException(e.getMessage(), e);
} finally {
HibernateUtil.close(session);
}
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
EmployeeDetail employeeDetail = new EmployeeDetail("10th Street", "LA",
"San Francisco", "U.S.");
Employee employee = new Employee("Nina", "Mayers", new Date(121212),
"114-857-965");
employee.setEmployeeDetail(employeeDetail);
employeeDetail.setEmployee(employee);
session.save(employee);
List<Employee> employees = session.createQuery("from Employee").list();
for (Employee employee1 : employees) {
System.out.println(employee1.getFirstname() + " , "
+ employee1.getLastname() + ", "
+ employee1.getEmployeeDetail().getState());
}
session.getTransaction().commit();
session.close();
}
private void addMissingProductTypes(Session aSession, List dbProductTypes, List xmlProductTypes) {
logger.debug("IN");
Iterator it2 = xmlProductTypes.iterator();
while (it2.hasNext()) {
boolean existsInDb = false;
SourceBean aProductTypeSB = (SourceBean) it2.next();
String labelXml = (String) aProductTypeSB.getAttribute("label");
logger.debug("Retrieved label of XML Product Type: " + labelXml);
String isActive = (String) aProductTypeSB.getAttribute("active");
if (isActive != null && isActive.equalsIgnoreCase("true")) {
Iterator it = dbProductTypes.iterator();
while (it.hasNext()) {
SbiProductType d = (SbiProductType) it.next();
String label = d.getLabel();
logger.debug("Retrieved label of DB Product Type: " + label);
if (labelXml.equalsIgnoreCase(label)) {
existsInDb = true;
logger.debug("Product Type already exists in the DB");
break;
}
}
if (!existsInDb) {
logger.debug("Product Type doesn't exist in the DB");
SbiProductType aProductType = new SbiProductType();
aProductType.setLabel((String) aProductTypeSB.getAttribute("label"));
logger.debug("New Product Type ready to be inserted in the DB");
logger.debug("Inserting Product Type with label = [" + aProductTypeSB.getAttribute("label") + "] ...");
aSession.save(aProductType);
logger.debug("New Product Type inserted in the DB");
writeEngineAssociations(aSession, aProductTypeSB);
}
}
}
logger.debug("OUT");
}
public boolean onSave(Session session) throws CallbackException {
created=true;
try {
foo = new Foo();
session.save(foo);
}
catch (Exception e) {
throw new CallbackException(e);
}
foo.setString("child of a qux");
return NO_VETO;
}
/**
* Insert viewpoint.
*
* @param viewpoint
* the viewpoint
*
* @throws EMFUserError
* the EMF user error
*
* @see it.eng.spagobi.analiticalmodel.document.dao.IMetaModelViewpointDAO#insertViewpoint(it.eng.spagobi.analiticalmodel.document.bo.Viewpoint)
*/
@Override
public void insertMetaModelViewpoint(Viewpoint viewpoint) throws EMFUserError {
Session aSession = null;
Transaction tx = null;
try {
aSession = getSession();
tx = aSession.beginTransaction();
SbiMetaModelViewpoints hibViewpoint = new SbiMetaModelViewpoints();
// hibViewpoint.setVpId(vpId);
SbiMetaModel aSbiMetaModel = (SbiMetaModel) aSession.load(SbiMetaModel.class, viewpoint.getBiobjId());
hibViewpoint.setSbiMetaModel(aSbiMetaModel);
hibViewpoint.setVpDesc(viewpoint.getVpDesc());
hibViewpoint.setVpOwner(viewpoint.getVpOwner());
hibViewpoint.setVpName(viewpoint.getVpName());
hibViewpoint.setVpScope(viewpoint.getVpScope());
hibViewpoint.setVpValueParams(viewpoint.getVpValueParams());
hibViewpoint.setVpCreationDate(viewpoint.getVpCreationDate());
updateSbiCommonInfo4Insert(hibViewpoint);
aSession.save(hibViewpoint);
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();
}
}
}
/**
* Create
*/
public static long create(QueryParams qp) throws DatabaseException {
log.debug("create({})", qp);
Session session = null;
Transaction tx = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
Long id = (Long) session.save(qp);
QueryParams qpTmp = (QueryParams) session.load(QueryParams.class, id);
for (String keyword : qp.getKeywords()) {
qpTmp.getKeywords().add(keyword);
}
for (String category : qp.getCategories()) {
qpTmp.getCategories().add(category);
}
for (Iterator<Entry<String, String>> it = qp.getProperties().entrySet().iterator(); it.hasNext(); ) {
Entry<String, String> entry = it.next();
qpTmp.getProperties().put(entry.getKey(), entry.getValue());
}
HibernateUtil.commit(tx);
log.debug("create: {}", id);
return id;
} catch (HibernateException e) {
HibernateUtil.rollback(tx);
throw new DatabaseException(e.getMessage(), e);
} finally {
HibernateUtil.close(session);
}
}
/**
* Insert data to tps_latency_history table
*
* @return
*/
public static void loadTpsLatencyHistory(final int envId, int conponentId , float tpsVaule, float latencyValue) {
final java.sql.Date todayDate = new java.sql.Date(Calendar.getInstance().getTimeInMillis());;
Session session = HibernateConfig.getSessionFactory().getCurrentSession();
Transaction txn = session.beginTransaction();
TpsLatHistoryEntity tpsLabHis = new TpsLatHistoryEntity();
setTPSLatencyHistory(envId, conponentId, tpsVaule, latencyValue, todayDate, tpsLabHis);
session.save(tpsLabHis);
txn.commit();
}
public K8sTpsLatencyHistoryEntity createK8sTpsLatencyHistoryEntity(Session session, String envName) {
K8sTpsLatencyHistoryEntity historyEntity = new K8sTpsLatencyHistoryEntity();
session = sessionFactory.openSession();
Transaction trx = session.beginTransaction();
createEnvironment(envName, 0);
EnvironmentEntity envEntity = envDao.getEnvironmentFromName(envName);
createComponentType();
createComponent();
ComponentEntity parentComponentEntity = session.get(ComponentEntity.class, compID);
createComponent();
ComponentEntity componentEntity = session.get(ComponentEntity.class, compID);
componentEntity.setParentComponent(parentComponentEntity);
parentCompID++;
session.save(componentEntity);
historyEntity.setComponent(componentEntity);
historyEntity.setEnvironment(envEntity);
historyEntity.setLatencyValue(0.0);
historyEntity.setTpsValue(0.0);
long date = System.currentTimeMillis();
historyEntity.setStatusDate(new java.sql.Date(date));
tpsLatencyID++;
trx.commit();
session.close();
return historyEntity;
}
public User uploadimg(File file, Long userId) throws IOException {
Session session = getSession();
User loginUser = get(User.class,userId);
loginUser.setHeaderpic(Hibernate.getLobCreator(session).createBlob(IOUtils.readFileToArray(file)));
//图像文件的后缀名
loginUser.setPicExtName(file.getName().substring(file.getName().lastIndexOf(".")));
session.save(loginUser);
return loginUser;
}
private SbiKpiThreshold from(Session session, SbiKpiThreshold sbiKpiThreshold, Threshold t) {
boolean saveAsNew = false;
if (sbiKpiThreshold == null) {
sbiKpiThreshold = new SbiKpiThreshold();
saveAsNew = true;
}
sbiKpiThreshold.setName(t.getName());
sbiKpiThreshold.setDescription(t.getDescription());
if (t.getTypeId() != null) {
SbiDomains type = (SbiDomains) session.load(SbiDomains.class, t.getTypeId());
sbiKpiThreshold.setType(type);
}
// clearing removed references
Iterator<SbiKpiThresholdValue> iterator = sbiKpiThreshold.getSbiKpiThresholdValues().iterator();
while (iterator.hasNext()) {
SbiKpiThresholdValue sbiKpiThresholdValue = iterator.next();
// List of threshold values cannot be null
if (t.getThresholdValues().indexOf(new ThresholdValue(sbiKpiThresholdValue.getId())) == -1) {
iterator.remove();
}
}
session.save(sbiKpiThreshold);
for (ThresholdValue tv : t.getThresholdValues()) {
SbiKpiThresholdValue sbiThresholdValue = null;
if (tv.getId() == null || saveAsNew) {
sbiThresholdValue = from(null, tv);
updateSbiCommonInfo4Insert(sbiThresholdValue);
sbiThresholdValue.setSbiKpiThreshold(sbiKpiThreshold);
sbiKpiThreshold.getSbiKpiThresholdValues().add(sbiThresholdValue);
} else {
sbiThresholdValue = (SbiKpiThresholdValue) session.load(SbiKpiThresholdValue.class, tv.getId());
from(sbiThresholdValue, tv);
updateSbiCommonInfo4Update(sbiThresholdValue);
}
sbiThresholdValue.setSbiKpiThreshold(sbiKpiThreshold);
session.save(sbiThresholdValue);
sbiKpiThreshold.getSbiKpiThresholdValues().add(sbiThresholdValue);
}
return sbiKpiThreshold;
}
/**
* Insert object's metadata content.
*
* @param aObjMetacontent
* the metadata content
*
* @throws EMFUserError
* the EMF user error
*
* @see it.eng.spagobi.tools.objmetadata.dao.IObjMetadataDAO#insertObjMetacontent(it.eng.spagobi.tools.objmetadata.bo.ObjMetacontent)
*/
@Override
public void insertObjMetacontent(ObjMetacontent aObjMetacontent) throws EMFUserError {
logger.debug("IN");
Session aSession = null;
Transaction tx = null;
Criterion aCriterion = null;
Criteria criteria = null;
try {
aSession = getSession();
tx = aSession.beginTransaction();
SbiObjMetacontents hibContents = new SbiObjMetacontents();
// get biobject reference
aCriterion = Expression.eq("biobjId", aObjMetacontent.getBiobjId());
criteria = aSession.createCriteria(SbiObjects.class);
criteria.add(aCriterion);
SbiObjects biobj = (SbiObjects) criteria.uniqueResult();
hibContents.setSbiObjects(biobj);
// get subobject reference
if (aObjMetacontent.getSubobjId() == null) {
hibContents.setSbiSubObjects(null);
} else {
aCriterion = Expression.eq("subObjId", aObjMetacontent.getSubobjId());
criteria = aSession.createCriteria(SbiSubObjects.class);
criteria.add(aCriterion);
SbiSubObjects subobj = (SbiSubObjects) criteria.uniqueResult();
hibContents.setSbiSubObjects(subobj);
}
SbiBinContents binaryContent = new SbiBinContents();
binaryContent.setContent(aObjMetacontent.getContent());
updateSbiCommonInfo4Insert(binaryContent);
aSession.save(binaryContent);
hibContents.setSbiBinContents(binaryContent);
hibContents.setObjmetaId(aObjMetacontent.getObjmetaId());
hibContents.setCreationDate(aObjMetacontent.getCreationDate());
hibContents.setLastChangeDate(aObjMetacontent.getLastChangeDate());
hibContents.setAdditionalInfo(aObjMetacontent.getAdditionalInfo());
updateSbiCommonInfo4Insert(hibContents);
aSession.save(hibContents);
tx.commit();
} catch (HibernateException he) {
logger.error(
"Error while inserting the metadata content with id "
+ ((aObjMetacontent == null) ? "" : String.valueOf(aObjMetacontent.getObjMetacontentId())), he);
if (tx != null)
tx.rollback();
throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
} finally {
if (aSession != null) {
if (aSession.isOpen())
aSession.close();
logger.debug("OUT");
}
}
}
public static void main(String[] args) {
System.out.println("Testing Hibernate Utility Class");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Category cat = new Category();
cat.setName("name");
session.save(cat);
cat = new Category();
cat.setName("namedd");
session.save(cat);
List all = session.createCriteria(Category.class).list();
System.out.println(all);
//session.delete(cat);
session.getTransaction().commit();
}
/**
* Test the equivalent of EJB3 LockModeType.WRITE
* <p/>
* From the spec:
* <p/>
* If transaction T1 calls lock(entity, LockModeType.WRITE) on a versioned object, the entity
* manager must avoid the phenomena P1 and P2 (as with LockModeType.READ) and must also force
* an update (increment) to the entity's version column. A forced version update may be performed immediately,
* or may be deferred until a flush or commit. If an entity is removed before a deferred version
* update was to have been applied, the forced version update is omitted, since the underlying database
* row no longer exists.
* <p/>
* The persistence implementation is not required to support calling lock(entity, LockMode-Type.WRITE)
* on a non-versioned object. When it cannot support a such lock call, it must throw the
* PersistenceException. When supported, whether for versioned or non-versioned objects, LockMode-Type.WRITE
* must always prevent the phenomena P1 and P2. For non-versioned objects, whether or
* not LockModeType.WRITE has any additional behaviour is vendor-specific. Applications that call
* lock(entity, LockModeType.WRITE) on non-versioned objects will not be portable.
* <p/>
* Due to the requirement that LockModeType.WRITE needs to force a version increment,
* a new Hibernate LockMode was added to support this behavior: {@link org.hibernate.LockMode#FORCE}.
*/
public void testLockModeTypeWrite() {
if ( ! readCommittedIsolationMaintained( "ejb3 lock tests" ) ) {
return;
}
if ( getDialect().doesReadCommittedCauseWritersToBlockReaders() ) {
reportSkip( "write locks block readers", "jpa read locking" );
return;
}
final String initialName = "lock test";
// set up some test data
Session s1 = getSessions().openSession();
Transaction t1 = s1.beginTransaction();
Item item = new Item();
item.setName( initialName );
s1.save( item );
MyEntity myEntity = new MyEntity();
myEntity.setName( "Test" );
s1.save( myEntity );
t1.commit();
s1.close();
Long itemId = item.getId();
long initialVersion = item.getVersion();
s1 = getSessions().openSession();
t1 = s1.beginTransaction();
item = ( Item ) s1.get( Item.class, itemId );
s1.lock( item, LockMode.FORCE );
assertEquals( "no forced version increment", initialVersion + 1, item.getVersion() );
myEntity = (MyEntity) s1.get( MyEntity.class, myEntity.getId() );
s1.lock( myEntity, LockMode.FORCE );
assertTrue( "LockMode.FORCE on a unversioned entity should degrade nicely to UPGRADE", true );
s1.lock( item, LockMode.FORCE );
assertEquals( "subsequent LockMode.FORCE did not no-op", initialVersion + 1, item.getVersion() );
Session s2 = getSessions().openSession();
Transaction t2 = s2.beginTransaction();
Item item2 = ( Item ) s2.get( Item.class, itemId );
assertEquals( "isolation not maintained", initialName, item2.getName() );
item.setName( "updated-1" );
s1.flush();
// currently an unfortunate side effect...
assertEquals( initialVersion + 2, item.getVersion() );
t1.commit();
s1.close();
item2.setName( "updated" );
try {
t2.commit();
fail( "optimisitc lock should have failed" );
}
catch( Throwable ignore ) {
// expected behavior
t2.rollback();
}
finally {
s2.close();
}
s1 = getSessions().openSession();
t1 = s1.beginTransaction();
s1.delete( item );
s1.delete( myEntity );
t1.commit();
s1.close();
}
@Override
public Integer insertCommunityFunctionality(LowFunctionality aLowFunctionality) throws EMFUserError {
logger.debug("IN");
Session aSession = null;
Transaction tx = null;
Integer result = null;
try {
aSession = getSession();
tx = aSession.beginTransaction();
SbiFunctions hibFunct = new SbiFunctions();
// recover sbidomain of the user functionality
Criterion vcdEQusfunct = Expression.eq("valueCd", "COMMUNITY_FUNCT");
Criteria criteria = aSession.createCriteria(SbiDomains.class);
criteria.add(vcdEQusfunct);
SbiDomains functTypeDomain = (SbiDomains) criteria.uniqueResult();
hibFunct.setFunctType(functTypeDomain);
hibFunct.setCode(aLowFunctionality.getCode());
hibFunct.setFunctTypeCd(functTypeDomain.getValueCd());
hibFunct.setDescr(aLowFunctionality.getDescription());
hibFunct.setName(aLowFunctionality.getName());
hibFunct.setPath(aLowFunctionality.getPath());
Integer parentId = aLowFunctionality.getParentId();
SbiFunctions hibParentFunct = null;
if (parentId != null) {
// if it is not the root controls if the parent functionality
// exists
Criteria parentCriteria = aSession.createCriteria(SbiFunctions.class);
Criterion parentCriterion = Expression.eq("functId", parentId);
parentCriteria.add(parentCriterion);
hibParentFunct = (SbiFunctions) parentCriteria.uniqueResult();
if (hibParentFunct == null) {
logger.error("The parent Functionality with id = " + parentId + " does not exist.");
throw new EMFUserError(EMFErrorSeverity.ERROR, 1038);
}
}
// if it is the root the parent functionality is null
hibFunct.setParentFunct(hibParentFunct);
// manages prog column that determines the folders order
if (hibParentFunct == null)
hibFunct.setProg(new Integer(1));
else {
// loads sub functionalities
Query hibQuery = aSession.createQuery("select max(s.prog) from SbiFunctions s where s.parentFunct.functId = ? and s.functTypeCd = ?");
hibQuery.setInteger(0, parentId.intValue());
hibQuery.setString(1, "COMMUNITY_FUNCT");
Integer maxProg = (Integer) hibQuery.uniqueResult();
if (maxProg != null)
hibFunct.setProg(new Integer(maxProg.intValue() + 1));
else
hibFunct.setProg(new Integer(1));
}
updateSbiCommonInfo4Insert(hibFunct, true);
result = (Integer) aSession.save(hibFunct);
tx.commit();
} catch (HibernateException he) {
logger.error("HibernateException", he);
if (tx != null)
tx.rollback();
throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
} finally {
if (aSession != null) {
if (aSession.isOpen()) {
aSession.close();
logger.debug("The [insertCommunityFunctionality] occurs. LowFunctionality cache will be cleaned.");
this.clearCache();
}
logger.debug("OUT");
}
}
return result;
}