亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術(shù)文章
文章詳情頁

java.lang.ClassCastException:com.sun.proxy。$Proxy0無法轉(zhuǎn)換為org.andrea.myexample.myDeclarativeTransaction

瀏覽:105日期:2024-04-18 15:38:22
如何解決java.lang.ClassCastException:com.sun.proxy。$Proxy0無法轉(zhuǎn)換為org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate?

選項(xiàng)1,更改您的配置以在接口級別注入事務(wù):

<aop:config> <aop:pointcut expression='execution(* org.andrea.myexample.myDeclarativeTransactionspring.StudentDAO.create(..))' /> <aop:advisor advice-ref='txAdvice' pointcut-ref='createOperation' /></aop:config>

并獲取該bean作為該接口的實(shí)例:

StudentDAO studentDao = (StudentDAO) context.getBean('studentJDBCTemplate');

選項(xiàng)2,指示代理應(yīng)使用proxy-target-class屬性擴(kuò)展目標(biāo)類:

<aop:config proxy-target-class='true'> ...</aop:config>

第一個選擇是更清潔的選擇,但是坦率地說,我更喜歡@Transactional在Spring beanXML中使用注釋而不是AOP聲明。有時很難使后者正確,如果您沒有對組件進(jìn)行特定的事務(wù)性測試,則 不一定 會 發(fā)現(xiàn)事情不正確 。

解決方法

我正在嘗試在Spring Framework應(yīng)用程序中實(shí)現(xiàn)有關(guān)聲明性事務(wù)的本教程,但不起作用,因?yàn)楫?dāng)我嘗試執(zhí)行 MainApp類以測試應(yīng)用程序行為時,我得到一個錯誤:

http://www.tutorialspoint.com/spring/declarative_management.htm

所以我只有 Student DAO 接口,我只定義了我想要的CRUD方法:

package org.andrea.myexample.myDeclarativeTransactionSpring;import java.util.List;import javax.sql.DataSource;/** Interfaccia che definisce i metodi che implementano le operazioni di CRUD * che vogliamo implementare nel nostro DAO: */public interface StudentDAO { /** * Questo metodo viene usato per inizializzare le risorse del database cioè * la connessione al database: */ public void setDataSource(DataSource ds); /** * Questo metodo serve a creare un record nella tabella Student e nella * tabella Marks: */ public void create(String name,Integer age,Integer marks,Integer year); /** * Questo metodo serve ad elencare tutti i record all’interno della tabella * Studend e della tabella Marks */ public List<StudentMarks> listStudents();}

然后,我有一個 學(xué)生標(biāo)記 類,代表我的 實(shí)體 要保留在數(shù)據(jù)庫的2表上:

package org.andrea.myexample.myDeclarativeTransactionSpring;// Rappresenta l’entity:public class StudentMarks { // Proprietà: private Integer age; private String name; private Integer id; private Integer marks; private Integer year; private Integer sid; // Metodi Getter & Setter: public void setAge(Integer age) {this.age = age; } public Integer getAge() {return age; } public void setName(String name) {this.name = name; } public String getName() {return name; } public void setId(Integer id) {this.id = id; } public Integer getId() {return id; } public void setMarks(Integer marks) {this.marks = marks; } public Integer getMarks() {return marks; } public void setYear(Integer year) {this.year = year; } public Integer getYear() {return year; } public void setSid(Integer sid) {this.sid = sid; } public Integer getSid() {return sid; }}

然后,我有類 StudentMarksMapper 實(shí)現(xiàn) 的RowMapper 接口:

package org.andrea.myexample.myDeclarativeTransactionSpring;import java.sql.ResultSet;import java.sql.SQLException;import org.springframework.jdbc.core.RowMapper;/** Classe che implementa l’interfaccia RowMapper. Si tratta di un’interfaccia * usata da JdbcTemplate per mappare le righe di un ResultSet (oggetto che * contiene l’insieme delle righe restituite da una query SQL) riga per riga. * Le implementazioni di questa interfaccia mappano ogni riga su di un oggetto * risultante senza doversi preoccupare della gestione delle eccezioni poichè * le SQLException saranno catturate e gestite dalla chiamata a JdbcTemplate. */public class StudentMarksMapper implements RowMapper<StudentMarks> { /** Implementazione del metodo dell’interfaccia RowMapper che mappa una * specifica riga della tabella su di un oggetto Student * * @param Un oggetto ResultSet contenente l’insieme di tutte le righe * restituite dalla query * * @param L’indice che indentifica una specifica riga * * @return Un nuovo oggetto Student rappresentante la riga selezionata * all’interno dell’oggetto ResultSet * * @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet,int) */ public StudentMarks mapRow(ResultSet rs,int rowNum) throws SQLException {StudentMarks studentMarks = new StudentMarks();studentMarks.setId(rs.getInt('id'));studentMarks.setName(rs.getString('name'));studentMarks.setAge(rs.getInt('age'));studentMarks.setSid(rs.getInt('sid'));studentMarks.setMarks(rs.getInt('marks'));studentMarks.setYear(rs.getInt('year'));return studentMarks; }}

