I am getting the following error while trying to pass in values from a properties file to Spring, so that I don't have to supply them directly in hibernate.cfg.xml. Is there a better (and correct) approach? I know that the properties file is being referenced because if I put in in invalid password, it fails on that. I'd be grateful for any help.
WARNING: No connection properties specified - the user must supply JDBC connections
Exception in thread "main" org.hibernate.HibernateException: Hibernate Dialect must be explicitly set
at org.hibernate.dialect.DialectFactory.determineDialect(DialectFactory.java:57)
at org.hibernate.dialect.DialectFactory.buildDialect(DialectFactory.java:39)
at org.hibernate.cfg.SettingsFactory.determineDialect(SettingsFactory.java:426)
This is applicationContext.xml:
<context:component-scan base-package="cmsutil"/>
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"/>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configurationClass="org.hibernate.cfg.AnnotationConfiguration"
p:packagesToScan="cmsutil.*">
<property name="exposeTransactionAwareSessionFactory" value="false" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
</props>
</property>
</bean>
<bean id="txnManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
This is my hibernate.cfg.xml file:
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="cmsutil.entity/contentcomponent.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Per Ramesh's request - web.xml
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
For Ramesh, this is my jdbc.properties, located in the root directory (/src/java/jdbc.properties)
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://xx:3306/x
jdbc.username=y
jdbc.password=z
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=false
hibernate.generate_statistics=false
add this bean in your applicationContext.xml
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>classpath:jdbc.properties</value></property>
</bean>
update this in web.xml instead of listener
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
I had the same issue but it was the result of an error in my java code. It required calling configure() on the Configuration before calling buildSessionFactory().
The javadoc for configure() method:
Use the mappings and properties specified in an application resource
named hibernate.cfg.xml.
Broken Code:
public static void main(String[] args) {
Configuration cfg = new Configuration();
factory = cfg.buildSessionFactory(); // missing the configure() call
Session s = factory.openSession();
Transaction tx = null;
try {
tx = s.beginTransaction();
Solution:
public static void main(String[] args) {
Configuration cfg = new Configuration();
factory = cfg.configure().buildSessionFactory();
Session s = factory.openSession();
Transaction tx = null;
try {
tx = s.beginTransaction();
Note: I was not using a Spring config.
Related
I know that there are lot of posts here with the same problem, but none of them seem to help me, so this will probably be a duplicate.
Im creating a spring mvc application using Maven, i have only one controller with one method. When i put the request mapping annotation only on the class level the application works fine but when i put it on the class level and the method level and i send a request like this:
localhost:8080/myapplication/planification/projet
i get 404 error: HTTP Status 404 - /myapplication/planification/WEB-INF/pages/test.jsp
here is my controller
#Controller
#RequestMapping("/planification")
public class PlanificationController {
#RequestMapping("/projet")
public ModelAndView projets (ModelAndView m){
m.addObject("projets", "All projects");
m.setViewName("test");
return m;
}
}
mvc-dispatcher-servlet.xml
<beans>
<context:component-scan base-package="com.smit"/>
<mvc:annotation-driven/>
<!-- **** VIEW RESOLVER BEAN **** -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
web.xml
<web-app>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet- class>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-dispatcher-servlet.xml
</param-value>
</context-param>
</web-app>
Hold on, you are using / in front of RequestMapping value, which means from the root. You should removed it like this
#RequestMapping("projet")
Then go to localhost:8080/myapplication/planification/projet
Edit:
WEB-INF should have / in front!
I'm working with JSF. Recently we decided to exclude service layer from our project, cause this layer in 80% of cases consist only of recalling the same named dao-methods (definelty, I know, that this way is "not true"). So, now we need to make our managed beans layer transactional, and here is the problem: I can make dao-layer transactional, but when I try to move this duty to managegbeans layer, I get an
org.hibernate.HibernateException: No Session found for current thread
Dao and managedbeans layers are in separated modules, so they have separated context.xml files. When i define tx:annotation-driven tag in dao's context.xml file, #Transactional annotations in classes in dao-module are "visible", but when I try to define this tag in managedbeans context.xml file, none of the #Transactional annotations (neiter the dao, nor the managedbeans) are visible, so i get an exception.
Any ideas, how I can correctly configure transactions?
applicationContext-dao.xml
<jee:jndi-lookup id="dataSource" jndi-name="java:/MSSQLDataSource"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan">
<list>
<value>com.company.project.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<context:component-scan base-package="com.company.project.dao"/>
applicationContext-web.xml
<context:annotation-config />
//Just because of the service layer is not fully removed, de facto we are using this import only for imort dao-context
<import resource="classpath:/applicationContext-service.xml"/>
<context:component-scan base-package="com.company.project"/>
<tx:annotation-driven transaction-manager="txManager" proxy-target-class="false"/>
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
Part of web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/applicationContext-web.xml
classpath:/applicationContext-security.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.company.project.util.ServletContextListenerConfig</listener-class>
</listener>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
ServletContextListenerConfig class:
public class ServletContextListenerConfig implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
System.setProperty("org.apache.el.parser.COERCE_TO_ZERO", "false");
}
public void contextDestroyed(ServletContextEvent event) {
// NOOP
}
}
Thanks in advance!
UPDATE:
After reading a "couple" of articles, I've spoken, that problem may be in double definition beans because of mapping them by different <context: component-scan>. In most of articles I've read, this contexts were root context by contextConfigLocation and servlet-context by DispatcherServlet , but in my case I haven't got DispatcherServlet, but I have FacesServlet by javax.faces.webapp.FacesServlet. So, does Faces Servlet do the same thing and, if yes, how? I don't see any connection between Faces Servlet and my context.xml files.
UPDATE 2:
My fault, that I didn't show this code at once.
Here's my controller:
#Component
#ViewScoped
public class ProfileBean extends EntityBeanBase<Profile> {
#Autowired
private ProfileDao profileDao;
#Override
#Transactional
protected List<Profile> getInitEntities() {
return profileDao.getAll();
}
public void profileNameValidator(FacesContext context, UIComponent component, Object value) {
if (!selectedEntity.getName().equals(value) && profileDao.exists((String) value)) {
System.out.println("Error validating");
}
}
EntityBenBase consist of many-many methods, but now I'm using only getInitEntities(), which is abstract in EnityBeanBase.
And ProfileDaoImpl:
#Repository
public class ProfileDaoImpl extends BaseDao implements ProfileDao {
#Override
public List<Profile> getAll() {
return sessionFactory.getCurrentSession().createCriteria(Profile.class).list();
}
..........
}
BaseDao is simple:
public abstract class BaseDao {
#Autowired
public SessionFactory sessionFactory;
}
Hi I am having hard time with following url:
dynamicLink
to map with following controller method:
#RequestMapping(value="/noticeOpen/{quesId}")
public ModelAndView noticeOpen(#ModelAttribute("NoticeForm") NoticeForm noticeForm,
ModelMap model,
#PathVariable("quesId") Integer quesId){
System.out.println(quesId);
return new ModelAndView("/noticeOpen","noticeForm",noticeForm);
}
Problem starts when i click on the anchor dynamicLink and it does not transfers control to my controller, instead it shows following in browser's address bar:
http://127.0.0.1:8080/prj/noticeOpen/2/WEB-INF/pages/noticeOpen.jsp
Moreover I have following mapping in applicationContext.xml
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
This all works fine if I remove {quesId} from controller's #RequestMapping and #PathParam from method signature(also remove questionId from anchor )
http://127.0.0.1:8080/prj/noticeOpen
But that does not sound dynamic and fulfill my requirement.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>Spring Web MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
Update
I created new Controller for /noticeOpen/{quesId} and its now getting the control, But I am not able to understand the behavior of the following methods.
Please take a look below on NoticeController and then result under that:
#Controller
public class NoticeController {
#RequestMapping(value="/noticeOpen/{quesId}")
public ModelAndView noticeOpen(#ModelAttribute("NoticeForm") NoticeForm noticeForm,ModelMap model,#PathVariable("quesId") Integer quesId){
return new ModelAndView("noticeOpen","noticeForm",noticeForm);
}
#RequestMapping(value="/noticeOpen")
public ModelAndView noticeOpen(#ModelAttribute("NoticeForm") NoticeForm noticeForm,ModelMap model){
return new ModelAndView("noticeOpen","noticeForm",noticeForm);
}
#RequestMapping(value="/noticeOpen") it redirects me to correct noticeOpen.jsp
#RequestMapping(value="/noticeOpen/{quesId}") it redirects me to following error Page
HTTP Status 404 - /prj/noticeOpen/WEB-INF/pages/noticeOpen.jsp
type Status report
message /prj/noticeOpen/WEB-INF/pages/noticeOpen.jsp
description The requested resource is not available.
Apache Tomcat/6.0.36
Change your prefix value in applicationContext.xml as follows
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
A slash before WEB-INF.It will work.
i am new to scala and vaadin, i'm just experimenting. I am trying to use spring application context and spring di in my scala vaadin app, but can't get a datasource to be injected. I dont know, maybe i'm doing something fundamentally wrong but here's my code:
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<description>
Vaadin production mode</description>
<param-name>productionMode</param-name>
<param-value>false</param-value>
</context-param>
<servlet>
<servlet-name>Scalatest Application</servlet-name>
<servlet-class>com.vaadin.terminal.gwt.server.ApplicationServlet</servlet-class>
<init-param>
<description>Vaadin application class to start</description>
<param-name>application</param-name>
<param-value>com.example.scalatest.ScalaApp</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Scalatest Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
application context:
<bean id="main" class="com.example.scalatest.ScalaApp">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="url"/>
<property name="username" value="root"/>
<property name="password" value="pass"/>
</bean>
and in my scala class
var dataSource:DataSource = _;
def setDataSource(datasource:DataSource){
dataSource = datasource;
}
Isn't working, ds is null at launch.
Can anyone guide me please?
The main problem you have is your application (ScalaApp) is not instantiated by Spring container but by VaadinServlet - make sure it does. There are several strategies. Here is the example project that can help you: https://github.com/archiecobbs/dellroad-stuff-vaadin-spring-demo3
Few more pieces of advice...
Instead of writing a setter yourself, add #BeanProperty annotation to your variable. Scala compiler will generate setter and getter for your variable:
#BeanProperty private var dataSource:DataSource = _
There is even better way - using Spring's annotation based container configuration. If you have only one bean of type DataSource in your context, simply add #Autowired to your variable (no need for xml definition in the context file - your class should be annotated as a #Component ):
#Component
class ScalaApp {
#Autowired private var dataSource:DataSource = _
}
Here is more information: http://static.springsource.org/spring/docs/3.0.x/reference/beans.html#beans-annotation-config
Here is part of my web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:application-config.xml
</param-value>
</context-param>
application-config.xml uses property placeholder:
<context:property-placeholder location="classpath:properties/db.properties"/>
Is it possible somehow to define which properties file to use in web.xml rather than in application-config.xml?
Yes, you can use ServletContextParameterFactoryBean to expose context-param value (it also requires full form of PropertyPlaceholderConfigurer instead of simple context:property-placeholder):
<bean id = "myLocation" class =
"org.springframework.web.context.support.ServletContextParameterFactoryBean">
<property name="initParamName" value = "myParameter" />
</bean>
<bean class =
"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" ref = "myLocation" />
</bean>
Or use Spring 3.0's EL:
<bean class =
"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value = "#{contextParameters.myParameter}" />
</bean>
Totally agree with axtavt. So all the info combined the most simple solution with Spring 3.0 thus is:
<context:property-placeholder location="#{contextParameters.propertiesLocation}"/>
with
<context-param>
<param-name>propertiesLocation</param-name>
<param-value>classpath:properties/db.properties</param-value>
</context-param>
in web.xml.