Transaction not successfully started异常分析及解决

本文探讨了在使用Spring管理事务时,如何正确执行Hibernate的更新操作,避免Transactionnotsuccessfullystarted异常,并提供了Spring事务配置示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在执行更新操作,写了如下

final String cardid = udto.getCarid0(); final String scdlsj = udto.getScdlsj(); final String bcdlsj = udto.getBcdlsj(); SessionFactory sf = hibernateTemplate.getSessionFactory(); Session s = sf.getCurrentSession(); //用spring管理了事务,不用写beginTransaction() //s.beginTransaction(); s.createQuery("update User u set u.scdlsj=:scdlsj,u.bcdlsj=:bcdlsj where carid0 = :carid0") .setString("scdlsj", scdlsj) .setString("bcdlsj", bcdlsj) .setString("carid0", cardid).executeUpdate(); //s.getTransaction().commit();

因为在spring中已经配置了事务,这里在写beginTransaction(),就会报
Transaction not successfully started异常

将其代码注释,如上面代码

附上spring中的事务配置

<!-- 事务 --> <bean id="myTxManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <aop:config> <aop:pointcut id="bussinessService" expression="execution(public * com.wuqn.login.dao.impl..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="bussinessService" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="myTxManager"> <tx:attributes> <tx:method name="exists" read-only="true" /> <tx:method name="add" propagation="REQUIRED" /> <tx:method name="load*" propagation="REQUIRED" /> <tx:method name="set*" propagation="REQUIRED" /> </tx:attributes> </tx:advice>


或者将SessionFactory.getCurrentSession() 改为 SessionFactory.OpenSession();

它们的区别 详见http://blog.youkuaiyun.com/woisnong/article/details/7423986

def execute_add_robot(self, sn, ip, fp, device_type, pi_ip=None): try: with self.db_engine.connect() as conn: # Start a transaction with conn.begin(): columns = ["serialnumber", "dut_ip", "floorplan", "device_type", "team", "available", "base_type", "pi_ip"] values = { "serialnumber": sn, "dut_ip": ip, "floorplan": fp, "device_type": device_type, "team": "local", "available": "1", "base_type": "ChargeBase", "pi_ip": pi_ip if pi_ip else "" } insert_stmt = text(f""" INSERT INTO devices ({', '.join(columns)}) VALUES ({', '.join([f':{col}' for col in columns])}) """) conn.execute(insert_stmt, values) if not ip.replace('.', '').isdigit(): raise ValueError("Illegal IP format") status_ip = f"status_{ip.replace('.', '_')}" create_table_sql = f""" CREATE TABLE IF NOT EXISTS `{status_ip}` ( `robot_ip` varchar(17) NOT NULL DEFAULT '{ip}', `status_busy` BOOLEAN NOT NULL DEFAULT 0, `status_base` BOOLEAN NOT NULL DEFAULT 0, `status_error` BOOLEAN NOT NULL DEFAULT 0, `status_warning` BOOLEAN NOT NULL DEFAULT 0, `external_voltage` INTEGER NOT NULL DEFAULT 0, `battery_capacity` INTEGER NOT NULL DEFAULT 100, `can_be_started` BOOLEAN NOT NULL DEFAULT 1, `last_entry_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `last_event` VARCHAR(255) NOT NULL DEFAULT 'not-initialized', `remote_rf_port` INTEGER DEFAULT 8970, `installed_firmware` VARCHAR(50) NOT NULL DEFAULT 'not-initialized', `queue_status` VARCHAR(255) NOT NULL DEFAULT 'not-initialized', `queue_length` VARCHAR(255) NOT NULL DEFAULT 'not-initialized', `queue_task` VARCHAR(255) NOT NULL DEFAULT 'not-initialized', UNIQUE KEY `robot_ip` (`robot_ip`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 """ self.execute_on_db(create_table_sql) replace_sql = text(f"REPLACE INTO `{status_ip}` (robot_ip) VALUES (:ip)") conn.execute(replace_sql, {"ip": ip}) return "Device information submitted successfully!", True except SQLAlchemyError as e: return f"Database error: {str(e)}", False except ValueError as ve: return f"IP format error: {str(ve)}", False except Exception as ex: return f"Unexpected error: {str(ex)}", False 增加注释
最新发布
03-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值