- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试在 Spring Framework 应用程序中实现有关声明式事务的教程,但没有成功,因为当我尝试执行 MainApp 类来测试应用程序行为时,我收到一个错误:
http://www.tutorialspoint.com/spring/declarative_management.htm
所以我有 StudentDAO 接口(interface),我只定义了我想要的 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();
}
然后我有 StudentMark 类代表我的实体 以保留在数据库的 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;
}
}
然后我有实现 RowMapper 接口(interface)的类 StudentMarksMapper:
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;
}
}
在它旁边是 StudentJDBCTemplate 类 StudentDAO 接口(interface):
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 age, Integer marks, 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, marks, 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 类:
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 id="studentJDBCTemplate" 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 id="dataSource"
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 id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="create" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="createOperation"
expression="execution(* org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate.create(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="createOperation" />
</aop:config>
<!-- Inizializzazione del Transaction Manager: -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Definizione del bean che rappresenta il DAO studentJDBCTemplate: -->
<bean id="studentJDBCTemplate" class="org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
问题是,当我尝试运行我的 MainApp 类时,我收到以下错误消息:
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Exception 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 行...那只是当我尝试获取具有 ID="studentJDBCTemplate:
的 bean 时StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate");
问题出在哪里?我该如何解决?
谢谢
安德里亚
最佳答案
选项 1,更改配置以在接口(interface)级别注入(inject)事务:
<aop:config>
<aop:pointcut id="createOperation"
expression="execution(* org.andrea.myexample.myDeclarativeTransactionSpring.StudentDAO.create(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="createOperation" />
</aop:config>
并获取 bean 作为该接口(interface)的实例:
StudentDAO studentDao = (StudentDAO) context.getBean("studentJDBCTemplate");
选项2,表明代理应该使用proxy-target-class
属性扩展目标类:
<aop:config proxy-target-class="true">
...
</aop:config>
第一个选项更简洁,但坦率地说,我更愿意在 Spring bean XML 中使用@Transactional
注释而不是 AOP 声明。有时很难让后者正确,如果您没有对您的组件进行特定的事务性测试,您将不一定会注意到事情不正确。
关于java.lang.ClassCastException : com. sun.proxy.$Proxy0 无法转换为 org.andrea.myexample.myDeclarativeTransactionSpring.StudentJDBCTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15141237/
我在这里阅读了有关代理的示例: http://docs.oracle.com/javase/1.3/docs/guide/reflection/proxy.html 可以看到,'invoke'方法中的
在我的通用 nuxt 应用程序中,我将代理设置为 true 并重写了我的 url 以避免 CORS 问题。但是当我将代理设置为 true 时,我所有的发布请求都会更改为获取请求。不明白为什么以及如何将
我正在开发一个连接到 SFTP 服务器并使用 Apache Commons VFS 下载文件的应用程序,它工作得很好,但系统需要允许用户根据需要指定代理。 现在,我知道 Apache Commons
跟随线程[实体无法转换为javassist.util.proxy.Proxy,我现在确实有服务器端错误(tks thomas) 我无法在我的应用程序中面对真正的问题。 java.lang.ClassC
我正在使用 Charles Proxy 重写 API 的响应以进行测试。 如果我设置断点,我就可以按照自己的意愿完全重写原始响应。 但是,如果我想通过“重写”工具自动化它,我就陷入困境了,似乎你无法修
让我解释一下困境。 我使用 Amazon 的 3 项服务:EC2、S3 和 CloudFront。 EC2 接收上传的文件,并将其存储在 S3 存储桶中。然后 CloudFront 镜像 S3 存储桶
我正在使用 Caddy 在 DigitalOcean Ubuntu droplet 上反向代理某些站点。 这是我的 Caddy 文件,非常简单:upside_down: my-site.com {
我正在尝试测试承受多台计算机负载的 SOCKS 代理。我的代码大纲类似于 使用一个客户端直接连接到服务器,下载测试文件,并记录所花费的时间。 通过代理与一个客户端连接,下载测试文件,并记录所花费的时间
以下情况: 如果我将浏览器的 http/https 代理设置为 Charles 为 (127.0.0.1:8888) 配置的端口,使用 Charles 代理拦截 Web 流量就可以正常工作 如果我将浏
我有一个使用 grunt 构建的 angularJs 应用程序和一个用 Java 编写的在 tomcat 服务器上运行的服务器后端。为了在开发时将它们连接在一起,我想使用 grunt-connect-
对于文件上传,我试图在我的 Spring Controller 中注入(inject)并使用 validator ,如下所示: @RestController @RequestMapping("/ap
我需要使用 CaSTLe DynamicProxy 来代理接口(interface),方法是向 ProxyGenerator.CreateInterfaceProxyWithTarget 提供接口(i
我已经看到,当不同框架(例如实现 EJB 规范的框架或某些 JPA 提供程序)中发生错误时,堆栈跟踪包含像 com.sun.proxy.$Proxy 这样的类。我知道代理是什么,但我正在寻找更技术性和
我正在使用带有多个 apiserver 的集群设置,它们前面有一个负载均衡器,用于外部访问,并安装在裸机上。 就像 High Availability Kubernetes Clusters 中提到的
我使用 Charles 代理(在 OS X 10.9.3 下,Mavericks 下)修改 Origin header ,以便我连接的 API(开发中)接受来自开发环境的传入请求。 我设法通过一个简单
我已经在 Python 中实现了一个“网络服务”父类(super class),如下所示: class NetworkService (threading.Thread): """
我正在使用node.js代理。但是它工作成功: proxy.on('proxyResponse', function (proxyRes, req, res) { console.log("h
我正在尝试使用Nginx-Proxy在Ubuntu VPS的docker容器内运行WordPress网站。 我创建了以下docker-compose.yml文件 version: '3.4' serv
我一直在使用 DataKinds 扩展以类型安全的方式将类型级别 Nats 传递给函数,我只是想知道是否有更好的编写方式: (Proxy :: Proxy 42) 例如,如果类型系统看到参数需要,是否
已关闭。此问题旨在寻求有关书籍、工具、软件库等的建议。不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以
我是一名优秀的程序员,十分优秀!