在它旁邊的是 StudentDAO 接口的 StudentJDBCTemplate 類:

package org.andrea.myexample.myDeclarativeTransactionSpring;import java.util.List;import javax.sql.DataSource;import org.springframework.dao.DataAccessException;import org.springframework.jdbc.core.JdbcTemplate;/** * Classe che fornisce l’implementazione per il nostro DAO le cui funzionalità * di CRUD sono state definite tramite l’interfaccia StudentDAO */public class StudentJDBCTemplate implements StudentDAO { // Utility per l’accesso alla sorgente dati private JdbcTemplate jdbcTemplateObject; /** * Metodo Setter per l’Injection della dipendenza relativa alla sorgente * dati. Tale metodo inoltre costruisce anche l’oggetto istanza di * JdbcTemplate usato per interagire con i dati nel database. * * @param la sorgente dati */ public void setDataSource(DataSource dataSource) {this.jdbcTemplateObject = new JdbcTemplate(dataSource); } /** * Metodo relativo all’operazione di CREATE che inserisce un nuovo record * all’interno della tabella Student ed un correlato nuovo record nella * tabella Marks. */ public void create(String name,Integer year) {try { // Query che inserisce nome ed età nella tabella Student: String SQL1 = 'insert into Student (name,age) values (?,?)'; // Esegue la query passandogli anche i valori effettivi da inserire: jdbcTemplateObject.update(SQL1,name,age); // Seleziona l’ultimo studente inserito nella tabella Marks: String SQL2 = 'select max(id) from Student'; // Esegue la query e mette il risultato (l’ID) in sid: int sid = jdbcTemplateObject.queryForInt(SQL2); /** * Query che inserisce un nuovo record nella tabella Marks. Il * record rappresenta il voto per l’ultimo studente inserito nella * tabella Student: */ String SQL3 = 'insert into Marks(sid,marks,year) ' + 'values (?,?,?)'; // Esegue la query passandogli anche i valori effettivi da inserire: jdbcTemplateObject.update(SQL3,sid,year); System.out.println('Created Name = ' + name + ',Age = ' + age); // SIMULA UNA RuntimeExceptio: throw new RuntimeException('Simulazione di una condizione d’errore');} catch (DataAccessException e) { // GESTIONE DELL’ECCEZIONE System.out.println('Errore nella creazione dei record,esegue rollback'); throw e;} } /** * Metodo relativo all’operazione di READ che recupera la lista degli * studenti e dei relativi voti * * @return La lista di oggetti che rappresentano uno studente ed i suoi voti * correlati */ public List<StudentMarks> listStudents() {/** * Query che estrae la lista di tutti i record nella tabella Student e * che per ogni record in tale tabella estrae i relativi record * correlati nella tabella Marks */String SQL = 'select * from Student,Marks where Student.id=Marks.sid';/** * Ottengo la lista degli oggetti StudentMarks,corrispondenti ognuno ad * un record della tabella Student con i correlati vori rappresentati * dai record della tabella Marks,invocando il metodo query * sull’oggetto JdbcTemplate passandogli i seguenti parametri. * * @param La query per creare il preparated statement * @param Un oggetto che implementa RowMapper che viene usato per *mappare una singola riga della tabella su di un oggetto Java */List<StudentMarks> studentMarks = jdbcTemplateObject.query(SQL,new StudentMarksMapper());return studentMarks; }}

然后,這是 MainApp 類來測試應(yīng)用程序:

package org.andrea.myexample.myDeclarativeTransactionSpring;import java.util.List;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;// Classe principale:public class MainApp { public static void main(String[] args) {/** * Crea il contesto in base alle impostazioni dell’applicazione definite * nel file Beans.xml */ApplicationContext context = new ClassPathXmlApplicationContext('Beans.xml');/** * Recupera un bean avente nel file di * configurazione Beans.xml */StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean('studentJDBCTemplate');System.out.println('------Creazione dei record--------');// Creo i record nelle tabelle Studend e Marks:studentJDBCTemplate.create('Zara',11,99,2010);studentJDBCTemplate.create('Nuha',20,97,2010);studentJDBCTemplate.create('Ayan',25,100,2011);System.out.println('------Elenca tutti i record--------');// Recupera la lista degli studenti con i voti ad essi associati:List<StudentMarks> studentMarks = studentJDBCTemplate.listStudents();for (StudentMarks record : studentMarks) { // e li stampa System.out.print('ID : ' + record.getId()); System.out.print(',Name : ' + record.getName()); System.out.print(',Marks : ' + record.getMarks()); System.out.print(',Year : ' + record.getYear()); System.out.println(',Age : ' + record.getAge());} }}

最后,這是我的 Beans.xml 配置文件:

<?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:tx='http://www.springframework.org/schema/tx' xmlns:aop='http://www.springframework.org/schema/aop' xsi:schemaLocation='http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd'> <!-- Initializazione della sorgente dati: --> <bean class='org.springframework.jdbc.datasource.DriverManagerDataSource'><property name='driverClassName' value='com.mysql.jdbc.Driver' /><property name='url' value='jdbc:mysql://localhost:3306/SpringTestDb' /><property name='username' value='root' /><property name='password' value='aprile12' /> </bean> <tx:advice transaction-manager='transactionManager'><tx:attributes> <tx:method name='create' /></tx:attributes> </tx:advice> <aop:config><aop:pointcut expression='execution(* org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate.create(..))' /><aop:advisor advice-ref='txAdvice' pointcut-ref='createOperation' /> </aop:config> <!-- Inizializzazione del Transaction Manager: --> <bean class='org.springframework.jdbc.datasource.DataSourceTransactionManager'><property name='dataSource' ref='dataSource' /> </bean> <!-- Definizione del bean che rappresenta il DAO studentJDBCTemplate: --> <bean class='org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate'><property name='dataSource' ref='dataSource' /> </bean></beans>

問題是,當(dāng)我嘗試運(yùn)行 MainApp 類時,出現(xiàn)以下錯誤信息:

INFO: Loaded JDBC driver: com.mysql.jdbc.DriverException in thread 'main' java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate at org.andrea.myexample.myDeclarativeTransactionSpring.MainApp.main(MainApp.java:22)

在此錯誤消息中,說問題出在MainApp類的第22行上……就是當(dāng)我嘗試獲取ID =“ studentJDBCTemplate的bean:

StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean('studentJDBCTemplate');

問題出在哪里?我該如何解決?

特納克斯

安德魯

標(biāo)簽: java
相關(guān)文章:
主站蜘蛛池模板: 草逼免费看 | 国产美女福利 | 国产精品成人免费视频 | 久久riav二区三区 | 麻豆视频免费网站 | 亚洲精品中文一区不卡 | 99九九精品免费视频观看 | 日韩精品一区在线观看 | 国产黄大片在线视频 | 精品自拍一区 | 妞干网在线观看视频 | 国产精品成人不卡在线观看 | 色综合久久夜色精品国产 | 黄色一级免费网站 | xxxx性xx另类 | 高清免费国产在线观看 | 免费一级成人免费观看 | 国产成人精品一区二区 | 一级a毛片免费观看 | 日本特黄特色大片免费视频观看 | 国产乱在线观看视频 | 欧美成人久久一级c片免费 欧美成人午夜不卡在线视频 | 欧美一区二区在线免费观看 | 欧美aaaav免费大片 | 亚洲欧美国产一区二区三区 | 欧美yw193.c㎝在线观看 | 日本理论片中文在线观看2828 | 尤物视频在线观看网址 | 狠狠五月天中文字幕 | 国产欧美日韩一区二区三区在线 | 免费黄在线观看 | 色综合久久夜色精品国产 | 久久一区二区三区免费 | 国产精品视频牛仔裤一区 | julia一区二区中文字幕 | 国语自产免费精品视频在 | 91精品国产免费入口 | 超级97碰碰碰碰久久久久最新 | 精品欧美激情在线看 | 91精品国产高清91久久久久久 | 国产一区二区影院 |