0

I have started using Spring and gone through multiple tutorials on the net. I am trying to use Spring MVC to insert a name,age record into database. While trying to achieve this, I have come to a stop trying to define a bean for my DAO. Do I need to define in it my application-servlet.xml and somehow get it though getBean or do I make a new xml to define beans and try to use application context. Also, do I define a new application context or somehow get it if Dispatcher servlet somehow already has made it.

This is my web.xml

<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" `enter code here`
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Spring MVC Form Handling</display-name>

    <servlet>
        <servlet-name>SpringDB</servlet-name>
        <servlet-class>
           org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SpringDB</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
         <param-value>/WEB-INF/SpringDB-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>
         org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>


</web-app>

this is my SpringDB.xml

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
   http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package="com.tutorialspoint" />

   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>

  <bean id="dataSource" 
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql://172.22.201.142:3306/"/>
      <property name="username" value="tcm_user"/>
      <property name="password" value="tcm_pwd"/>
   </bean>

  <bean id="studentJDBCTemplate" 
      class="com.tutorialspoint.StudentJDBCTemplate">
      <property name="dataSource"  ref="dataSource" />    
   </bean>

</beans>

This is my first question and I am sorry for any errors, I will edit any mistakes or add info. Thanks

sidgate
  • 14,650
  • 11
  • 68
  • 119
SKaul
  • 349
  • 2
  • 7
  • 22

3 Answers3

0

Firstly you need not to include contextConfigLocation /WEB-INF/SpringDB-servlet.xml

As dispatcher servlet will automatically load this xml You can make a new xml or you can define it in /WEB-INF/SpringDB-servlet.xml. For defining it in new xml like "DAOBeans.xml" use below configuration and define beans in it

<context-param>
    <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/DAOBeans.xml</param-value>
</context-param>

<listener>
    <listener-class>
     org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>
nikhilgupta86
  • 472
  • 3
  • 15
  • If I define it in SpringDB-servlet.xml, then how do I access it ? I am having trouble understanding the context hierarchy and do not want to create multiple application contexts. – SKaul Jan 27 '14 at 08:40
  • Most probably this link will help you understanding the applicationcontext.xml and application-servlet.xml [link](http://stackoverflow.com/questions/3652090/difference-between-applicationcontext-xml-and-spring-servlet-xml-in-spring) – nikhilgupta86 Jan 27 '14 at 08:47
  • Thanks, the link clears up some doubts. Can you please give me a link of an example on the same.Also, how do I retrieve the dispatcher servlet's context or the higher up-application context so that I can use getBean() method ? – SKaul Jan 27 '14 at 09:01
  • But why do you want servlet context object beans will be instantiated automatically for you by the container once you create the xml file for loading beans and mention them in context loader parameters. – nikhilgupta86 Jan 29 '14 at 07:25
  • Yes, I understand the concept now, Thanks for replying – SKaul Jan 30 '14 at 07:02
0

For more details, please refer to my github repo.
Hello buddy, I love spring-web-mvc so deeply that I would use it as my primary dispatcher framework.
Integrated with spring and hibernate, this SSH framework will be rather powerful and easy for you to develop a web application.

spring is a bean container and factory pattern that maintain all instances and beans in your backend application.

hibernate is a ORM framework use to free you from nasty and fundamental SQL.
springmvc is a dispatcher framework like struts, but I think springmvc is much better than struts due to its convenience.

spring

To achieve them, first you need to register the spring in web.xml

   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

In spring, you could use xml based configurationor annotation based configuration. I personally prefer annotation because it is much easier.
For DAO bean, you could use package scan in applicationContext.xml

<context:component-scan base-package="root-package-name"/>

Then you should put your applicationContext.xml into your classpath as the <context-param> depicted to configure the spring container.

hibernate

Next you need to configure hibernate. Beware hibernate need to configure in applicationContext.xml rather than web.xml.
Actually you can use other ORM framework. I just provide you as an example from me.
All entity could be automatically scanned by:

<bean name="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>rugal.center.core.entity</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.format_sql">false</prop>
            <prop key="hibernate.hbm2ddl.auto">validate</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.connection.autocommit">false</prop>
        </props>
    </property>
</bean>

Isn't it easy?

spring-web-mvc

Finally it is springmvc that matters. you need to register it in web.xml

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/static/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

After this, you need a springmvc-sevlet.xml under WEB-INF folder, which used to configure URL-mapping, response rule and so on.
all controller in springmvc could be scanned automatically by:

<mvc:annotation-driven >
<context:component-scan base-package="rugal.**.controller">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
Community
  • 1
  • 1
Rugal
  • 2,612
  • 1
  • 15
  • 16
0

Congrats for starting with Spring :)

I found that using annotation-configuration along with the spring-tool-suite (IDE) was the easiest. This way you dont have to search for your beans in XML-files when your projects gets larger, and you just have to relate to .java files. (which i prefer).

Below is as simple cut/paste example to give you some pointers. This is how i used hibernate through a DAO-layer to persist simple pojos to a database. This example uses an MSSQL base

In order to enable @-annotaion driven configuration. Use the below code in your applicationcontext.xml.

<context:annotation-config/>
<context:component-scan base-package="com.***.***.wfmforecastfetcher.*"/>

