2013-03-08 2 views
7

Я совершенно новый в весеннем мире. Я разработал DAO с использованием Spring 3.2 и Hibernate 4.1.9, но я заметил странную вещь.получение пакета org.springframework.transaction.annotation не существует ошибка при упаковке приложения

Все используемые зависимости, относящиеся к Spring, относятся к версии 3.2.1, за исключением того, что относится к модулю spring-aop . Для этого модуля я должен использовать версию 3.2.0, потому что, если я использую 3.2.1 в реализации класса дао не найти этот импорт: org.springframework.transaction.annotation.Transactional

Это мой оригинальный pom.xml файл (который работает хорошо):

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 

    <groupId>org.andrea.myexample</groupId> 
    <artifactId>HibernateOnSpring</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <packaging>jar</packaging> 

    <name>HibernateOnSpring</name> 
    <url>http://maven.apache.org</url> 

    <properties> 
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
    </properties> 

    <dependencies> 
     <dependency> 
      <groupId>junit</groupId> 
      <artifactId>junit</artifactId> 
      <version>3.8.1</version> 
      <scope>test</scope> 
     </dependency> 

     <!-- Dipendenze di Spring Framework --> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-core</artifactId> 
      <version>3.2.1.RELEASE</version> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-beans</artifactId> 
      <version>3.2.1.RELEASE</version> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-context</artifactId> 
      <version>3.2.1.RELEASE</version> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-context-support</artifactId> 
      <version>3.2.1.RELEASE</version> 
     </dependency> 


     <dependency> <!-- Usata da Hibernate 4 per LocalSessionFactoryBean --> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-orm</artifactId> 
      <version>3.2.0.RELEASE</version> 
     </dependency> 

     <!-- Dipendenze per AOP --> 
     <dependency> 
      <groupId>cglib</groupId> 
      <artifactId>cglib</artifactId> 
      <version>2.2.2</version> 
     </dependency> 

     <!-- Dipendenze per Persistence Managment --> 

     <dependency> <!-- Apache BasicDataSource --> 
      <groupId>commons-dbcp</groupId> 
      <artifactId>commons-dbcp</artifactId> 
      <version>1.4</version> 
     </dependency> 

     <dependency> <!-- MySQL database driver --> 
      <groupId>mysql</groupId> 
      <artifactId>mysql-connector-java</artifactId> 
      <version>5.1.23</version> 
     </dependency> 

     <dependency> <!-- Hibernate --> 
      <groupId>org.hibernate</groupId> 
      <artifactId>hibernate-core</artifactId> 
      <version>4.1.9.Final</version> 
     </dependency> 

    </dependencies> 
</project> 

и это мой PersonDAOImpl класса (класс, реализовать мои конкретные DAO):

package org.andrea.myexample.HibernateOnSpring.dao; 

import java.util.List; 

import org.andrea.myexample.HibernateOnSpring.entity.Person; 

import org.hibernate.Criteria; 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction; 
import org.hibernate.SessionFactory; 
import org.hibernate.cfg.Configuration; 
import org.hibernate.service.ServiceRegistry; 
import org.hibernate.service.ServiceRegistryBuilder; 
import org.springframework.transaction.annotation.Transactional; 

public class PersonDAOImpl implements PersonDAO { 

    // Factory per la creazione delle sessioni di Hibernate: 
    private static SessionFactory sessionFactory; 

    public void setSessionFactory(SessionFactory sessionFactory) { 
     this.sessionFactory = sessionFactory; 
    } 

    // CREATE CRUD Operation: 
    @Transactional(readOnly = false) 
    public Integer addPerson(Person p) { 

     System.out.println("Inside addPerson()"); 

     Session session = sessionFactory.openSession(); 

     Transaction tx = null; 
     Integer personID = null; 

     try { 
      tx = session.beginTransaction(); 

      personID = (Integer) session.save(p); 
      tx.commit(); 
     } catch (HibernateException e) { 
      if (tx != null) 
       tx.rollback(); 
      e.printStackTrace(); 
     } finally { 
      session.close(); 
     } 

     return personID; 

    } 

    // READ CRUD Operation (legge un singolo record avente uno specifico id): 
    public Person getById(int id) { 

     System.out.println("Inside getById()"); 

     Session session = sessionFactory.openSession(); 

     Transaction tx = null;   
     Person retrievedPerson = null; 

     try { 
      tx = session.beginTransaction(); 
      retrievedPerson = (Person) session.get(Person.class, id); 
      tx.commit(); 
     }catch (HibernateException e) { 
      if (tx != null)     
       tx.rollback();   
      e.printStackTrace(); 
     } finally {     
      session.close(); 
     } 

     return retrievedPerson; 
    } 

    // READ CRUD Operation (recupera la lista di tutti i record nella tabella): 
    @SuppressWarnings("unchecked") 
    public List<Person> getPersonsList() { 

     System.out.println("Inside getPersonsList()"); 

     Session session = sessionFactory.openSession(); 
     Transaction tx = null; 
     List<Person> personList = null; 

     try { 
      tx = session.beginTransaction(); 
      Criteria criteria = session.createCriteria(Person.class); 
      personList = criteria.list(); 
      System.out.println("personList: " + personList); 
      tx.commit(); 
     }catch (HibernateException e) { 
      if (tx != null)     
       tx.rollback();   
      e.printStackTrace(); 
     } finally { 
      session.close(); 
     } 
     return personList; 
    } 

