Соответствующий шаблон является строгим, но для элемента ‘tx: annotation-driven’
Я пытаюсь настроить JSF + Spring + hibernate, и я привязываюсь для запуска теста, но когда я использую этот «tx: annotation-driven» в моем файле application-context.xml, я получаю эту ошибку:
Соответствующий шаблон является строгим, но для элемента ‘tx: annotation-driven’
Вот мой application-context.xml:
- EJB-транзакции в локальных методах-вызовах
- Операционная система Android
- javax.transaction.Transactional vs org.springframework.transaction.annotation.Transactional
- Использование транзакций или SaveChanges (false) и AcceptAllChanges ()?
- Что произойдет, если вы не совершаете транзакцию с базой данных (скажем, SQL Server)?
om.mycompany.model.Course om.mycompany.model.Student om.mycompany.model.Teacher org.hibernate.dialect.OracleDialect
и вот мой CourseServiceImplTest. Я еще не реализовал тесты:
public class CourseServiceImplTest { private static ClassPathXmlApplicationContext context; private static CourseService courseService; public CourseServiceImplTest() { } @BeforeClass public static void setUpClass() throws Exception { context=new ClassPathXmlApplicationContext("application-context.xml"); courseService=(CourseService) context.getBean("courseService"); } @AfterClass public static void tearDownClass() throws Exception { context.close(); } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getAllCourses method, of class CourseServiceImpl. */ @Test public void testGetAllCourses() { System.out.println("getAllCourses"); CourseServiceImpl instance = new CourseServiceImpl(); List expResult = null; List result = instance.getAllCourses(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getCourse method, of class CourseServiceImpl. */ @Test public void testGetCourse() { System.out.println("getCourse"); Integer id = null; CourseServiceImpl instance = new CourseServiceImpl(); Course expResult = null; Course result = instance.getCourse(id); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); }
и вот CourseServiceImpl:
@Service("courseService") @Transactional public class CourseServiceImpl implements CourseService{ @Autowired private SessionFactory sessionFactory; @Override public List getAllCourses() { return sessionFactory.getCurrentSession().createQuery("from Course").list(); } @Override public Course getCourse(Integer id) { return (Course) sessionFactory.getCurrentSession().get(Course.class, id); } @Override public void save(Course course) { sessionFactory.getCurrentSession().saveOrUpdate(course); } }
- Django: как я могу защитить от одновременной модификации записей в базе данных
- Являются ли функции PostgreSQL транзакционными?
- Фиксация «Тайм-аут блокировки ожидания превышен; попробуйте перезапустить транзакцию «за« застрявшую »таблицу Mysql?
- Firebase runTransaction не работает - MutableData имеет значение null
- Откат вложенной / дочерней транзакции
- Структура Entity Framework и уровень изоляции транзакций
- Дублирование fragmentов на транзакции fragmentов
- Как обойти отсутствие транзакций в MongoDB?
У вас есть некоторые ошибки в вашем appcontext.xml:
-
Использовать * -2.5.xsd
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
-
Typos в
tx:annotation-driven
иcontext:component-scan
(вместо -)
Это для других (как я :)). Не забудьте добавить зависимость пружины tx jar / maven. Также правильная конфигурация в appctx:
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
, по ошибке неправильная конфигурация, которую другие могут иметь
xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
то есть дополнительный «/spring-tx-3.1.xsd»
xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
другими словами, что есть в xmlns (namespace) должно иметь правильное отображение в schemaLocation (namespace vs schema).
пространство имен: http://www.springframework.org/schema/tx
Схема Doc пространства имен: http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
эта схема пространства имен позже отображается в банке, чтобы найти путь к фактическому xsd, расположенному в org.springframework.transaction.config
Для меня все, что сработало, – это порядок, в котором пространства имен были определены в теге xsi: schemaLocation: [поскольку версия была хороша, а также уже был менеджером транзакций]
Ошибка была связана с:
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/tx http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
И ПОСТАНОВИЛИ:
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
В моем случае это было фактически симптомом сервера, размещенного на AWS, без IP для внешней сети. Он попытается загрузить пространства имен с сайта springframework.org и не сможет установить соединение.
FWIW У меня была эта же проблема. Оказалось, что мои xsi: schemaLocation были неверными, поэтому я пошел в официальные документы и вставил их в свою:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html раздел 16.5.6
Мне пришлось добавить еще пару, но все было в порядке. Далее нужно выяснить, почему это устранило проблему …
Убедитесь, что версия Spring и версия xsd одинаковы. В моем случае я использую Spring 4.1.1, поэтому мой xsd должен быть версией * -4.1.xsd
Одна дополнительная передняя косая черта (/) перед tx и файлом * .xml беспокоили меня в течение 8 часов!
Виноват:
http://www.springframework.org/schema/tx/ http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
Исправление:
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
Действительно, одному персонажу все меньше и больше удается удерживать программистов в течение нескольких часов!
Я учусь от удемий. Я следовал за каждым шагом, который показал мне мой инструктор. В весенней секции mvc crud при настройке среды разработки я имел ту же ошибку:
and
то я просто заменил
http://www.springframework.org/schema/mvc/spring-mvc.xsd
с
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
а также
http://www.springframework.org/schema/tx/spring-tx.xsd
с
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
на самом деле я посетил эти два сайта http://www.springframework.org/schema/mvc/ и http://www.springframework.org/schema/tx/ и просто добавил последнюю версию spring-mvc и spring-tx ie , spring-mvc-4.2.xsd и spring-tx-4.2.xsd
Поэтому я предлагаю попробовать это. Надеюсь это поможет. Спасибо.
Any one can help for me!!!!!!!!! (ERROR OCCUR) (ERROR OCCUR) classpath:hibernate.cfg.xml org.hibernate.cfg.AnnotationConfiguration ${org.hibernate.dialect.MySQLDialect} true (ERROR OCCUR)