Java Code Examples for org.hibernate.Session.save()

The following are Jave code examples for showing how to use save() of the org.hibernate.Session class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: hibernateMaster   File: DaoUtil.java   Source Code and License Vote up 6 votes
public final static boolean saveList(List<? extends BaseRelationalDatabaseDomain> list){
	Session session = null;
	try {
		session = getSession();
		beginTransaction();
		for (Object obj:list) {
			session.save(obj);
		}
		return managTransaction(true);
	} catch (Exception e) {
		setException(e);
		return managTransaction(false);
	}finally{
		closeSession();
	}
}
 
Example 2
Project: DWSurvey   File: SurveyAnswerDaoImpl.java   Source Code and License Vote up 6 votes
/**
 * 矩陈评分题
 * @param surveyAnswer
 * @param chenScoreMaps
 * @param session
 * @return
 */
private int saveChenScoreMaps(SurveyAnswer surveyAnswer,
		Map<String, Object> chenScoreMaps, Session session) {
	
	String surveyId=surveyAnswer.getSurveyId();
	String surveyAnswerId=surveyAnswer.getId();
	int answerQuCount=0;
	if(chenScoreMaps!=null){
		for (String key : chenScoreMaps.keySet()) {
			String quId=key;
			Map<String,Object> mapRows=(Map<String, Object>) chenScoreMaps.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();
					AnChenScore anChenScore=new AnChenScore(surveyId,surveyAnswerId,quId,rowId,colId,answerValue);
					session.save(anChenScore);
				}
			}
		}
	}
	return answerQuCount;
}
 