    // DELETE CRUD Operation (elimina un singolo record avente uno specifico id): 
    public void delete(int id) { 

     System.out.println("Inside delete()"); 

     Session session = sessionFactory.openSession(); 
     Transaction tx = null; 

     try { 
      tx = session.beginTransaction(); 
      Person personToDelete = getById(id); 
      session.delete(personToDelete); 
      tx.commit(); 
     }catch (HibernateException e) { 
      if (tx != null)     
       tx.rollback();   
      e.printStackTrace(); 
     } finally { 
      session.close(); 
     } 

    } 

    @Transactional 
    public void update(Person personToUpdate) { 

     System.out.println("Inside update()"); 

     Session session = sessionFactory.openSession(); 
     Transaction tx = null; 

     try { 
      System.out.println("Insite update() method try"); 
      tx = session.beginTransaction(); 
      session.update(personToUpdate); 

      tx.commit(); 
     }catch (HibernateException e) { 
      if (tx != null)     
       tx.rollback();   
      e.printStackTrace(); 
     } finally { 
      session.close(); 
     } 

    } 

} 

Проблема заключается в том, что если я использую версию 3.2.1 для весенне-AOP модуль вместо 3.2.0 меняющегося эту зависимость следующим образом:

<dependency> <!-- Usata da Hibernate 4 per LocalSessionFactoryBean --> 
     <groupId>org.springframework</groupId> 
     <artifactId>spring-orm</artifactId> 
     <version>3.2.1.RELEASE</version> 
    </dependency> 

Когда я бегу Maven ---> Maven установка произойдет сбой компиляции и возвращает следующее сообщение об ошибке:

[ERROR] COMPILATION ERROR : 
[INFO] ------------------------------------------------------------- 
[ERROR] /home/andrea/Documents/ws/HibernateOnSpring/src/main/java/org/andrea/myexample/HibernateOnSpring/dao/PersonDAOImpl.java:[15,49] error: package org.springframework.transaction.annotation does not exist 
[ERROR] /home/andrea/Documents/ws/HibernateOnSpring/src/main/java/org/andrea/myexample/HibernateOnSpring/dao/PersonDAOImpl.java:[27,2] error: cannot find symbol 
[ERROR] class PersonDAOImpl 
/home/andrea/Documents/ws/HibernateOnSpring/src/main/java/org/andrea/myexample/HibernateOnSpring/dao/PersonDAOImpl.java:[128,2] error: cannot find symbol 
[INFO] 3 errors 
[INFO] ------------------------------------------------------------- 
[INFO] ------------------------------------------------------------------------ 
[INFO] BUILD FAILURE 
[INFO] ------------------------------------------------------------------------ 
[INFO] Total time: 3.288s 
[INFO] Finished at: Fri Mar 08 13:19:23 CET 2013 
[INFO] Final Memory: 12M/105M 
[INFO] ------------------------------------------------------------------------ 
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project HibernateOnSpring: Compilation failure: Compilation failure: 
[ERROR] /home/andrea/Documents/ws/HibernateOnSpring/src/main/java/org/andrea/myexample/HibernateOnSpring/dao/PersonDAOImpl.java:[15,49] error: package org.springframework.transaction.annotation does not exist 
[ERROR] /home/andrea/Documents/ws/HibernateOnSpring/src/main/java/org/andrea/myexample/HibernateOnSpring/dao/PersonDAOImpl.java:[27,2] error: cannot find symbol 
[ERROR] class PersonDAOImpl 
[ERROR] /home/andrea/Documents/ws/HibernateOnSpring/src/main/java/org/andrea/myexample/HibernateOnSpring/dao/PersonDAOImpl.java:[128,2] error: cannot find symbol 
[ERROR] -> [Help 1] 
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. 
[ERROR] Re-run Maven using the -X switch to enable full debug logging. 
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles: 
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException 

Andin в PersonDAOImpl случиться так, что не найти FOLLO крыло импортного класса:

org.springframework.transaction.annotation.Transactional; 

Почему у меня есть эта проблема, если я попытаюсь использовать версию весенне-модульного модуля 3.2.1? Как я могу решить использовать его?

ответ

1

Аннотации @Transactional находятся в модуле spring-tx. Включите в нее версию 3.2.1 и всегда убедитесь, что используете ту же версию всех модулей Spring.

2

Попробуйте использовать все зависимости, связанные с весной той же версии. Я думаю, org.springframework.transaction.annotation.Transactional присутствует весной 3.2.0. Так что это не должно быть проблемой. Включите зависимость spring-tx для работы @Transactionl.

+0

я решил добавлять весенне-ТХ и пружинные зависимости JDBC оба принадлежат 3.2.1 версии ... но я не понять, почему он работает, когда у меня их нет, с использованием версии 2.0.0 версии модуля Spring-orm ... – AndreaNobili

+0

Я добавил зависимость и действительно, что делает работу. Спасибо за комментарий – Myna

17

Пакет org.springframework.transaction предоставляется артефактом spring-tx. Добавьте следующие строки в pom.xml и сделать Maven обновление, что нужно сделать:

<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-tx</artifactId> 
    <version>${org.springframework-version}</version> 
</dependency> 
+1

В градиенте просто добавьте строку: compile 'org.springframework: spring-tx: 3.2.2.RELEASE' Замените "3.2.2.RELEASE" версией, которую вы используете, конечно, – Myna

+0

Спасибо Шан. Это должен быть принятый ответ. –

Смежные вопросы