HibernateConfig.java - config

import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class HibernateConfig {

@Bean
public DataSource dataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    ds.setUsername("USERNAME");
    ds.setPassword("PASSWORD");
    ds.setUrl("jdbc:sqlserver://URL-TO-DATABSE\\DATABASENAME:PORT;databaseName=DATABASENAME");
    return ds;
}

@Bean
public SessionFactory sessionFactory() {
    LocalSessionFactoryBean factoryBean = null;
    try {
        factoryBean = new LocalSessionFactoryBean();
        Properties pp = new Properties();
        pp.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
        pp.setProperty("hibernate.hbm2ddl.auto", "update");
        pp.setProperty("hibernate.show_sql", "true");
        pp.setProperty("hibernate.jdbc.batch_size", "100");

        factoryBean.setDataSource(dataSource());
        factoryBean.setPackagesToScan(new String[] { "com.***.***.wfmforecastfetcher.model" });
        factoryBean.setHibernateProperties(pp);
        factoryBean.afterPropertiesSet();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return factoryBean.getObject();
}

@Bean
public HibernateTransactionManager transactionManager() {
    return new HibernateTransactionManager(sessionFactory());
}

}

ForecastDAOImpl.java - hibernate

@Repository("forecastDAO")
public class ForecastDAOImpl implements ForecastDAO {

@Autowired
private SessionFactory sessionFactory;

public void deleteForecast(Forecast forecast) {

    sessionFactory.getCurrentSession().delete(forecast);

}

public void deleteForecasts(List<Forecast> forecasts) {
    for (Forecast frc : forecasts) {
        sessionFactory.getCurrentSession().delete(frc);
    }

}

public void persistForecast(Forecast forecast) {
    sessionFactory.getCurrentSession().persist(forecast);
}

@SuppressWarnings("unchecked")
public List<Forecast> getAllForecast() {

    List<Forecast> forecasts =     sessionFactory.getCurrentSession().createCriteria(Forecast.class).list();

    return forecasts;
}

public Forecast getForecastById(int id) {

    return (Forecast) sessionFactory.getCurrentSession().get(Forecast.class, id);

}

public void persistForecast(ArrayList<Forecast> forecasts) {

    StatelessSession session = sessionFactory.openStatelessSession();
    Transaction tx = session.beginTransaction();
    int i = 0;
    for (Forecast each : forecasts) {
        session.insert(each);

    }

    tx.commit();
    session.close();

}

public void deleteAllForecasts() {
    String hql = "delete from WFM_FORECAST";
    Query query = sessionFactory.getCurrentSession().createQuery(hql);

}
}

Forecast.java - pojo

@Entity(name = "WFM_FORECAST")
public class Forecast {

private int activityId;
private double averageHandlingTime;
private int businessUnitId;
private Date dateTime;

@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Index(name = "idIndex")
private int id;

private double interactionVolume;
private int siteId;

public Forecast() {
    // Default Constructor for Hibernate
}

public Forecast(int activityId, double averageHandlingTime, int buId, Date dateTime, double interactionVolume,
        int siteId) {
    this.dateTime = dateTime;
    this.businessUnitId = buId;
    this.siteId = siteId;
    this.activityId = activityId;
    this.setInteractionVolume(interactionVolume);
    this.setAverageHandlingTime(averageHandlingTime);
}

/**
 * @return the activityId
 */
public int getActivityId() {
    return activityId;
}

/**
 * @return the averageHandlingTime
 */
public double getAverageHandlingTime() {
    return averageHandlingTime;
}

/**
 * @return the businessUnitId
 */
public int getBusinessUnitId() {
    return businessUnitId;
}

/**
 * @return the dateTime
 */
public Date getDateTime() {
    return dateTime;
}

/**
 * @return the id
 */

public int getId() {
    return id;
}

/**
 * @return the interactionVolume
 */
public double getInteractionVolume() {
    return interactionVolume;
}

/**
 * @return the siteId
 */
public int getSiteId() {
    return siteId;
}

/**
 * @param activityId
 *            the activityId to set
 */
public void setActivityId(int activityId) {
    this.activityId = activityId;
}

/**
 * @param averageHandlingTime
 *            the averageHandlingTime to set
 */
public void setAverageHandlingTime(double averageHandlingTime) {
    this.averageHandlingTime = averageHandlingTime;
}

/**
 * @param businessUnitId
 *            the businessUnitId to set
 */
public void setBusinessUnitId(int businessUnitId) {
    this.businessUnitId = businessUnitId;
}

/**
 * @param dateTime
 *            the dateTime to set
 */
public void setDateTime(Date dateTime) {
    this.dateTime = dateTime;
}

/**
 * @param id
 *            the id to set
 */
public void setId(int id) {
    this.id = id;
}

/**
 * @param interactionVolume
 *            the interactionVolume to set
 */
public void setInteractionVolume(double interactionVolume) {
    this.interactionVolume = interactionVolume;
}

/**
 * @param siteId
 *            the siteId to set
 */
public void setSiteId(int siteId) {
    this.siteId = siteId;
}

}
Yash
  • 9,250
  • 2
  • 69
  • 74
Jørgen Skår Fischer
  • 883
  • 1
  • 10
  • 22