Example 3
Project: bdf2   File: DesignerServiceController.java   Source Code and License Vote up 6 votes
private void saveProcessDef(NewDeployment deployment,String xmlData) throws Exception{
	DeploymentImpl deploy=(DeploymentImpl)deployment;
	ProcessDefinition pd=(ProcessDefinition)deploy.getObjects().values().iterator().next();
	String deploymentId=pd.getDeploymentId();
	String name=pd.getName();
	int version=pd.getVersion();
	DesignerProcess process=new DesignerProcess();
	process.setDeploymentId(deploymentId);
	process.setName(name);
	process.setCreateDate(new Date());
	Session session=hibernateDao.getSessionFactory().openSession();
	try{
		process.setVersion(version);
		String lobId=lobStoreService.storeString(xmlData);
		process.setLobId(lobId);
		process.setId(UUID.randomUUID().toString());
		session.save(process);
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 4
Project: bdf2   File: BpmServiceImpl.java   Source Code and License Vote up 6 votes
private void addProcessDefinition(String processDefinitionId){
	Session session=this.getSessionFactory().openSession();
	IUser user=ContextHolder.getLoginUser();
	String companyId=null;
	if(user!=null){
		companyId=user.getCompanyId();
	}
	String fixedCompanyId=Configure.getString("bdf2.jbpm4.fixedCompanyId");
	if(StringUtils.isEmpty(fixedCompanyId)){
		fixedCompanyId=Configure.getString(IDao.FIXED_COMPANY_ID);
	}
	if(StringUtils.isNotEmpty(fixedCompanyId)){
		companyId=fixedCompanyId;
	}
	try{
		com.bstek.bdf2.jbpm4.model.ProcessDefinition pd=new com.bstek.bdf2.jbpm4.model.ProcessDefinition();
		pd.setCompanyId(companyId);
		pd.setId(processDefinitionId);
		pd.setCreateDate(new Date());
		session.save(pd);
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 5
Project: hibernateMaster   File: DaoUtil.java   Source Code and License Vote up 6 votes
/**
 * 如果数据库有obj对象就update否则save
 * @param obj
 * @return
 */
public final static boolean saveOrUpdate(BaseRelationalDatabaseDomain obj){
	Session session = null;
	try {
		session = getSession();
		beginTransaction();
		if (BaseUtil.isObjEmpty(DomainUtil.getDomainId(obj))) {
			return save(obj);
		}else {
			BaseRelationalDatabaseDomain smartGet = smartGet(obj);
			if (smartGet != null) {
				session.evict(smartGet);
				session.update(obj);
			}else {
				session.save(obj);
			}
		}
		return managTransaction(true);
	} catch (Exception e) {
		setException(e);
		return managTransaction(false);
	}finally{
		closeSession();
	}
}
 
Example 6
Project: DWSurvey   File: SurveyAnswerDaoImpl.java   Source Code and License Vote up 6 votes
private int saveCompChehRadioMaps(SurveyAnswer surveyAnswer,
		Map<String, Object> compChenRadioMaps, Session session) {
	String surveyId=surveyAnswer.getSurveyId();
	String surveyAnswerId=surveyAnswer.getId();
	
	int answerQuCount=0;
	if(compChenRadioMaps!=null){
		for (String key : compChenRadioMaps.keySet()) {
			String quId=key;
			Map<String,Object> mapRows=(Map<String, Object>) compChenRadioMaps.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 optionId=mapRow.get(keyCol).toString();
					AnCompChenRadio anCompChenRadio=new AnCompChenRadio(surveyId,surveyAnswerId,quId,rowId,colId,optionId);
					session.save(anCompChenRadio);
				}
			}
		}
	}
	return answerQuCount;
}
 
Example 7
Project: ImageClassify   File: ImageService.java   Source Code and License Vote up 6 votes
@Override
public boolean saveImageCategory(Image_Category image_Category) {
	Session session = HibernateUtils.getSession(); //生成session实例
    Transaction tx = session.beginTransaction();  //创建transaction实例
     
    try {   
        session.save(image_Category); 
        tx.commit();            //提交事务 
        return true;
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();          //回滚事务 
		return false;
	}finally {
	  HibernateUtils.closeSession();  //关闭Session实例
	} 
}
 
Example 8
Project: FlashBoard   File: Driver2.java   Source Code and License Vote up 6 votes
public static void createAdmin() {
	Session session = HibernateUtil.getSession();
	Transaction tx = null;
	
	User newUser = new User("John", "Doe", "admin", "[email protected]", "password", 2);
	
	try {
		tx = session.beginTransaction();
		session.save(newUser);
		tx.commit();
		System.out.println("User: '" + newUser.getUsername() + "' has been successfully created!");
	} catch (HibernateException he) {
		if (tx != null) {
			tx.rollback();
		}
		System.out.println("User creation failed!");
		he.printStackTrace();
		
	} finally {
		session.close();
	}
}
 
Example 9
Project: java-jdbc   File: HibernateTest.java   Source Code and License Vote up 6 votes
@Test
public void hibernate() {
  SessionFactory sessionFactory = createSessionFactory(false);
  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);
  assertNull(mockTracer.activeSpan());
}
 
Example 10
Project: uflo   File: DeployProcessResourceCommand.java   Source Code and License Vote up 5 votes
public Blob execute(Context context) {
	Session session=context.getSession();
	if(update){
		Query query=session.createQuery("delete from "+Blob.class.getName()+" where processId=:processId");
		query.setLong("processId", processId);
		query.executeUpdate();
	}
	Blob lob=new Blob();
	lob.setId(IDGenerator.getInstance().nextId());
	lob.setBlobValue(processRes);
	lob.setName(name);
	lob.setProcessId(processId);
	session.save(lob);
	return lob;
}
 
Example 11
Project: uflo   File: HeartbeatDetectionJob.java   Source Code and License Vote up 5 votes
public void execute(JobExecutionContext context) throws JobExecutionException {
	DetectionJobDetail jobDetail=(DetectionJobDetail)context.getJobDetail();
	Session session=jobDetail.getSessionFactory().openSession();
	try {
		String currentInstanceName=jobDetail.getCurrentInstanceName();
		Operation operation=detection(session,jobDetail.getJobInstanceNames(),currentInstanceName);
		if(operation.equals(Operation.reset)){
			SchedulerService service=jobDetail.getSchedulerService();
			service.resetScheduer();
			
			Heartbeat beat=new Heartbeat();
			Calendar c=Calendar.getInstance();
			c.setTime(new Date());
			c.add(Calendar.SECOND, 1);
			beat.setDate(c.getTime());
			beat.setId(UUID.randomUUID().toString());
			beat.setInstanceName(currentInstanceName);
			session.save(beat);
			
			initHeartJob(currentInstanceName, service.getScheduler());
		}
	} catch (Exception e) {
		throw new JobExecutionException(e);
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 12
Project: bdf2   File: PositionMaintain.java   Source Code and License Vote up 5 votes
@DataResolver
public void savePostions(final Collection<DefaultPosition> positions) {
	Session session = this.getSessionFactory().openSession();
	try {
		IUser user = ContextHolder.getLoginUser();
		if (user == null) {
			throw new NoneLoginException("Please login first");
		}
		String companyId = user.getCompanyId();
		if (StringUtils.isNotEmpty(getFixedCompanyId())) {
			companyId = getFixedCompanyId();
		}
		for (DefaultPosition position : positions) {
			EntityState state = EntityUtils.getState(position);
			if (state.equals(EntityState.NEW)) {
				position.setCompanyId(companyId);
				position.setCreateDate(new Date());
				session.save(position);
			} else if (state.equals(EntityState.MODIFIED)) {
				session.update(position);
			} else if (state.equals(EntityState.DELETED)) {
				roleService.deleteRoleMemeber(position.getId(), MemberType.Position);
				groupService.deleteGroupMemeber(position.getId(), MemberType.Position);
				positionService.deleteUserPosition(position.getId());
				session.delete(position);
			}
		}
	} finally {
		session.flush();
		session.close();
	}
}
 
Example 13
Project: bdf2   File: ComponentMaintain.java   Source Code and License Vote up 5 votes
@DataResolver
public void saveSorts(Collection<ComponentSort> sorts,String url,String parentComponentId,String controlId,String assignTargetId,String type){
	Session session=this.getSessionFactory().openSession();
	try{
		this.checkCompoentInfo(session, url, parentComponentId, controlId, assignTargetId, type);
		session.createQuery("delete "+ComponentSort.class.getName()+" where parentComponentId=:parentComponentId").setString("parentComponentId",parentComponentId).executeUpdate();
		for(ComponentSort sort:sorts){
			sort.setId(UUID.randomUUID().toString());
			session.save(sort);
		}
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 14
Project: SchTtableServer   File: CourseDaoImpl.java   Source Code and License Vote up 5 votes
@Override
public boolean add(CourseBean courseBean) throws Exception {
    if (courseBean == null) {
        return false;
    }
    
    Session session = sessionFactory.getCurrentSession();
    session.save(courseBean);
    return true;
}
 
Example 15
Project: hibernate-springcache   File: EventManager.java   Source Code and License Vote up 5 votes
public Long addPersonToAccount(Long personId, Account account) {
	Session session = sessionFactory.getCurrentSession();
	session.beginTransaction();

	Person aPerson = session.load(Person.class, personId);
	account.setPerson(aPerson);

	Long accountId = (Long)session.save(account);

	session.getTransaction().commit();
	return accountId;
}
 
Example 16
Project: bdf2   File: UrlMaintain.java   Source Code and License Vote up 5 votes
@DataResolver
public void saveUrls(Collection<Url> urls) throws Exception{
	IUser user=ContextHolder.getLoginUser();
	if(user==null){
		throw new NoneLoginException("Please login first");
	}
	String companyId=user.getCompanyId();
	if(StringUtils.isNotEmpty(getFixedCompanyId())){
		companyId=getFixedCompanyId();
	}
	Session session=this.getSessionFactory().openSession();
	try{
		for(Url url:urls){
			EntityState state=EntityUtils.getState(url);
			if(state.equals(EntityState.NEW)){
				url.setId(UUID.randomUUID().toString());
				url.setCompanyId(companyId);
				session.save(url);
			}
			if(state.equals(EntityState.MODIFIED) || state.equals(EntityState.MOVED)){
				session.update(url);
			}
			if(url.getChildren()!=null){
				saveUrls(url.getChildren());
			}
			if(state.equals(EntityState.DELETED)){
				session.delete(url);
			}
		}
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 17
Project: TrabalhoCrisParte2   File: DAOFornecedor.java   Source Code and License Vote up 4 votes
public void armazenar(Fornecedor fornecedor) {


       Session session = DAOHibernateUtil.getSession();

       try {

           session.beginTransaction(); // Abre-se uma transação
           session.save(fornecedor);      // Acumula a operação de gravação do objeto produto no BD, na transação
           session.getTransaction().commit();   // Realiza definitivamente todas as operações pendentes na transação
           JOptionPane.showMessageDialog(null, "Fornecedor armazenado com sucesso");

       } catch (Exception ex) {
           JOptionPane.showMessageDialog(null, ex);

       }
   }
 
Example 18
Project: Homework   File: MasterDaoImpl.java   Source Code and License Vote up 4 votes
public void save(Master master, Session session, Transaction tx)
{
    session.save(master);
    session.flush();
}
 
Example 19
Project: OpenVertretung   File: HibernateFabric.java   Source Code and License Vote up 4 votes
public static void main(String args[]) throws Exception {

        String hostname = System.getProperty("com.mysql.fabric.testsuite.hostname");
        String port = System.getProperty("com.mysql.fabric.testsuite.port");
        String user = System.getProperty("com.mysql.fabric.testsuite.username");
        String password = System.getProperty("com.mysql.fabric.testsuite.password");
        String database = System.getProperty("com.mysql.fabric.testsuite.database");
        String fabricUsername = System.getProperty("com.mysql.fabric.testsuite.fabricUsername");
        String fabricPassword = System.getProperty("com.mysql.fabric.testsuite.fabricPassword");

        // Using JDBC Fabric connection to create database and table
        Class.forName("com.mysql.fabric.jdbc.FabricMySQLDriver");
        Connection con = DriverManager.getConnection("jdbc:mysql:fabric://" + hostname + ":" + Integer.valueOf(port)
                + "/mysql?fabricServerGroup=fabric_test1_global&fabricUsername=" + fabricUsername + "&fabricPassword=" + fabricPassword, user, password);
        Statement stmt = con.createStatement();
        stmt.executeUpdate("create database if not exists employees");
        con.close();

        con = DriverManager.getConnection("jdbc:mysql:fabric://" + hostname + ":" + Integer.valueOf(port) + "/" + database
                + "?fabricServerGroup=fabric_test1_global&fabricUsername=" + fabricUsername + "&fabricPassword=" + fabricPassword, user, password);
        stmt = con.createStatement();
        stmt.executeUpdate("create database if not exists employees");
        stmt.executeUpdate("drop table if exists employees.employees");
        stmt.executeUpdate("create table employees.employees (emp_no INT PRIMARY KEY, first_name CHAR(40), last_name CHAR(40))");
        stmt.close();

        // we have to wait for replication ....
        Thread.sleep(2000);

        // Using Hibernate
        SessionFactory sf = createSessionFactory("http://" + hostname + ":" + port, user, password, fabricUsername, fabricPassword);

        // add some employees
        for (int i = 1; i < 11; ++i) {
            int j = i;
            // put a few in the other shard
            if ((j % 2) == 0) {
                j += 10000;
            }

            Session session = sf.withOptions().tenantIdentifier("" + j) // choose a db server
                    .openSession();

            // vanilla hibernate code
            session.beginTransaction();
            Employee e = new Employee();
            e.setId(j);
            e.setFirstName("First name of employee " + j);
            e.setLastName("Smith" + j);
            session.save(e);

            session.getTransaction().commit();
            session.close();
        }

        // clean up
        con.createStatement().executeUpdate("drop table employees.employees");
        con.close();

    }
 
Example 20
Project: sdudoc   File: CollectDaoImpl.java   Source Code and License Vote up 4 votes
@Override
public void addCollect(Collect collect) {
	Session session = sessionFactory.getCurrentSession();
	session.save(collect);
}