如果数据库不支持事务,如何保证sql执行中出错回滚

如果数据库不支持事务,也不能改为支持事务的存储引擎,如何解决sql执行中出错进行回滚。

3个回答

比如说MySQL,MyISAM存储引擎实际上是对整张表加上了写锁,即使出错,也只是当前语句不执行而已。

sinat_39397107
暴躁小马 那出错之前已经执行的sql语句该如何回滚
12 个月之前 回复

可以使用悲观锁或者欢乐锁!

只能使用手动捕捉错误,然后手动把数据改回去

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
C# 数据模型是dbml,从sqlserver转sqlite,事务中InsertOnSubmit出错
一个桌面程序,数据库要从sqlserver转到sqlite,我还在研究中,只是想把目前理解到的信息发出来,希望有类似经验的人能一针见血 数据模型是dbml的,一次insert为例 ``` DBModel.Test data=... DataContext dc = theDB.GetDataContext(); dc.GetTable<DBModel.Test>().InsertOnSubmit(data); dc.SubmitChanges(); ``` 数据库连接已经变了,在某次操作中,不用事务,且只进行一次如上操作时,没有问题。如果操作中,有2次以上如上操作时,原来的程序是用事务的,在第一次如上操作时就报错, ![图片说明](https://img-ask.csdn.net/upload/201709/28/1506588085_268719.png) 我把第一次的操作改成insert into Test。。。的sql语句,执行能过去,到了下一个操作又报同样的错误。 以下2017年9月29日 11:28:35 听了caozhy的建议。我去看了生成的sql。不报错的是类似这样的 ``` exec sp_executesql N'INSERT INTO [dbo].[CustomerInfo]([customerNo], [customerType], [contractNo], [customerName]) VALUES (@p0, @p1, @p2, @p3, @p4)',N'@p0 nvarchar(4000),@p1 int,@p2 nvarchar(4000),@p3 nvarchar(4000),@p4 nvarchar(4000)',@p0=N'1000000150',@p1=0,@p2=N'',@p3=N'321654987',@p4=N'321654987' ``` 而报错的是这样的 ``` exec sp_executesql N'INSERT INTO [dbo].[ReceiptItemDetial]([ReceiptNo], [items], [Unit], [Price], [Quantity], [subTotal], [remark]) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6) SELECT CONVERT(Int,SCOPE_IDENTITY()) AS [value]',N'@p0 int,@p1 nvarchar(4000),@p2 nvarchar(4000),@p3 decimal(18,3),@p4 decimal(18,3),@p5 decimal(18,3),@p6 nvarchar(4000)',@p0=14402,@p1=N'sdfg',@p2=N'元/米',@p3=1.000,@p4=1.000,@p5=1.000,@p6=N'' ``` 看了sql。我想起了这些表的差别了。不报错的那几个表,主键是nvarchar,而报错的那几个,主键是int,自增的。或许这就是他们sql语句不同的原因?也是转到sqlite错误的原因?
C# MySQL事务回滚无效
![图片说明](https://img-ask.csdn.net/upload/202003/11/1583920110_472462.jpg) ![图片说明](https://img-ask.csdn.net/upload/202003/11/1583920171_582727.jpg)![图片说明](https://img-ask.csdn.net/upload/202003/11/1583920254_505999.jpg) 数据库引擎什么的都改了,如果语句直接执行回滚是可以的,但是出错了就没有办法回滚,执行过的还是被提交了没有被回滚,求助!
php中 预处理与事务同时使用
sql1,sql2两条语句分别插入到不同的表中,sql2某一个属性就是sql1插入后自增长的ID值, 我希望使用预处理来处理sql1和sql2, 同时希望他们执行的时候是在一个事务中, 现在问题就是, 事务中没提交的操作并没有真的插入到数据库中, 所以自增长的ID不存在,sql2插入出错, 肿麽办?
求助:php获取事务是否成功问题
ezql php新手 事务怎么捕捉操作数据库出错 多条语句操作数据库 全部成功执行才提交事务 否则回滚 比如 insert 一句成功执行 update 语句执行无错,但更新影响到的记录为0,此时是不要回滚的 如下,$uname 值与数据库中 uname 值相同 $res 就返回0 事务失败 $db->query("BEGIN"); $sql="update member set uname=$uname where id=$id"; $res=$db->query($sql); if($res){ $db->query("COMMIT"); errAlert("成功","list.php"); }else{ $db->query("ROLLBACK"); errAlert("失败,发生错误",$theUrl); } $db->query("END");
求助下关于VB6连接SQL Sever 2008数据库的问题
Private Sub Borrow_Click() '单击“借书”按钮 Dim Readernumber, ISBN, BookID As String Dim in_ReaderID, in_ISBN, in_BookID, out_str '储存过程执行的参数 Dim ReturnValue As Integer '定义返回值变量 Dim Strs As String Readernumber = ReaderID.Text ISBN = T_ISBN.Text BookID = T_BookID.Text '如果借书证号、ISBN、图书ID均不为空 If Readernumber <> "" And ISBN <> "" And BookID <> "" Then SqlCmd.CommandText = "Book_Borrow" SqlCmd.CommandType = adCmdStoredProc '追加参数法调用存储过程 Set in_ReaderID = SqlCmd.CreateParameter("@in_ReaderID", adChar, adParamInput, 8) SqlCmd.Parameters.Append (in_ReaderID) Set in_ISBN = SqlCmd.CreateParameter("@in_ISBN", adChar, adParamInput, 18) SqlCmd.Parameters.Append (in_ISBN) Set in_BookID = SqlCmd.CreateParameter("@in_BookID", adChar, adParamInput, 10) SqlCmd.Parameters.Append (in_BookID) Set out_str = SqlCmd.CreateParameter("@out_str", adChar, adParamInput, 30) SqlCmd.Parameters.Append (out_str) '参数赋值 SqlCmd("@in_ReaderID") = ReaderID.Text SqlCmd("@in_ISBN") = T_ISBN.Text SqlCmd("@in_BookID") = T_BookID.Text SqlCmd.Execute (ReturnValue) '执行存储过程,并将返回值赋给ReturnValue Strs = SqlCmd.Parameters("@out_str") '将存储过程输出参数的值赋给变量Strs MsgBox (Strs) '给出提示信息 '删除参数 SqlCmd.Parameters.delete ("@in_ReaderID") SqlCmd.Parameters.delete ("@in_ISBN") SqlCmd.Parameters.delete ("@in_BookID") SqlCmd.Parameters.delete ("@out_str") '刷新BorrowADO控件 BorrowADO.RecordSource = "SELECT * FROM RBL WHERE 借书证号='" + Trim(Readernumber) + "'" BorrowADO.Refresh Else MsgBox ("请输入正确的借书信息!") End If End Sub 数据库已经设置好,Book_Borrow存储过程也设置好了,在SQL中执行未出错 代码中 SqlCmd.Execute (ReturnValue) '执行存储过程,并将返回值赋给ReturnValue 这一行出错 实时错误'-2147217904 (80040e10)' 过程或函数'Book_Borrow'需要参数'@out_str',但未提供该参数 希望有高手可以帮我查查错,感谢 附上SQL里的设置 USE MBOOK GO CREATE PROCEDURE Book_Borrow @in_ReaderID char(6),@in_ISBN char(18), @in_BookID char(10),@out_str char(30) OUTPUT AS BEGIN /*判断是否存在该读者*/ IF NOT EXISTS(SELECT * FROM TReader WHERE 借书证号=@in_ReaderID) BEGIN SET @out_str='该读者不存在' RETURN 0 END /*判断是否存在该图书*/ IF NOT EXISTS(SELECT * FROM TBook WHERE ISBN=@in_ISBN) BEGIN SET @out_str='该图书不存在' RETURN 0 END /*判断借书量是否已经到了借书上限数5*/ IF(SELECT 借书量 FROM TReader WHERE 借书证号=@in_ReaderID)=5 BEGIN SET @out_str='读者借书量不能大于5' RETURN 0 END /*判断库存量是否为0*/ IF (SELECT 库存量 FROM TBook WHERE ISBN=@in_ISBN)=0 BEGIN SET @out_str='图书库存量为0' RETURN 0 END /*判断读者是否已经借过该书*/ IF @in_ISBN IN (SELECT ISBN FROM TLend WHERE 借书证号=@in_BookID) BEGIN SET @out_str='读者已经借过该书' RETURN 0 END /*判断该书是否已经被借*/ IF EXISTS(SELECT * FROM TLend WHERE 图书ID=@in_BookID) BEGIN SET @out_str='该图书ID已存在' RETURN 0 END BEGIN TRAN /*开始一个事务*/ /*插入借书记录*/ INSERT INTO TLend(借书证号,ISBN,图书ID,借书时间) VALUES(@in_ReaderID,@in_ISBN,@in_BookID,GETDATE()) IF @@ERROR>0 /*如果前面一条SQL语句出错则回滚事务并返回*/ BEGIN ROLLBACK TRAN SET @out_str='执行过程中遇到错误' RETURN 0 END UPDATE TReader SET 借书量=借书量+1 WHERE 借书证号=@in_ReaderID IF @@ERROR>0 /*如果前面一条SQL语句出错则回滚事务并返回*/ BEGIN ROLLBACK TRAN SET @out_str='执行过程中遇到错误' RETURN 0 END UPDATE TBook SET 库存量=库存量-1 WHERE ISBN=@in_ISBN IF @@ERROR>0 /*如果前面一条SQL语句出错则回滚事务并返回*/ BEGIN ROLLBACK TRAN SET @out_str='执行过程中遇到错误' RETURN 0 END UPDATE TBLend SET 是否借出=1 WHERE 图书ID=@in_BookID IF @@ERROR=0 /*如果所有语句都不出错则结束事务并返回*/ BEGIN COMMIT TRAN SET @out_str='借书成功' RETURN 1 END ELSE /*如果执行出错则回滚所有操作并返回*/ BEGIN ROLLBACK TRAN SET @out_str='执行过程中遇到错误' RETURN 0 END END 这是在SQL 2008中执行的Borrow_Book过程
db2 存储过程加了atomic不回滚是什么原因
CREATE PROCEDURE "LOAN".PROCDEALDAILYBAL ( IN V_DATE VARCHAR(10) ) SPECIFIC "PROCDEALDAILYBAL" DYNAMIC RESULT SETS 1 LANGUAGE SQL NOT DETERMINISTIC EXTERNAL ACTION MODIFIES SQL DATA CALLED ON NULL INPUT INHERIT SPECIAL REGISTERS begin declare V_DEALED varchar(1) default '1'; declare V_INVALID_YEAR integer; declare V_INVALID_DAY varchar(5); declare V_INVALID_DATE varchar(10); declare V_INVALID_DATE_RN varchar(10); declare V_CONSUM_SQL varchar(512); declare USEREXCEPTION CONDITION FOR SQLSTATE '99998'; declare sqlcode INTEGER DEFAULT 0;-- declare sqlstate CHAR(5);-- declare V_MESSAGE CHAR(100);-- declare MESSAGE_TEXT VARCHAR(100);-- declare EXIT HANDLER FOR SQLEXCEPTION begin values ('调用失败,SQLCode:' || CHAR(sqlcode) || 'SQLState:' || CHAR(sqlstate)) INTO V_MESSAGE;-- insert into ITG_DATA_UPLOAD(WORKDATE,DATATIME,PACKETERR,PACKETFLAG) values (to_char(current timestamp ,'yyyyMMddHH24miss'),V_DATE,V_MESSAGE,'0');-- SIGNAL SQLSTATE '99999';-- SET MESSAGE_TEXT = V_DATE || ' 日数据更新失败!';-- end;-- declare GLOBAL TEMPORARY TABLE session.USER_CONSUM ( CUSTOMID VARCHAR(32), CONSUM DECIMAL(18,8) ) NOT LOGGED WITH REPLACE;-- declare GLOBAL TEMPORARY TABLE session.DAILY_BAL ( CUSTOMID VARCHAR(32), CUSTOMNAME VARCHAR(64), BALANCE DECIMAL(18,8) ) NOT LOGGED WITH REPLACE;-- set V_INVALID_YEAR = integer(to_char(to_date(V_DATE,'yyyy-MM-dd') -1 years,'yyyy')); set V_INVALID_DAY = substr(V_DATE,6); set V_INVALID_DATE = to_char(to_date(V_DATE,'yyyy-MM-dd') -1 years,'yyyy') || substr(V_DATE,5); set V_INVALID_DATE_RN = to_char(to_date(V_INVALID_DATE,'yyyy-MM-dd') -1 days,'yyyy-MM-dd'); select count(1) into V_DEALED from ITG_DATA_UPLOAD where DATATIME = V_DATE AND PACKETFLAG = '1';-- if V_DEALED <> '0' then SIGNAL USEREXCEPTION;-- end if; if ((mod(V_INVALID_YEAR,400) = 0 ) or ( mod(V_INVALID_YEAR , 4) = 0 and mod(V_INVALID_YEAR , 100) != 0 )) and (V_INVALID_DAY = '03-01') then set V_CONSUM_SQL = 'insert into session.USER_CONSUM select customid,COALESCE(sum(COALESCE(integraldec,0)),0) - COALESCE(sum(COALESCE(integraladd,0)),0) from itg_details where trandate >=''' || V_INVALID_DATE_RN || ''' group by customid'; else set V_CONSUM_SQL = 'insert into session.USER_CONSUM select customid,COALESCE(sum(COALESCE(integraldec,0)),0) - COALESCE(sum(COALESCE(integraladd,0)),0) from itg_details where trandate >=''' || V_INVALID_DATE || ''' group by customid'; end if;-- EXECUTE IMMEDIATE V_CONSUM_SQL;-- --事物开始 p1: begin atomic insert into session.DAILY_BAL select a.acustomid,a.acustomname, case when COALESCE(a.ALSTYEAR,0) >= COALESCE(b.CONSUM,0) then COALESCE(a.AYEAR,0) - ( COALESCE(a.ALSTYEAR,0) - COALESCE(b.CONSUM,0) ) else COALESCE(a.AYEAR,0) end from ITG_BALANCE_DAILY a left join session.USER_CONSUM b on a.acustomid = b.customid;-- merge into ITG_BALANCE a USING (select * from session.DAILY_BAL) b on (a.customid=b.customid) when matched then update set a.balance = a.balance + b.balance when not matched then insert (a.customid,a.customname,a.balance) values (b.customid,b.customname,b.balance);-- --插入日志表 insert into ITG_DATA_UPLOAD(WORKDATE,DATATIME,PACKETERR,PACKETFLAG) values(to_char(current timestamp ,'yyyyMMddHH24miss')||'1111111111111111',V_DATE,'数据更新成功','1');-- end p1; end 在p1 模块加了atomic 我在插入日志表这块故意让他出错 但是merge into 这部分却没有回滚,不知道为什么 求解
spring使用声明事务不能回滚,请帮我看下原因
初学spring,编写一个事务的例子,但是不能回滚。代码如下 spring配置文件 [code="java"] <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="homePlaceholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>classpath:config.properties</value> </property> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName"> <value>${datasource.driverClassName}</value> </property> <property name="url"> <value>${datasource.url}</value> </property> <property name="username"> <value>${datasource.username}</value> </property> <property name="password"> <value>${datasource.password}</value> </property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"><ref local="dataSource"/></property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"> <ref local="dataSource" /> </property> </bean> <bean id="txProxyTemplate" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"><ref local="transactionManager"/></property> <property name="transactionAttributes"> <props> <prop key="addUser">PROPAGATION_REQUIRED</prop> </props> </property> </bean> <bean id="userDao" class="cn.com.home.dao.jdbc.UserDao" autowire="byName"></bean> <bean id="userServiceTarget" class="cn.com.home.service.UserService" autowire="byName"></bean> <bean id="userService" parent="txProxyTemplate" > <property name="target"><ref local="userServiceTarget"/></property> </bean> </beans> [/code] dao代码 [code="java"] public class UserDao { private JdbcTemplate jdbcTemplate; /** * @param jdbcTemplate * the jdbcTemplate to set */ public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } /** * * @param user */ public void save(User user) throws DatabaseException { String sql = "insert into t_user (id,name,sex,age,city) values (?,?,?,?,?)"; Object[] params = new Object[] { user.getId(), user.getName(), user.getSex(), user.getAge(), user.getCity() }; try { jdbcTemplate.update(sql, params); } catch (Exception e) { log.error(e.getMessage(), e); throw new DatabaseException(e); } } } [/code] service代码 [code="java"] public class UserService{ private UserDao userDao; /** * @param userDao * the userDao to set */ public void setUserDao(UserDao userDao) { this.userDao = userDao; } /** * @throws Exception * */ public void addUser() throws DatabaseException { User u = new User(); u.setId(Long.valueOf(123)); u.setName("张三"); u.setAge(20); u.setSex("男"); u.setCity(571); userDao.save(u); User u2 = new User(); u2.setId(Long.valueOf(123)); u2.setName("李四"); u2.setAge(20); u2.setSex("男男男男男男男男男男男男男男男男男男男男男男男男男男"); u2.setCity(571); userDao.save(u2); } /** * @param args */ public static void main(String[] args) { BeanFactory bf = new ClassPathXmlApplicationContext( "spring/applicationContext.xml"); UserService service = (UserService) bf.getBean("userService"); try { service.addUser(); } catch (DatabaseException e) { } } } [/code] 第二个user的sex故意设置成超过数据库字段长度的值,故意是inser出错。 但是为什么 这个事务没有回滚呢? 结果是第一个user插入到了数据库中。应该是两个都没有提交的。
2000数据库提示未撤销日志记录,怎么办呢
2019-10-23 08:37:10.60 spid52 SQL Server 断言: 文件: <page.cpp>,行 = 2777 ... 2019-10-23 08:37:10.61 spid52 Using 'sqlimage.dll' version '4.0.5'... 2019-10-23 08:37:10.61 spid52 ex_raise2: Exception raised, major=34, minor=48, severity=21, attempting to cre 2019-10-23 08:37:10.61 spid52 错误: 3624,严重度: 20,状态: 1。 2019-10-23 08:37:10.77 spid52 Using 'sqlimage.dll' version '4.0.5'... 2019-10-23 08:37:10.77 spid52 ex_raise2: Exception raised, major=34, minor=48, severity=25, attempting to cre 2019-10-23 08:37:10.77 spid52 Could not undo log record (26587:31:3), for transaction ID (3:3670864), on page 2019-10-23 08:37:10.77 spid52 错误: 3448,严重度: 21,状态: 1 2019-10-23 08:37:10.77 spid52 未能撤消日志记录 (26587:31:3),它属于事务 ID (3:3670864),位于页 (1:5857),数据库 'hydee'(数据库 ID 7)。页 2019-10-23 08:37:10.77 spid52 错误: 3448,严重度: 21,状态: 1 2019-10-23 08:37:10.86 spid52 Error while undoing logged operation in database 'hydee'. Error at log record I 2019-10-23 08:37:10.86 spid52 错误: 3314,严重度: 21,状态: 5 2019-10-23 08:37:10.86 spid52 撤消数据库 'hydee' 的日志中记录的操作时出错。出错位置在日志记录 ID (26587:31:1)。。 2019-10-23 08:37:10.86 spid52 错误: 3314,严重度: 21,状态: 5 2019-10-23 08:37:10.86 spid52 The log for database 'hydee' is not available.。 2019-10-23 08:37:10.86 spid52 错误: 9001,严重度: 21,状态: 1 2019-10-23 08:37:10.86 spid52 数据库 'hydee' 的日志不可用。。 2019-10-23 08:37:10.86 spid52 错误: 9001,严重度: 21,状态: 1 2019-10-23 08:37:10.86 spid52 Error while undoing logged operation in database 'hydee'. Error at log record I 2019-10-23 08:37:10.86 spid52 错误: 3314,严重度: 21,状态: 4 2019-10-23 08:37:10.86 spid52 撤消数据库 'hydee' 的日志中记录的操作时出错。出错位置在日志记录 ID (26587:31:3)。。 2019-10-23 08:37:10.86 spid52 错误: 3314,严重度: 21,状态: 4
调用存储过程出错,提示不允许使用远程表值函数调用
1、项目使用springmvc, spring, mybatis三个框架 2、在一个serverice中调用dao的方法,dao方法执行的是一个存储过程,该service方法在spring的事务中进行了如下配置<tx:method name="refreshMetaData" propagation="NEVER">,不使用事务管理。 3、数据库使用SQL Server 2008 现在service在执行refreshMetaData,出现了如下问题: ![图片说明](https://img-ask.csdn.net/upload/201508/11/1439252234_292418.jpg) 而在数据库中直接执行这个存储过程就不会出现任何错误信息,正常执行。存储过程中使用了SQL Server的链接服务器linkedserver。 存储过程代码如下: 1 CREATE PROC [dbo].[PRO_UPDATE_METADATA] 2 @metadataclassId int, 3 @parentmetadataclassId int, 4 @metadataTabName varchar(500), 5 @linkedServerName varchar(8000), 6 @planDBHost varchar(20), 7 @planDBName varchar(200), 8 @planDBUser varchar(200), 9 @planDBPWD varchar(200), 10 @planDBPort varchar(10), 11 @trans INT output 12 AS 13 DECLARE @remoteServer varchar(8000) =''; -- 远程服务器地址 14 DECLARE @TableName varchar(8000) =''; -- 代码表名称 15 DECLARE @TableNames varchar(8000) =''; -- 所有代码表名称组成的字符串 16 DECLARE @fieldName varchar(8000) ='';-- 元数据字段名称 17 DECLARE @fieldNames varchar(8000) ='';-- 元数据所有字段名称组成的字符串 18 DECLARE @fieldNamesWithTempTable varchar(8000) ='';-- 元数据所有字段名称组成的字符串 19 DECLARE @readFieldsSQL varchar(8000) = ''; -- 需要读取的字段 20 DECLARE @readFieldsSQL2 varchar(8000) = ''; -- 需要读取的字段 21 DECLARE @inserDataSql varchar(8000) ='';-- 存储元数据的SQL 22 23 DECLARE @result_flag int = 0; -- 出错标识,用户事物回滚提交 24 25 DECLARE @count int; 26 DECLARE fieldsCur CURSOR FOR select CODE_TABLE, FIELD_NAME from TBL_METADATA_CLASS_FIELD where 27 METADATA_ID=@metadataclassId or METADATA_ID=@parentmetadataclassId; -- 元数据字段 28 29 30 DECLARE @dataTblName varchar(200);-- 包含元数据属性的数据表名称 31 DECLARE @getCodeTableDataSQL varchar(8000);-- 获取代码表数据的SQL 32 DECLARE @getDataTableSQL varchar(8000); -- 获取数据表数据的SQL 33 DECLARE @unitFiles varchar(8000); -- 获取被审计单位信息 34 DECLARE @joinConditions varchar(8000); -- -数据表于代码表查询数据的条件 35 DECLARE @tableCursorSQL nvarchar(max); -- 动态创建游标SQL 36 37 BEGIN 38 39 /*创建链接服务器*/ 40 set @remoteServer = @planDBHost + ',' + @planDBPort 41 -- 判断链接服务器是否存在 42 IF EXISTS (SELECT 1 FROM MASTER..SYSSERVERS WHERE SRVNAME = @linkedServerName) 43 EXEC SP_DROPSERVER @linkedServerName,'DROPLOGINS' 44 -- 创建链接服务器 45 EXEC sp_addlinkedserver 46 @server=@linkedServerName, 47 @srvproduct='', 48 @provider='SQLOLEDB', 49 @datasrc=@remoteServer; 50 51 -- 登录链接服务器 52 EXEC sp_addlinkedsrvlogin @linkedServerName, 'false', NULL, @planDBUser, @planDBPWD 53 54 BEGIN TRANSACTION; 55 56 /*获取元数据字段信息*/ 57 set @count = 0; 58 set @joinConditions = ' 1=1 ' 59 Open fieldsCur; 60 fetch next from fieldsCur Into @TableName,@fieldName 61 While ( @@Fetch_Status=0 ) 62 begin 63 DECLARE @tableAlias varchar(30); 64 set @tableAlias = 'data_tab_' + CONVERT(varchar(2), @count); 65 set @readFieldsSQL = @readFieldsSQL + ', ' + '[' + @tableAlias + '].[' + @fieldName + '] as [' + @fieldName + ']'; 66 set @readFieldsSQL2 = @readFieldsSQL2 + ', ' + '[#dataTblName#].[' + @fieldName + '] as [' + @fieldName + ']'; 67 set @fieldNames = @fieldNames + ', ' + '[' + @fieldName + ']'; 68 set @fieldNamesWithTempTable = @fieldNamesWithTempTable + ', ' + '#codetabledata.[' + @fieldName + ']'; 69 set @TableNames = @TableNames + ',[' + @linkedServerName + '].[' + @planDBName + '].[dbo].' + '[' + @TableName + '] ' + @tableAlias; 70 set @joinConditions = @joinConditions + ' and [#dataTblName#].[' + @fieldName + ']=#codetabledata.[' + @fieldName + ']'; 71 set @count = @count + 1; 72 fetch next from fieldsCur Into @TableName,@fieldName; 73 end 74 Close fieldsCur; 75 Deallocate fieldsCur; 76 77 IF @@ERROR<>0 78 SET @result_flag=1; 79 80 -- 找出包含元数据分类属性的表 81 set @tableCursorSQL = 'DECLARE tablesCur CURSOR FOR select tblName from ( ' + 82 'select ' + 83 'sysobjects.name as tblName, ' + 84 'COUNT(*) as colCount ' + 85 'from ' + @linkedServerName + '.' + @planDBName + '.dbo.sysobjects ' + 86 'left join ' + 87 @linkedServerName + '.' + @planDBName + '.dbo.syscolumns ' + 88 'on sysobjects.id = syscolumns.id ' + 89 'where ' + 90 'sysobjects.xtype=''U'' ' + 91 'and syscolumns.name in ( ' + 92 'select FIELD_NAME from TBL_METADATA_CLASS_FIELD ' + 93 'where METADATA_ID=' + convert(varchar(20), @metadataclassId) + ' or METADATA_ID= ' + convert(varchar(20), @parentmetadataclassId) + 94 ') ' + 95 'group by sysobjects.name ' + 96 ') as cc where colCount >=' + convert(varchar(20), @count) + ' and tblName not like ''代码表_%'''; 97 98 exec sp_executesql @tableCursorSQL; 99 100 IF @@ERROR<>0 101 SET @result_flag=1 102 103 -- 清空数据信息表 104 exec ('truncate table ' + @metadataTabName); 105 open tablesCur; 106 fetch next from tablesCur Into @dataTblName 107 While ( @@Fetch_Status=0 ) 108 begin 109 -- 获取代码表数据 110 set @getCodeTableDataSQL = 'select distinct ' + SUBSTRING(@readFieldsSQL, 2, LEN(@readFieldsSQL)-1) + ' into #codetabledata from ' + SUBSTRING(@TableNames, 2, LEN(@TableNames)-1); 111 112 -- 基本单位信息 113 set @unitFiles = ',TBL_UNDERAUDITUNIT.[underauditunit] as [被采集单位信息], TBL_UNDERAUDITUNIT.[datadesc] as [数据信息描述], ' + 114 'TBL_UNDERAUDITUNIT.[othersoft] as [对方软件信息], TBL_UNDERAUDITUNIT.[remark] as [备注] '; 115 116 set @getDataTableSQL = 'select [col_id] as [DC_ID], [unit_id] ' + @unitFiles + REPLACE(@readFieldsSQL2, '#dataTblName#', @dataTblName) + ' into #metatableadata from #codetabledata ' + 117 'left join ' + 118 @linkedServerName + '.' + @planDBName + '.dbo.' + @dataTblName + ' ' + 119 'on ' + 120 REPLACE(@joinConditions, '#dataTblName#', @dataTblName) + ' ' + 121 'left join TBL_UNDERAUDITUNIT ' + 122 'on ' + 123 'TBL_UNDERAUDITUNIT.id = ' + @dataTblName + '.unit_id where col_id is not null'; 124 125 126 set @inserDataSql = ' insert into ' + @metadataTabName + '([DC_ID],[被采集单位信息], [数据信息描述],[对方软件信息],[备注] ' + @fieldNames + ') select * from ( ' + 127 ' select [DC_ID],[被采集单位信息], [数据信息描述],[对方软件信息],[备注] ' + @fieldNames + ' from #metatableadata ' + 128 ' except ' + 129 ' select [DC_ID],[被采集单位信息], [数据信息描述],[对方软件信息],[备注] ' + @fieldNames + ' from ' + @metadataTabName + 130 ' ) as metatab '; 131 132 133 exec(@getCodeTableDataSQL + ';' + @getDataTableSQL + ';' + @inserDataSql + '; drop table #codetabledata; drop table #metatableadata;'); 134 135 136 fetch next from tablesCur Into @dataTblName 137 end 138 Close tablesCur; 139 Deallocate tablesCur; 140 141 IF @result_flag=1 142 BEGIN 143 ROLLBACK TRANSACTION 144 SET @trans=1 145 END 146 ELSE 147 BEGIN 148 COMMIT TRANSACTION 149 SET @trans =0 150 END 151 -- 退出登录 152 Exec sp_droplinkedsrvlogin @linkedServerName, null; 153 --删除链接服务器 154 Exec sp_dropserver @linkedServerName; 155 select @trans as trans 156 157 END
dbutils插入数据到mysql数据库报莫名其妙地NullpointerException
web层 public class BaseServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //获取子类字节码对象 Class clazz = this.getClass(); System.out.println(this); //获取method方法名参数,作为获取方法对象的参数 String m = request.getParameter("method"); if(m==null){ m="index"; } System.out.println(m); //获取方法对象 Method method = clazz.getMethod(m, HttpServletRequest.class, HttpServletResponse.class); //让方法执行,返回值为请求转发路径 String s = (String) method.invoke(this, request, response); System.out.println(s); //判断次路径是否为空,不为空请求转发到次路径 if(s != null){ request.getRequestDispatcher(s).forward(request, response); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } } public class OrderServlet extends BaseServlet { /** * 生成订单 * @param request * @param response * @return * @throws Exception */ public String add(HttpServletRequest request, HttpServletResponse response) throws Exception { //0判断用户是否登录 User user = (User) request.getSession().getAttribute("user"); if(user == null) { request.setAttribute("msg", "请先登录~~~~~"); return "/jsp/msg.jsp"; } //1封装数据 Order order = new Order(); //1.1 封装订单id order.setOid(UUIDUtils.getId()); //1.2封装订单时间 order.setOrderTime(new Date()); //1.3封装订单金额 //获取session中的购物车 Cart cart = (Cart) request.getSession().getAttribute("cart"); order.setTotal(cart.getTotalPrice()); //1.4封装订单项 //从购物车中获取购物车项,遍历购物车中的购物车项,得到每个订单项中的数据 for (CartItem cartItem : cart.getCartItem()) { OrderItem oi = new OrderItem(); //设置订单项id oi.setItemid(UUIDUtils.getId()); //设置订单项包含的商品 oi.setProduct(cartItem.getProduct()); //设置包含于那个订单 oi.setOrder(order); //设置订单项中的商品数 oi.setCount(cartItem.getCount()); //设置定单项的小计 oi.setSubTotal(cartItem.getSubTotal()); //添加订单项到order对 象中 order.getItems().add(oi); } //1.5设置用户 order.setUser(user); //调用service,完成对订单的添加 OrderService os = (OrderService) BeanFactory.getBean("OrderService"); os.add(order); //将order对象放入request域 request.setAttribute("order", order); //将以前的购物车中的东西,即将以前的从购物车清除了 request.getSession().removeAttribute("cart"); //请求转发到订单详情页面 return "/jsp/order_info.jsp"; } } service层 public interface OrderService { void add(Order order) throws Exception; } public class OrderServiceImpl implements OrderService { /** * 将订单数据添加到数据库中 * @throws Exception */ @Override public void add(Order order) throws Exception{ try { //1对者两个添加要加入事务 DataSourceUtils.startTransaction(); //2在order添加一条数据 OrderDao od = (OrderDao) BeanFactory.getBean("OrderDao"); od.add2Order(order); //在orderitem中添加n条数据 for (OrderItem oi : order.getItems()) { od.add2OrderItem(oi); } //提交事务 DataSourceUtils.commitAndClose(); } catch (Exception e) { e.printStackTrace(); //事务回滚 DataSourceUtils.rollbackAndClose(); throw e; } } } dao层 public interface OrderDao { void add2Order(Order order) throws Exception; void add2OrderItem(OrderItem oi) throws Exception; } public class OrderDaoImpl implements OrderDao{ /** * 添加一条订单 */ @Override public void add2Order(Order order) throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "insert into order values(?, ?, ?, ?, ?, ?, ?, ?)"; qr.update(DataSourceUtils.getConnection(), sql, order.getOid(), order.getOrderTime(), order.getTotal(), order.getState(), order.getAddress(), order.getName(), order.getPhone(), order.getUser().getUid()); } /** * 添加一条订单项 */ @Override public void add2OrderItem(OrderItem oi) throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "insert into orderitem values(?, ?, ?, ?, ?)"; qr.update(DataSourceUtils.getConnection(),sql, oi.getItemid(), oi.getCount(), oi.getSubTotal(), oi.getProduct().getPid(), oi.getOrder().getOid()); } } 出错后jsp页面显示不出,所报异常 java.lang.NullPointerException at com.mysql.jdbc.ResultSetMetaData.getField(ResultSetMetaData.java:397) at com.mysql.jdbc.ResultSetMetaData.getColumnType(ResultSetMetaData.java:275) at com.mysql.jdbc.MysqlParameterMetadata.getParameterType(MysqlParameterMetadata.java:80) at org.apache.commons.dbutils.AbstractQueryRunner.fillStatement(AbstractQueryRunner.java:197) at org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:485) at org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:402) at com.local.dao.OrderDaoImpl.add2Order(OrderDaoImpl.java:19) at com.local.service.OrderServiceImpl.add(OrderServiceImpl.java:28) at com.local.web.servlet.OrderServlet.add(OrderServlet.java:82) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.local.web.servlet.BaseServlet.service(BaseServlet.java:36) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at com.local.web.filter.EncodingFilter.doFilter(EncodingFilter.java:36) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.local.web.servlet.BaseServlet.service(BaseServlet.java:36) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at com.local.web.filter.EncodingFilter.doFilter(EncodingFilter.java:36) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.NullPointerException at com.mysql.jdbc.ResultSetMetaData.getField(ResultSetMetaData.java:397) at com.mysql.jdbc.ResultSetMetaData.getColumnType(ResultSetMetaData.java:275) at com.mysql.jdbc.MysqlParameterMetadata.getParameterType(MysqlParameterMetadata.java:80) at org.apache.commons.dbutils.AbstractQueryRunner.fillStatement(AbstractQueryRunner.java:197) at org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:485) at org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:402) at com.local.dao.OrderDaoImpl.add2Order(OrderDaoImpl.java:19) at com.local.service.OrderServiceImpl.add(OrderServiceImpl.java:28) at com.local.web.servlet.OrderServlet.add(OrderServlet.java:82) ... 28 more 七月 08, 2017 12:01:24 下午 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet [OrderServlet] in context with path [/store] threw exception java.lang.RuntimeException at com.local.web.servlet.BaseServlet.service(BaseServlet.java:44) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at com.local.web.filter.EncodingFilter.doFilter(EncodingFilter.java:36) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) com.local.web.servlet.OrderServlet@8bc0b9 add 我用debug方式看了看了下order在dao用dbutils插入时的数据,数据是封装进去的,就name,address,phone,三项没有封装。并已经接图。以前在mysql中插入数据页是可以插入空数值的, 为何会报NullPointerException,困扰了好些时候了,各位大神有时间的话帮着看一下呀!
关于jdbc多表操作事务的一些疑问,怎么去控制事务
现在回归原始做jdbc的程序。主要功能是实现一个sql脚本管理功能(版本控制)一共3张表 <br />表一: sripit_info&nbsp; (主要存脚本的描述性信息,和最新的版本号和内容ID) <br />主要字段说明: id(主键),creator,createTime,version(最新版本号),content_id(最新版本对应的内容id) <br />表二:script_content(维护版本和脚本内容) <br />主要字段:id(主键),script_id(外键,表示属于哪个脚本),version(版本号),content(sql代码内容,是个 blob大字段) <br />表三:script_sqls (把不同版本的脚本内容拆分成单条sql放在这张表中) <br />主要字段:id(主键),text(一条sql文),content_id(外键,表示这条sql所对应的版本的内容id) <br />另外就是建个seq_script(orcale 的 sequence) <br /> <br />我想的设计流程是(假设是一个新增操作): <br />1、取得一个sequence,并另保存为sripit_id <br />2、插入 sripit_info 表 <br />3、取得一个sequence,并另保存为content_id <br />4、插入 script_content 表,其中的外键可以用之前的sripit_id得到 <br />5、批处理插入 script_sqls 表(把脚本的sql文拆分为单条sql语句,外键可以从content_id得到) <br />6、更新版本,把 content_id 和version信息 更新到sripit_info 表 <br />7、完成 <br /> <br />我现在的问题是,以上的每一步都是一个事务,但是业务上后面的事务都要依赖与之前的事务完成才能进行。 <br />我不知道jdbc怎么去控制业务上的事务, 我已经设置了connection的autocommit为false.然后以上涉及insert的操作都是成功commit,失败rollback的。但是如何把整个业务设计成一个事务,就是以上7步只要有一步不成功,全部都rollback ,怎么做? <br />例如 我步骤2(插入 sripit_info 表)成功了,数据库确实是commit进去了,能查到了。但是后面的步骤4(插入 script_content 表)出错了,被rollback,没有提交到数据库,但我希望此时之前的操作也能都rollback。要怎么设计呢? <br /> <br />刚刚换单位,居然这边都不用spring和hibernate。全部是jdbc,小弟对jdbc的事务不是很清楚,请大家帮我解惑,谢谢 <br /> <br /><br/><strong>问题补充</strong><br/>我暂时吧所以业务写在一个事务里面了
ssh中spring的配置加上事务配置后就出错,恳请大家帮忙
出错信息: 2011-3-27 20:15:08 org.apache.catalina.core.AprLifecycleListener lifecycleEvent 信息: The Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: D:\Program Files\java\bin;D:\Program Files\Tomcat 5.5\bin 2011-3-27 20:15:08 org.apache.coyote.http11.Http11BaseProtocol init 信息: Initializing Coyote HTTP/1.1 on http-1688 2011-3-27 20:15:08 org.apache.catalina.startup.Catalina load 信息: Initialization processed in 406 ms 2011-3-27 20:15:08 org.apache.catalina.core.StandardService start 信息: Starting service Catalina 2011-3-27 20:15:08 org.apache.catalina.core.StandardEngine start 信息: Starting Servlet Engine: Apache Tomcat/5.5.16 2011-3-27 20:15:08 org.apache.catalina.core.StandardHost start 信息: XML validation disabled 2011-03-27 20:15:09,062 INFO [org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/SSHExt]] - Initializing Spring root WebApplicationContext 2011-03-27 20:15:09,062 INFO [org.springframework.web.context.ContextLoader] - Root WebApplicationContext: initialization started 2011-03-27 20:15:09,203 INFO [org.springframework.web.context.support.XmlWebApplicationContext] - Refreshing Root WebApplicationContext: startup date [Sun Mar 27 20:15:09 CST 2011]; root of context hierarchy 2011-03-27 20:15:09,359 INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml] 2011-03-27 20:15:09,593 ERROR [org.springframework.web.context.ContextLoader] - Context initialization failed org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:412) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:93) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3729) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4183) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:759) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:739) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:524) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:904) at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:867) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:474) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1112) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:310) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1021) at org.apache.catalina.core.StandardHost.start(StandardHost.java:718) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:442) at org.apache.catalina.core.StandardService.start(StandardService.java:450) at org.apache.catalina.core.StandardServer.start(StandardServer.java:709) at org.apache.catalina.startup.Catalina.start(Catalina.java:551) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:275) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) Caused by: java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1812) at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:866) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1319) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1198) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) at org.springframework.transaction.config.TxAdviceBeanDefinitionParser.getBeanClass(TxAdviceBeanDefinitionParser.java:69) at org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser.parseInternal(AbstractSingleBeanDefinitionParser.java:66) at org.springframework.beans.factory.xml.AbstractBeanDefinitionParser.parse(AbstractBeanDefinitionParser.java:59) at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1335) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1325) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:135) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:93) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390) ... 37 more 2011-03-27 20:15:09,593 ERROR [org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/SSHExt]] - Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:412) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:93) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3729) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4183) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:759) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:739) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:524) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:904) at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:867) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:474) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1112) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:310) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1021) at org.apache.catalina.core.StandardHost.start(StandardHost.java:718) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:442) at org.apache.catalina.core.StandardService.start(StandardService.java:450) at org.apache.catalina.core.StandardServer.start(StandardServer.java:709) at org.apache.catalina.startup.Catalina.start(Catalina.java:551) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:275) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) Caused by: java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1812) at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:866) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1319) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1198) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) at org.springframework.transaction.config.TxAdviceBeanDefinitionParser.getBeanClass(TxAdviceBeanDefinitionParser.java:69) at org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser.parseInternal(AbstractSingleBeanDefinitionParser.java:66) at org.springframework.beans.factory.xml.AbstractBeanDefinitionParser.parse(AbstractBeanDefinitionParser.java:59) at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1335) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1325) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:135) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:93) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390) ... 37 more 2011-3-27 20:15:09 org.apache.catalina.core.StandardContext start 严重: Error listenerStart 2011-3-27 20:15:09 org.apache.catalina.core.StandardContext start 严重: Context [/SSHExt] startup failed due to previous errors 2011-03-27 20:15:09,593 INFO [org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/SSHExt]] - Closing Spring root WebApplicationContext 2011-3-27 20:15:09 org.apache.coyote.http11.Http11BaseProtocol start 信息: Starting Coyote HTTP/1.1 on http-1688 2011-3-27 20:15:09 org.apache.jk.common.ChannelSocket init 信息: JK: ajp13 listening on /0.0.0.0:8009 2011-3-27 20:15:09 org.apache.jk.server.JkMain start 信息: Jk running ID=0 time=0/47 config=null 2011-3-27 20:15:09 org.apache.catalina.storeconfig.StoreLoader load 信息: Find registry server-registry.xml at classpath resource 2011-3-27 20:15:09 org.apache.catalina.startup.Catalina start 信息: Server startup in 1703 ms spring的配置信息如下: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> <!-- 配置数据库连接池 --> <!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName"> <value>oracle.jdbc.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:orcl</value> </property> <property name="password"> <value>orcl</value> </property> <property name="username"> <value>yhj</value> </property> </bean> <property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property> <property name="connection.url">jdbc:jtds:sqlserver://127.0.0.1:1433;DatabaseName=hibernate</property> --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName"> <value>net.sourceforge.jtds.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:jtds:sqlserver://127.0.0.1:1433;databaseName=sshtest</value> </property> <property name="password"> <value>sa</value> </property> <property name="username"> <value>sa</value> </property> </bean> <!-- <property name="connection.url"> jdbc:sqlserver://127.0.0.1:1433;databaseName=HTSiteSrv </property> <property name="connection.username">sa</property> <property name="connection.password">sa</property> <property name="connection.driver_class"> com.microsoft.sqlserver.jdbc.SQLServerDriver </property> --> <!-- 配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref local="dataSource"/> </property> <property name="mappingResources"> <list> <value>UserTab.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <!-- <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>--> <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <!--AOP的事务管理 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!--传播特性 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="get*" read-only="true" /> <tx:method name="search*" read-only="true" /> </tx:attributes> </tx:advice> <!--配置事务管理器应用的范围 --> <aop:config> <aop:pointcut id="userServiceMethods" expression="execution(*com.ssh.test.dao.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="userServiceMethods" /> </aop:config> <!-- dao配置 --> <bean id="userDao" class="com.ssh.test.dao.UserDao" scope="prototype"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <!-- 业务层配置 --> <bean id="userManageBusiness" class="com.ssh.test.business.UserManageBusiness" scope="prototype"> <property name="userDao"> <ref bean="userDao" /> </property> </bean> <!-- action配置 --> <bean id="loginAction" class="com.ssh.test.action.LoginAction" scope="prototype"> </bean> <bean id="userManageAction" class="com.ssh.test.action.UserManageAction" scope="prototype"> <property name="userManageBusiness"> <ref bean="userManageBusiness" /> </property> </bean> <bean id="deptManageAction" class="com.ssh.test.action.DeptManageAction" scope="prototype"> </bean> </beans> 去掉事务的配置就好,但是加上了就错,大家给力啊
请教一下,到底我的mapper.xml哪里出错了,弄不明白为什么找不到我写的log类
## update一下经大佬提点后如何解决的 可能因为我曾用粗暴的方法改动过Log.java的类名,导致Log类编译出问题了,编译后类文件夹内根本没有Log.class文件。于是我又粗暴地delete了Log类重写了一次,果然没问题了。 顺便百度了一下如何修改类名 https://zhidao.baidu.com/question/340215163.html ## 原问题如下 小白入门程序媛,这个是一个mybatis的关于银行转账的小练习 在写log部分之前,我写的account部分测试过是没有问题的,转账的业务也成功了的。现在是想增加一个记录日志的操作,在数据库log表格添加转账记录,并且利用log4j在硬盘生成log file中记录转账信息。 可是按照同样的套路写了了log实体类后再写logmapper.xml,却出现了以下的错误,后来干脆连mybatis中的别名的部分都去掉了,直接在mapper.xml中使用完整的类名,还是说找不到我写的log类。实在搞不懂是namespace出错了还是怎么滴。。。。 ## 错误信息如下: ``` 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Server version: Apache Tomcat/8.5.42 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Server built: Jun 4 2019 20:29:04 UTC 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Server number: 8.5.42.0 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: OS Name: Windows 10 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: OS Version: 10.0 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Architecture: amd64 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Java Home: C:\Program Files\Java\jdk1.8.0_201\jre 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: JVM Version: 1.8.0_201-b09 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: JVM Vendor: Oracle Corporation 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: CATALINA_BASE: D:\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: CATALINA_HOME: D:\apache-tomcat-8.5.42 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Command line argument: -Dcatalina.base=D:\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Command line argument: -Dcatalina.home=D:\apache-tomcat-8.5.42 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Command line argument: -Dwtp.deploy=D:\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Command line argument: -Djava.endorsed.dirs=D:\apache-tomcat-8.5.42\endorsed 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Command line argument: -Dfile.encoding=UTF-8 七月 13, 2019 8:47:00 下午 org.apache.catalina.core.AprLifecycleListener lifecycleEvent 信息: Loaded APR based Apache Tomcat Native library [1.2.21] using APR version [1.6.5]. 七月 13, 2019 8:47:00 下午 org.apache.catalina.core.AprLifecycleListener lifecycleEvent 信息: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true]. 七月 13, 2019 8:47:00 下午 org.apache.catalina.core.AprLifecycleListener lifecycleEvent 信息: APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true] 七月 13, 2019 8:47:00 下午 org.apache.catalina.core.AprLifecycleListener initializeSSL 信息: OpenSSL successfully initialized [OpenSSL 1.1.1a 20 Nov 2018] 七月 13, 2019 8:47:00 下午 org.apache.coyote.AbstractProtocol init 信息: Initializing ProtocolHandler ["http-nio-8080"] 七月 13, 2019 8:47:00 下午 org.apache.tomcat.util.net.NioSelectorPool getSharedSelector 信息: Using a shared selector for servlet write/read 七月 13, 2019 8:47:00 下午 org.apache.coyote.AbstractProtocol init 信息: Initializing ProtocolHandler ["ajp-nio-8009"] 七月 13, 2019 8:47:00 下午 org.apache.tomcat.util.net.NioSelectorPool getSharedSelector 信息: Using a shared selector for servlet write/read 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.Catalina load 信息: Initialization processed in 828 ms 七月 13, 2019 8:47:00 下午 org.apache.catalina.core.StandardService startInternal 信息: Starting service [Catalina] 七月 13, 2019 8:47:00 下午 org.apache.catalina.core.StandardEngine startInternal 信息: Starting Servlet Engine: Apache Tomcat/8.5.42 七月 13, 2019 8:47:01 下午 org.apache.jasper.servlet.TldScanner scanJars 信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. 七月 13, 2019 8:47:02 下午 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler ["http-nio-8080"] 七月 13, 2019 8:47:02 下午 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler ["ajp-nio-8009"] 七月 13, 2019 8:47:02 下午 org.apache.catalina.startup.Catalina start 信息: Server startup in 1377 ms 七月 13, 2019 8:47:32 下午 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet [yan.ibbie.servlet.TransferServlet] in context with path [/bank] threw exception org.apache.ibatis.exceptions.PersistenceException: ### Error building SqlSession. ### The error may exist in yan/ibbie/mapper/logmapper.xml ### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'yan/ibbie/mapper/logmapper.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'yan.ibbie.pojo.Log'. Cause: java.lang.ClassNotFoundException: Cannot find class: yan.ibbie.pojo.Log at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:80) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:64) at yan.ibbie.service.Impl.AccountServiceImpl.transfer(AccountServiceImpl.java:23) at yan.ibbie.servlet.TransferServlet.service(TransferServlet.java:36) at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:660) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:808) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'yan/ibbie/mapper/logmapper.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'yan.ibbie.pojo.Log'. Cause: java.lang.ClassNotFoundException: Cannot find class: yan.ibbie.pojo.Log at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:121) at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:99) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:78) ... 26 more Caused by: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'yan/ibbie/mapper/logmapper.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'yan.ibbie.pojo.Log'. Cause: java.lang.ClassNotFoundException: Cannot find class: yan.ibbie.pojo.Log at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:120) at org.apache.ibatis.builder.xml.XMLMapperBuilder.parse(XMLMapperBuilder.java:92) at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:373) at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:119) ... 28 more Caused by: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'yan.ibbie.pojo.Log'. Cause: java.lang.ClassNotFoundException: Cannot find class: yan.ibbie.pojo.Log at org.apache.ibatis.builder.BaseBuilder.resolveClass(BaseBuilder.java:118) at org.apache.ibatis.builder.xml.XMLStatementBuilder.parseStatementNode(XMLStatementBuilder.java:68) at org.apache.ibatis.builder.xml.XMLMapperBuilder.buildStatementFromContext(XMLMapperBuilder.java:135) at org.apache.ibatis.builder.xml.XMLMapperBuilder.buildStatementFromContext(XMLMapperBuilder.java:128) at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:118) ... 31 more Caused by: org.apache.ibatis.type.TypeException: Could not resolve type alias 'yan.ibbie.pojo.Log'. Cause: java.lang.ClassNotFoundException: Cannot find class: yan.ibbie.pojo.Log at org.apache.ibatis.type.TypeAliasRegistry.resolveAlias(TypeAliasRegistry.java:120) at org.apache.ibatis.builder.BaseBuilder.resolveAlias(BaseBuilder.java:149) at org.apache.ibatis.builder.BaseBuilder.resolveClass(BaseBuilder.java:116) ... 35 more Caused by: java.lang.ClassNotFoundException: Cannot find class: yan.ibbie.pojo.Log at org.apache.ibatis.io.ClassLoaderWrapper.classForName(ClassLoaderWrapper.java:200) at org.apache.ibatis.io.ClassLoaderWrapper.classForName(ClassLoaderWrapper.java:89) at org.apache.ibatis.io.Resources.classForName(Resources.java:261) at org.apache.ibatis.type.TypeAliasRegistry.resolveAlias(TypeAliasRegistry.java:116) ... 37 more ``` ## mybatis.xml如下: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <!-- default填默认使用的environment的id --> <environments default="default"> <!-- environment标签声明一个环境 --> <environment id="default"> <!-- type="JDBC"表示使用原生JDBC事务 --> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=GMT%2B8"/> <property name="username" value="root"/> <property name="password" value="1233210"/> </dataSource> </environment> </environments> <mappers> <mapper resource="yan/ibbie/mapper/accountmapper.xml"/> <mapper resource="yan/ibbie/mapper/logmapper.xml"/> </mappers> </configuration> ``` ## accountmapper.xml如下: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="yan.ibbie.mapper.accountmapper"> <!-- 根据账号和密码查询账户信息 --> <select id="selByAccnoPassword" resultType="yan.ibbie.pojo.Account" parameterType="yan.ibbie.pojo.Account"> select * from account where accno=#{accNo} and password=#{password} </select> <!-- 根据账号和姓名查询账户信息 --> <select id="selByAccnoName" resultType="yan.ibbie.pojo.Account" parameterType="yan.ibbie.pojo.Account"> select * from account where accno=#{accNo} and name=#{name} </select> <!-- 根据账号修改账户余额 --> <update id="updBalanceByAccno" parameterType="yan.ibbie.pojo.Account"> update account set balance=balance+#{balance} where accno=#{accNo} </update> </mapper> ``` ## logmapper.xml如下: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="yan.ibbie.mapper.logmapper"> <insert id="insLog" parameterType="yan.ibbie.pojo.Log"> insert into log values(default,#{accOut},#{accIn},#{money}) </insert> </mapper> ``` ## yan.ibbie.pojo.log如下 ``` package yan.ibbie.pojo; public class Log { private int id; private String accOut; private String accIn; private double money; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAccOut() { return accOut; } public void setAccOut(String accOut) { this.accOut = accOut; } public String getAccIn() { return accIn; } public void setAccIn(String accIn) { this.accIn = accIn; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } } ``` ## AccountServiceImpl如下: ``` package yan.ibbie.service.Impl; import java.io.IOException; import java.io.InputStream; import java.util.Date; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.sun.istack.internal.logging.Logger; import yan.ibbie.pojo.Account; import yan.ibbie.pojo.Log; import yan.ibbie.service.AccountService; public class AccountServiceImpl implements AccountService { @Override public int transfer(Account accIn, Account accOut) throws IOException { InputStream is = Resources.getResourceAsStream("mybatis.xml"); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); SqlSession session = factory.openSession(); Account accOutSelect = session.selectOne("yan.ibbie.mapper.accountmapper.selByAccnoPassword",accOut); if (accOutSelect!=null) { if(accOutSelect.getBalance()>=accOut.getBalance()) { Account accInSelect = session.selectOne("yan.ibbie.mapper.accountmapper.selByAccnoName",accIn); if (accInSelect!=null) { accIn.setBalance(accOut.getBalance()); accOut.setBalance(-accOut.getBalance()); int index=session.update("yan.ibbie.mapper.accountmapper.updBalanceByAccno", accOut); index += session.update("yan.ibbie.mapper.accountmapper.updBalanceByAccno",accIn); if (index==2) { Log log = new Log(); log.setAccOut(accOut.getAccNo()); log.setAccIn(accIn.getAccNo()); log.setMoney(accIn.getBalance()); session.update("yan.ibbie.mapper.logmapper.insLog", log); Logger logger = Logger.getLogger(AccountServiceImpl.class); logger.info(log.getAccOut()+"给"+log.getAccIn()+ "在"+new Date().toLocaleString()+"转了"+log.getMoney()); session.commit(); session.close(); return SUCCESS; }else { session.rollback(); session.close(); return ERROR; } }else { return ACCOUNT_NAME_NOT_MATCH; } }else { return ACCOUNT_BALANCE_NOT_ENOUGHT; } }else { return ACCOUNT_PASSWORD_NOT_MATCH; } } } ```
C# 使用Mysql.Data 构造参数化查询,设置出参被设置为NULL报错
在C#中使用MySql.Data执行一个Insert语句,获取新增的自增主键。 使用的commandText如下: ``` INSERT T_Test_Table ( Name ) VALUES ( @Name -- Name - nvarchar(50) );SET @Id = @@IDENTITY ``` 该语句在Mysql中无论是用存储过程执行,还是直接输入参数执行,都不会报错; 在C#程序中。 设置参数化属性如下: ``` MySqlParameter mpName = new MySqlParameter("Name",MySqlDbType.Varchar,50,"Test"); mpName.Direction = ParameterDirection.Input; MySqlParameter mpId = new MySqlParameter("Id",MySqlDbType.Int32); mpId.Direction = ParameterDirection.OutPut; ``` 代码执行后报错: ``` You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL = @@IDENTITY' at line 1 ``` 这里不知道为什么: SET @Id = @@IDENTITY 中 @Id被替换为 NULL; 由于未写事务的缘故,查询数据库发现数据已新增成功。 这是什么问题?应该怎么解决?求解。 数据库结构如下: ``` SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for t_test_table -- ---------------------------- DROP TABLE IF EXISTS `t_test_table`; CREATE TABLE `t_test_table` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `Name` varchar(50) DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE=MyISAM AUTO_INCREMENT=73 DEFAULT CHARSET=utf8mb4; ``` 附完整代码: ``` public static void Test() { try { string connetStr = "data source=127.0.0.1;database=Test; uid=root;pwd=root;Allow User Variables=True;"; MySqlConnection conn = new MySqlConnection(connetStr); conn.Open(); string sql = @"INSERT T_Test_Table ( Name ) VALUES ( @Name -- Name - nvarchar(50) ); SET @Id = @@IDENTITY";//在sql语句中定义parameter,然后再给parameter赋值 MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlParameter mpName = new MySqlParameter("Name", MySqlDbType.VarChar, 50); mpName.Value = "Tests"; mpName.Direction = ParameterDirection.Input; MySqlParameter mpId = new MySqlParameter("Id", MySqlDbType.Int32); mpId.Direction = ParameterDirection.Output; cmd.Parameters.Add(mpName); cmd.Parameters.Add(mpId); int iRes = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); conn.Close(); } catch(Exception ex) { Console.WriteLine(ex.ToString()); throw new Exception("Mysql执行出错:\r\n" + ex.Message, ex); } } ```
关于Hibernate级联数据表的存储问题(多对一)
本问题来自Struts2.1权威指南一书第19章例19.4问题,是一个关于Hibernate关联数据表存储的问题。 整个例子的目标就是建立一个WEB应用,在一个input.jsp页面上输入父亲和儿子信息,点击提交按钮,将这两个持久化对象的信息写入数据库中的两个数据表中,两个数据表分别是person(代表父亲)和son(代表儿子)。他们的关系是1(person)对N(son) 我在调试这个例程的时候遇到一个问题,就是在向数据库中写入持久化对象时出现错误提示如下: [color=blue]Caused by: java.sql.SQLException: Unknown column 'person_id' in 'field list'[/color] [b][color=red]经过检查具体出问题的语句是在PersonServiceImpl.java代码中的sd.save(s, son)这句(大约第在25行,就是向数据库中写入Son对象的那句)。这里说明一下sd是Son的DAO组件,具体的PersonServiceImpl.java代码见后面。 因为如果将这句注释掉,运行程序,程序可以走通,发现person表中person_id列是可以写入的。此时只是son表中没有写入任何数据。[/color][/b] 于是我检查了Person.hbm.xml、Son.hbm.xml文件,实在没有发现什么可疑之处,现将相关配置文件可能出现问题的关键部位贴出如下: --------------------PersonServiceImpl.java代码------ [code="java"] public class PersonServiceImpl implements PersonService { public void createPersonAndSon(String name , String gender , String[] sonName , int[] sonAge)throws PersonException { try { //业务逻辑组件依赖于DAO组件,从组件工厂中取出两个DAO组件 PersonDao pd = (PersonDao)ComponentFactory.instance().getComponent("personDao"); SonDao sd = (SonDao)ComponentFactory.instance().getComponent("sonDao"); //获取Hibernate Session Session s = HibernateUtil.sf.getCurrentSession(); Transaction tx = s.beginTransaction(); //以面向对象方式开始持久化操作 Person p = new Person(); p.setName(name); p.setGender(gender); pd.save(s , p); //增加Person实体关联的Son实体 for (int i = 0 ; i < sonName.length ; i++ ) { Son son = new Son(sonName[i] , sonAge[i]); son.setParent(p); sd.save(s, son);//就是这句出错了,如果注释掉这句,程序依然可以运行,只是son对象不写入数据库而已!!! } //提交事务 tx.commit(); } catch (Exception e) { e.printStackTrace(); throw new PersonException("业务异常"); } } } [/code] ---------------------Son.hbm.xml片段---------------------------------- [code="xml"] <!-- 每个class元素映射一个持久化类 --> <class name="Son" table="son"> <id name="id" column="son_id" unsaved-value="null"> <generator class="identity"/> </id> <property name="sonName" type="string"/> <property name="sonAge" type="int"/> <!-- 映射N:1关联实体 --> <many-to-one name="parent" column="person_id" class="Person" cascade="all" not-null="true"/> </class> [/code] ---------------------Person.hbm.xml片段---------------------------------- [code="xml"] <!-- 每个class元素映射一个持久化类 --> <class name="Person" table="person"> <id name="id" column="person_id" unsaved-value="null"> <generator class="identity"/> </id> <property name="name" type="string"/> <property name="gender" type="string"/> <!-- 映射1:N关联实体 --> <set name="sons" inverse="true"> <key column="person_id"/> <one-to-many class="Son"/> </set> </class> [/code] -----------------------创建数据库及表所使用的SQL语句---------------------- [code="sql"] DROP database if exists struts2hibernate; CREATE database struts2hibernate; use struts2hibernate; CREATE TABLE person(person_id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), gender VARCHAR(50)); CREATE TABLE son(son_id INT AUTO_INCREMENT PRIMARY KEY, sonName VARCHAR(50), sonAge INT); [/code] 别的文件就是光盘中提供的,基本没有修改。目前由于已经能够登录到数据库,并且可以修改部分数据内容,因此关于数据库连接方面配置应该没有问题,但是实在是不知道问题出在哪里了。请不吝赐教!不胜感激!
学习hibernate 使用junit测试时 出错 - -
**_<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.url"> jdbc:mysql://localhost:3306/hibernate?characterEncoding=UTF-8 </property> <property name="connection.username">root</property> <property name="connection.password"></property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">true</property> <mapping resource="Student.hbm.xml"/> </session-factory> </hibernate-configuration> org.hibernate.exception.SQLGrammarException: Error calling Driver#connect 这是Student.hbm.xml <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2016-11-22 20:14:28 by Hibernate Tools 3.4.0.CR1 --> **<hibernate-mapping> <class name="hibernate.Student" table="STUDENT"> <id name="sid" type="java.lang.String"> <column name="SID" /> <generator class="assigned" /> </id> <property name="sname" type="java.lang.String"> <column name="SNAME" /> </property> <property name="gender" type="java.lang.String"> <column name="GENDER" /> </property> <property name="birthdayDate" type="java.sql.Date"> <column name="BIRTHDAYDATE" /> </property> <property name="address" type="java.lang.String"> <column name="ADDRESS" /> </property> </class> </hibernate-mapping>** 这是TestStudent package hibernate; import java.util.Date; import javax.imageio.spi.ServiceRegistry; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; public class StudentTest { private SessionFactory sessionFactory; private Session session; private Transaction transaction; private StandardServiceRegistry serviceRegistry; @Before public void init(){ Configuration config =new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(config.getProperties()); StandardServiceRegistryImpl registry = (StandardServiceRegistryImpl) builder.build(); sessionFactory = config.buildSessionFactory(registry); // serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).build(); // sessionFactory=config.buildSessionFactory(serviceRegistry);//创建会话工厂 session=sessionFactory.openSession();//打开会话 transaction=session.beginTransaction();//打开事务 } @After public void destory(){ transaction.commit();//打开事务 session.close();//关闭会话 sessionFactory.close();//关闭会话工厂 } @Test public void testSaveStudent(){ //生成学生对象 Student s=new Student(1,"李四","男",(java.sql.Date) new Date(),"北京"); session.save(s);//保存对象进入数据库 } } **_
想参考springside实现Hibernate的零配置,但提示错误:org.hibernate.hql.ast.QuerySyntaxException
想参考Springside实现Hibernate的零配置文件,写了一个简单的测试用例,查询一张表(数据库表名为TB_USER,对应的实体类名为User),但是出错如下: org.hibernate.hql.ast.QuerySyntaxException: User is not mapped [from User] 错误提示是说我的“from User”语句中“User”未建立映射。在网上查过,类似的问题一般是因为类名的大小写错误或者配置文件错误,导致类名和数据库表名没有建立映射关系,但我似乎没有这类问题。好几天了找不到原因,不知道哪里的配置有毛病,以下是相关代码 测试用例如下: [code="java"] import org.springframework.beans.factory.annotation.Autowired; import org.springside.modules.test.junit38.SpringTransactionalTestCase; import accountant.entity.User; public class DaoTest extends SpringTransactionalTestCase { @Autowired org.springside.modules.orm.hibernate.HibernateDao<User, Long> dao ; //列出所有User表记录 public void testUserList() { //试过把完整包名带上,写成“from accountant.entity.User”,还是一样的错误 dao.find("from User", null); } } [/code] User类代码如下,其中@Table(name="TB_USER")指明对应的数据库表是“TB_USER”,这张表在库中确定存在,并有两条记录 [code="java"] package accountant.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Table(name="TB_USER") public class User { String name; String id; String sex; String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } [/code] applicationContext.xml中的数据库相关配置如下,其中 “<property name="packagesToScan" value="accountant.entity.*" />”是指定自动扫描实体类的包,User类也就在“accountant.entity”这个包下 [code="java"] <!-- 数据源配置,使用应用内的DBCP数据库连接池。--> <!--这里数据库的连接应该是没问题的,因为出错时提示的是Hql执行错误,说明数据库连接已经成功建立了,不过是执行的语句有问题 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- Connection Info --> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- Connection Pooling DBCP --> <property name="initialSize" value="5" /> <property name="maxActive" value="100" /> <property name="maxIdle" value="30" /> <property name="maxWait" value="1000" /> <property name="poolPreparedStatements" value="true" /> <property name="defaultAutoCommit" value="false" /> </bean> <!-- Hibernate配置--> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="namingStrategy"> <bean class="org.hibernate.cfg.ImprovedNamingStrategy" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9iDialect</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider </prop> </props> </property> <property name="packagesToScan" value="accountant.entity.*" /> </bean> <!-- Dao类 --> <bean id="hibernateDao" class="org.springside.modules.orm.hibernate.HibernateDao"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> [/code] 相关的代码就是以上三处,不知道哪里有遗漏或是错误,请指点一二,非常感谢! [b]问题补充:[/b] [code="java"][/code] 先谢谢二位,我的spring和hibernate的jar版本如下: [img]/upload/attachment/124016/5a67b24b-27e0-348a-ab6f-5d7003972509.gif[/img] [img]/upload/attachment/124018/751e247e-4c6c-341f-9859-4a52863af90d.gif[/img] 这个小例子是在springside的mini-web范例上直接改的,应该环境方面不会有大问题吧 to layer555: springside的mini-web的applicationContext.xml是这样的: [code="java"] <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" default-lazy-init="true"> <description>Spring公共配置文件 </description> <!-- 定义受环境影响易变的变量 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> <property name="ignoreResourceNotFound" value="true" /> <property name="locations"> <list> <!-- 标准配置 --> <value>classpath*:/application.properties</value> <!-- 本地开发环境配置 --> <value>classpath*:/application.local.properties</value> <!-- 服务器生产环境配置 --> <!-- <value>file:/var/myapp/application.server.properties</value> --> </list> </property> </bean> <!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 --> <context:component-scan base-package="org.springside.examples.miniweb" /> <!-- 数据源配置,使用应用内的DBCP数据库连接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- Connection Info --> <property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- Connection Pooling DBCP --> <property name="initialSize" value="5" /> <property name="maxActive" value="100" /> <property name="maxIdle" value="30" /> <property name="maxWait" value="1000" /> <property name="poolPreparedStatements" value="true" /> <property name="defaultAutoCommit" value="false" /> </bean> <!-- 数据源配置,使用应用服务器的数据库连接池 --> <!--<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/ExampleDB" />--> <!-- Hibernate配置 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="namingStrategy"> <bean class="org.hibernate.cfg.ImprovedNamingStrategy" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider </prop> <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.ehcache_config_file}</prop> </props> </property> <property name="packagesToScan" value="org.springside.examples.miniweb.entity.*" /> </bean> <!-- 事务管理器配置,单数据源事务 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 事务管理器配置,多数据源JTA事务--> <!-- <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager or WebLogicJtaTransactionManager" /> --> <!-- 使用annotation定义事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans> [/code] 这里面也没有configurationClass,也能正常,不知道在什么地方设置或默认了 to xuzhfa123: 改了你说的两处,确实可以跑通了,非常感谢。但搞不明白的是,在上面贴的mini-web的配置文件中是这么写的: [code="java"]<property name="packagesToScan" value="org.springside.examples.miniweb.entity.*" /> [/code] 这个例子是可以正常运行的,为什么我就必须改成 [code="java"] <property name="packagesToScan" value="accountant.entity" /> [/code] 才可以呢?
hibernate初识框架搭建,一直报错
![图片说明](https://img-ask.csdn.net/upload/201906/02/1559489729_923786.png) 具体代码就是以下三个主要配置文件,求大佬瞄一眼哪里出错了。 错误提示只有上面几句话 Mytest.java ``` package com.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.Test; public class Mytest { @Test public void demo() { try { Configuration cfg = new Configuration().configure(); System.out.println("t1"); SessionFactory sessionFactory= cfg.buildSessionFactory(); // 根据配置生成Session工厂 System.out.println("t2"); Session session = sessionFactory.openSession(); // 打开一个新的Session Transaction tx = session.beginTransaction(); // 开启事务 User user=new User(); user.setid(2); user.setName("王一一"); session.save(user); tx.commit();//提交事务 session.close();//资源释放 } catch(Exception e) {System.out.println("t3");} } } ``` User.hbm.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.hibernate"> <class name="User" table="stu"> <id name="id" type="int" column="id"> <generator class="native"/> </id> <!-- 其他属性映射 --> <property name="name" type="string" column="name" /> </class> </hibernate-mapping> ``` hibernate.cfg.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory name="myConfig"> <!-- 1.方言(连接的数据库类型) --> <property name="dialect">org.hibernate.dialect.SQLServerDialect</property> <!-- 2. 配置数据库信息 --> <property name="connection.url">jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=666</property> <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver"</property> <property name="connection.username">sa</property> <property name="connection.password">123</property> <!-- 3. 其他配置--> <!-- 显示生成的SQL语句 以日志的形式跟踪数据sql语句 --> <property name="hibernate.show_sql">true</property> <!-- 格式化 --> <property name="hibernate.format_sql">true</property> <!-- 4. 导入映射文件 --> <mapping resource="com/hibernate/User.hbm.xml" /> </session-factory> </hibernate-configuration> ```
getHibernateTemplate()为NUll,困扰好几天了,网上也找了好些方法一直解决不掉
小弟刚刚开始学SSH,是用的Struts2+Hibernate+Spring,运行的时候发现getHibernateTemplate()得到的模板类始终是nUll值,郁闷好几天了,一直在我网上试各种方法,迄今任为解决,恳请各位指教咯! [size=large][b]applicationContext.xml:([/b]事务处理这儿没贴出来)[/size] [code="java"] <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <!-- 定义数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/jjufriend"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <!-- 定义Hibernate的sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <!-- Hibernate 的sessionFactory的属性 --> <property name="hibernateProperties"> <props> <!-- 数据库方言 --> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <!-- 显示Hibernate持久化操作所生成的SQL语句 --> <prop key="hibernate.show_sql">true</prop> <!-- 将SQL脚本进行格式化后再输出 --> <prop key="hibernate.format_sql">true</prop> </props> </property> <!-- 列出全部的映射文件 --> <property name="mappingResources"> <list> <value>com/jjufriend/student/model/Student.hbm.xml</value></list> </property></bean> <!-- 配置dao组件 --> <bean id="studentDao" class="com.jjufriend.student.dao.impl.StudentDaoHibernate"> <!-- 依赖注入DAO组件所必需的SessionFactory引用 --> <property name="sessionFactory" ref="sessionFactory"> </property> </bean> <!-- 配置业务逻辑组件 --> <bean id="mgr" class="com.jjufriend.student.service.impl.StudentManagerImpl"> <property name="studentDao" ref="studentDao"></property> </bean> [/code] [size=large]studentDao.java:[/size] [code="java"]package com.jjufriend.student.dao; import java.util.List; import com.jjufriend.student.model.Student; public interface StudentDao { Student get(Integer id); Integer save(Student student); void update(Student student); void delete(Student student); void delete(Integer id); List<Student> findAll(); Student findStudentByNameAndPass(String username,String password); Student findByName(String username); }[/code] [size=large]StudentDaoHibernate.java:[/size] [code="java"]package com.jjufriend.student.dao.impl; import java.io.Serializable; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.jjufriend.student.dao.StudentDao; import com.jjufriend.student.model.Student; public class StudentDaoHibernate extends HibernateDaoSupport implements StudentDao,Serializable { private SessionFactory sessionFactory; HibernateTemplate ht = this.getHibernateTemplate() ; public void delete(Student student) { // TODO Auto-generated method stub getHibernateTemplate().delete(student); } public void delete(Integer id) { // TODO Auto-generated method stub getHibernateTemplate().delete(get(id)); } public List<Student> findAll() { // TODO Auto-generated method stub return (List<Student>)getHibernateTemplate().find("from Student"); } public Student findByName(String username) { List stu = getHibernateTemplate().find("from Student st where st.username = ?",username); if(stu != null && stu.size() >= 1){ return (Student)stu.get(0); } return null; } public Student findStudentByNameAndPass(String username, String password) { // TODO Auto-generated method stub List students = null; try{ // HibernateTemplate temple = this.getHibernateTemplate(); System.out.println("模板类是否为NULL>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+ht); // 取出所有 students = temple.find("from student"); students = ht.find("from student st where st.username = " + username + " and st.password = " + password); }catch(Exception e){ System.out.println("查找过程中出现异常.............."); e.printStackTrace(); } if(students != null && students.size() >= 1){ return (Student)students.get(0); } return null; } public Student get(Integer id) { return (Student)getHibernateTemplate().get(Student.class, id); } public Integer save(Student student) { return (Integer)getHibernateTemplate().save(student); } public void update(Student student) { // TODO Auto-generated method stub getHibernateTemplate().update(student); } } [/code] [size=large]StudentManager.java:[/size] [code="java"]package com.jjufriend.student.service; import com.jjufriend.student.model.Student; public interface StudentManager { int addStudent(Student student) throws Exception; int loginValid(Student student) throws Exception; boolean validateName(String username) throws Exception; } [/code] [size=large]StudentManagerImpl.java:[/size] [code="java"]package com.jjufriend.student.service.impl; import com.jjufriend.student.dao.StudentDao; import com.jjufriend.student.dao.impl.StudentDaoHibernate; import com.jjufriend.student.model.Student; import com.jjufriend.student.service.StudentManager; public class StudentManagerImpl implements StudentManager { /*2009-11-12 22:44修改 出去new StudentDaoHibernate() */ private StudentDao studentDao = new StudentDaoHibernate() ; // private ApplicationContext cxt = // new FileSystemXmlApplicationContext("../webapps/JJUFriend/WEB-INF/applicationContext.xml"); // studentDao =(StudentDaoHibernate)cxt.getBean("studentDao"); public void setStudentDao(StudentDao studentDao){ this.studentDao = studentDao ; } public int addStudent(Student student) throws Exception { // TODO Auto-generated method stub try{ studentDao.save(student); return student.getId(); }catch(Exception e){ e.printStackTrace(); throw new Exception("新增用户时出现异常"); } } public int loginValid(Student student) throws Exception { try{ System.out.println(studentDao); System.out.println("是否取到页面提交的数据:Name="+student.getUsername()); Student stu = studentDao.findStudentByNameAndPass(student.getUsername(), student.getPassword()); if(stu != null ){ return stu.getId(); } }catch(Exception e){ System.out.println("验证用户登录时出现异常"); e.printStackTrace(); } // TODO Auto-generated method stub return -1; } public boolean validateName(String username) throws Exception { // TODO Auto-generated method stub try{ if (studentDao.findByName(username) != null){ return true ; } }catch(Exception e){ System.out.println("验证用户名是否用效时出错"); e.printStackTrace(); } return false ; } } [/code] 问题的关键是通过方法getHibernateTemplate()不能正确得到HibernateTemplate对象,始终的空值,网上有很多解决的办法,差不多我都试过了, 下面这种方法是说不能直接new StudentDao对象,用下面这种方法取得,可以启动服务器老是不停地跳动,一直不停,直到报错。 [code="java"] // private ApplicationContext cxt = // new FileSystemXmlApplicationContext("../webapps/JJUFriend/WEB-INF/applicationContext.xml"); // private StudentDao studentDao =(StudentDaoHibernate)cxt.getBean("studentDao");[/code] 还有些方法是直接从applicationContext.xml中的bean取得HibernateTemplate对象,始终都搞不定,望大家指教了。 [size=medium](顶格的System.out.println()语句均是测试用的语句)[/size] [b]问题补充:[/b] 谢谢大家的热心帮助!! 确实其中出了不少问题,主要是最近网上看到解决这个方法的帖子很多,尝试过很多方法,都有点儿改晕了。 一楼的方法我尝试了,还是不行,[code="java"] private ApplicationContext cxt = this.getApplicationContext(); private StudentDao studentDao = (StudentDaoHibernate)cxt.getBean("studentDao"); [/code] 其中那个this.getApplicationContext(); 方法根本不存在啊,无法取得配置文件。 之前类似的方法我也用过就是用[code="java"] private ApplicationContext cxt = new FileSystemXmlApplicationContext("../webapps/JJUFriend/WEB-INF/applicationContext.xml"); private StudentDao studentDao =(StudentDaoHibernate)cxt.getBean("studentDao"); [/code]取得,但是当启动服务器后,后台一直跑个不停,仿佛是个死循环似的。浏览器中通过http://localhost:8080访问都无效! StudentDaoHibernate.java中的private SessionFactory sessionFactory;已经去掉 数据库方言也该过来了
在中国程序员是青春饭吗?
今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...
我在支付宝花了1分钟,查到了女朋友的开房记录!
在大数据时代下,不管你做什么都会留下蛛丝马迹,只要学会把各种软件运用到极致,捉奸简直轻而易举。今天就来给大家分享一下,什么叫大数据抓出轨。据史料证明,马爸爸年轻时曾被...
程序员请照顾好自己,周末病魔差点一套带走我。
程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。
卸载 x 雷某度!GitHub 标星 1.5w+,从此我只用这款全能高速下载工具!
作者 | Rocky0429 来源 | Python空间 大家好,我是 Rocky0429,一个喜欢在网上收集各种资源的蒟蒻… 网上资源眼花缭乱,下载的方式也同样千奇百怪,比如 BT 下载,磁力链接,网盘资源等等等等,下个资源可真不容易,不一样的方式要用不同的下载软件,因此某比较有名的 x 雷和某度网盘成了我经常使用的工具。 作为一个没有钱的穷鬼,某度网盘几十 kb 的下载速度让我...
20道你必须要背会的微服务面试题,面试一定会被问到
写在前面: 在学习springcloud之前大家一定要先了解下,常见的面试题有那块,然后我们带着问题去学习这个微服务技术,那么就会更加理解springcloud技术。如果你已经学了springcloud,那么在准备面试的时候,一定要看看看这些面试题。 文章目录1、什么是微服务?2、微服务之间是如何通讯的?3、springcloud 与dubbo有哪些区别?4、请谈谈对SpringBoot 和S...
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试,面试官没想到一个ArrayList,我都能跟他扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
2020 年,大火的 Python 和 JavaScript 是否会被取而代之?
Python 和 JavaScript 是目前最火的两大编程语言,但是2020 年,什么编程语言将会取而代之呢? 作者 |Richard Kenneth Eng 译者 |明明如月,责编 | 郭芮 出品 | CSDN(ID:CSDNnews) 以下为译文: Python 和 JavaScript 是目前最火的两大编程语言。然而,他们不可能永远屹立不倒。最终,必将像其他编程语言一...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
最全最强!世界大学计算机专业排名总结!
我正在参与CSDN200进20,希望得到您的支持,扫码续投票5次。感谢您! (为表示感谢,您投票后私信我,我把我总结的人工智能手推笔记和思维导图发送给您,感谢!) 目录 泰晤士高等教育世界大学排名 QS 世界大学排名 US News 世界大学排名 世界大学学术排名(Academic Ranking of World Universities) 泰晤士高等教育世界大学排名 中国共...
作为一名大学生,如何在B站上快乐的学习?
B站是个宝,谁用谁知道???? 作为一名大学生,你必须掌握的一项能力就是自学能力,很多看起来很牛X的人,你可以了解下,人家私底下一定是花大量的时间自学的,你可能会说,我也想学习啊,可是嘞,该学习啥嘞,不怕告诉你,互联网时代,最不缺的就是学习资源,最宝贵的是啥? 你可能会说是时间,不,不是时间,而是你的注意力,懂了吧! 那么,你说学习资源多,我咋不知道,那今天我就告诉你一个你必须知道的学习的地方,人称...
那些年,我们信了课本里的那些鬼话
教材永远都是有错误的,从小学到大学,我们不断的学习了很多错误知识。 斑羚飞渡 在我们学习的很多小学课文里,有很多是错误文章,或者说是假课文。像《斑羚飞渡》: 随着镰刀头羊的那声吼叫,整个斑羚群迅速分成两拨,老年斑羚为一拨,年轻斑羚为一拨。 就在这时,我看见,从那拨老斑羚里走出一只公斑羚来。公斑羚朝那拨年轻斑羚示意性地咩了一声,一只半大的斑羚应声走了出来。一老一少走到伤心崖,后退了几步,突...
使用 Python 和百度语音识别生成视频字幕
文章目录从视频中提取音频根据静音对音频分段使用百度语音识别获取 Access Token使用 Raw 数据进行合成生成字幕总结 从视频中提取音频 安装 moviepy pip install moviepy 相关代码: audio_file = work_path + '\\out.wav' video = VideoFileClip(video_file) video.audio.write_...
一个程序在计算机中是如何运行的?超级干货!!!
强烈声明:本文很干,请自备茶水!???? 开门见山,咱不说废话! 你有没有想过,你写的程序,是如何在计算机中运行的吗?比如我们搞Java的,肯定写过这段代码 public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } ...
【蘑菇街技术部年会】程序员与女神共舞,鼻血再次没止住。(文末内推)
蘑菇街技术部的年会,别开生面,一样全是美女。
那个在阿里养猪的工程师,5年了……
简介: 在阿里,走过1825天,没有趴下,依旧斗志满满,被称为“五年陈”。他们会被授予一枚戒指,过程就叫做“授戒仪式”。今天,咱们听听阿里的那些“五年陈”们的故事。 下一个五年,猪圈见! 我就是那个在养猪场里敲代码的工程师,一年多前我和20位工程师去了四川的猪场,出发前总架构师慷慨激昂的说:同学们,中国的养猪产业将因为我们而改变。但到了猪场,发现根本不是那么回事:要个WIFI,没有;...
为什么程序猿都不愿意去外包?
分享外包的组织架构,盈利模式,亲身经历,以及根据一些外包朋友的反馈,写了这篇文章 ,希望对正在找工作的老铁有所帮助
Java校招入职华为,半年后我跑路了
何来 我,一个双非本科弟弟,有幸在 19 届的秋招中得到前东家华为(以下简称 hw)的赏识,当时秋招签订就业协议,说是入了某 java bg,之后一系列组织架构调整原因等等让人无法理解的神操作,最终毕业前夕,被通知调往其他 bg 做嵌入式开发(纯 C 语言)。 由于已至于校招末尾,之前拿到的其他 offer 又无法再收回,一时感到无力回天,只得默默接受。 毕业后,直接入职开始了嵌入式苦旅,由于从未...
世界上有哪些代码量很少,但很牛逼很经典的算法或项目案例?
点击上方蓝字设为星标下面开始今天的学习~今天分享四个代码量很少,但很牛逼很经典的算法或项目案例。1、no code 项目地址:https://github.com/kelseyhight...
立即提问