jeudi 23 juin 2011

Maven Spring3 JBoss 6 Hibernate exemple


Je suis fier d'annoncer la première version du projet lin-mon-webapp avec Spring 3 Hibernate Maven sur JBoss 6.Le code source est disponible sur Google project :  http://code.google.com/p/lin-mon-webapp/.
Pour réussir je me suis aidé du blog suivant :http://www.nabeelalimemon.com/blog/2010/05/spring-3-integrated-with-hibernate-part-a/. (Merci ;-)))

Pour construire te déployer le war, vous aurez besoin de :

-> Maven 2
-> JBoss 6 ( In jbossweb-standalone/lib/ vous devez mettre les jars suivants :  jstl-1.1.2.jar et standard-1.1.2.jar )
-> Mysql et de créer la base intégration avec la table User :

create database integration;
GRANT ALL ON integration.* TO 'integration'@'localhost' IDENTIFIED BY 'integration';
flush privileges;
create table USER (   
user_id int(11) primary key,   
first_name varchar(30),   
last_name varchar(30),   
email varchar(30) );
insert into USER values (1, 'titi', 'toto', 'mail@gmail.com');

Puis vous pouvez consulter le nombre et la liste des utilisateurs : http://localhost:8080/monitor/users

Voici les fichiers principaux de l'application :


Maven pom.xml :

<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>fr.dr.linmon</groupId>
<artifactId>linmon</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Monitor app</name>
<repositories>
<repository>
  <id>JBoss Repo</id>
  <url>http://repository.jboss.com/maven2</url>
</repository>
</repositories>
<dependencies>
  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${org.springframework.version}</version>
   </dependency>
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework.version}</version>
   </dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-orm</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>${org.springframework.version}</version>
</dependency>    
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>  
<dependency>
    <groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.5</version>
     <scope>runtime</scope>
</dependency>



        <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.9</version>
        </dependency>


   <dependency>
     <groupId>log4j</groupId>
     <artifactId>log4j</artifactId>
     <version>1.2.15</version>
     <exclusions>
       <exclusion>
         <groupId>javax.mail</groupId>
         <artifactId>mail</artifactId>
       </exclusion>
       <exclusion>
         <groupId>javax.jms</groupId>
         <artifactId>jms</artifactId>
       </exclusion>
       <exclusion>
         <groupId>com.sun.jdmk</groupId>
         <artifactId>jmxtools</artifactId>
       </exclusion>
       <exclusion>
         <groupId>com.sun.jmx</groupId>
         <artifactId>jmxri</artifactId>
       </exclusion>
     </exclusions>
   </dependency>
   <dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-validator</artifactId>
     <version>4.0.2.GA</version>
     <exclusions>
  <exclusion>
    <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
   </exclusion>      
     </exclusions>
   </dependency>
   <dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-annotations</artifactId>
     <version>3.4.0.GA</version>
     <exclusions>
       <!-- Exclude Commons Logging in favor of SLF4j -->
       <exclusion>
         <groupId>org.apache.commons</groupId>
         <artifactId>com.springsource.org.apache.commons.logging</artifactId>
       </exclusion>
   <exclusion>
     <groupId>xml-apis</groupId>
     <artifactId>xml-apis</artifactId>
   </exclusion>
   <exclusion>
     <groupId>org.slf4j</groupId>
     <artifactId>slf4j-api</artifactId>
   </exclusion>            
     </exclusions>
   </dependency>
   <dependency>
      <groupId>javax.persistence</groupId>
      <artifactId>persistence-api</artifactId>
      <version>1.0</version>
    </dependency>
   <dependency>
     <groupId>commons-dbcp</groupId>
     <artifactId>commons-dbcp</artifactId>
     <version>1.2.2</version>
   </dependency>
   <dependency>
     <groupId>org.aspectj</groupId>
     <artifactId>aspectjrt</artifactId>
     <version>${aspectj.version}</version>
   </dependency>
  <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>


<build>
<finalName>monitor</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
<verbose>true</verbose>
</configuration>
</plugin>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.4</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
</plugins>
</build>
  
<properties>
    <org.springframework.version>3.0.5.RELEASE</org.springframework.version>
    <aspectj.version>1.6.6</aspectj.version>    
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
</project>


First the web.xml in whicn we create the servlet monitor :

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
  <display-name>Maven Spring MVC 3 with JBOSS 6 </display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/spring.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>     
  
  <!-- Front servlet.  -->
  <servlet>
<servlet-name>monitor</servlet-name>
<display-name>monitor</display-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/monitor-servlet.xml</param-value>
    </init-param>
<load-on-startup>1</load-on-startup>
  </servlet>
 
<!-- Every request on / will be treat by monitor servlet. -->
  <servlet-mapping>
<servlet-name>monitor</servlet-name>
<url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

Then there is the monitor servlet which define the controller, view relover ... and also where to search controller methos:

monitor-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-autowire="byName">
<!-- Every contoller is automaticaly detect due to annotation @Controller.
    We define here in wich package the post processor have to search controller annotation -->
  <context:component-scan base-package="fr.dr.monitor.controller"/>  

<context:annotation-config/>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<bean 
class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>
</beans>



The controller class contains this method :

@RequestMapping(value = "users", method = RequestMethod.GET)
public ModelAndView getUsers() {
  List<User> users = userDAO.getUsers();
  ModelAndView modelAndView = new ModelAndView("users");
  modelAndView.addObject("users", users);
  return modelAndView;
}  

To do that the controller call UserDAO methods and Hibernate will retreive data in User table.
Here is the spring beans file that create Hibernate Session and datasource :

spring.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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">


 <!--  <context:component-scan base-package="com.springhibernate.integration.aspects" />-->

 <!--Enables the use of @AspectJ style of aspects' declarations. AspectJ run-time isn't necessarily involved-->
 <aop:aspectj-autoproxy/>

 <!--Platform Transaction Manager declared as "transactionManager" will be used.-->
 <!--"aspectj" mode enables load-time/compile-time weaving of transactional methods, which enables
  those methods to be intercepted even when called internally.
  (Unlike Spring generated proxies which will only be intercepted when called from outside)--> 
 <tx:annotation-driven transaction-manager="transactionManager"/>

<!--
Activates various annotations to be detected in bean classes: Spring's
@Required and @Autowired, as well as JSR 250's @PostConstruct,
@PreDestroy and @Resource (if available) and JPA's @PersistenceContext
and @PersistenceUnit (if available).
-->
<context:annotation-config/>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
 <property name="dataSource" ref="dataSource"/>
 <property name="hibernateProperties">
   <props>
     <prop key="dialect">org.hibernate.dialect.MySQL5Dialect</prop>
     <prop key="show_sql">true</prop>
   </props>
 </property>
 <property name="mappingResources">
   <list>
     <value>mappings/user.hbm.xml</value>
   </list>
 </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
 <property name="sessionFactory" ref="sessionFactory"/>
</bean>

<context:property-placeholder location="classpath*:/META-INF/properties/*.properties"/>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
 <property name="driverClassName" value="${database.driverClassName}"/>
 <property name="url" value="${database.url}"/>
 <property name="username" value="${database.username}"/>
 <property name="password" value="${database.password}"/>
</bean>



  <!--repository init area-->
  <bean id="repository.users" class="fr.dr.monitor.repository.UserDAO"
        autowire="constructor"/>
</beans>

The session factory will be inject to UserDAO to query on USER table :

UserDAO.java

@Repository
@Transactional
public class UserDAO implements IUser {

private SessionFactory sessionFactory;

@Autowired
public UserDAO(SessionFactory sessionFact) {
this.sessionFactory = sessionFact;
}

@Transactional
public User getUser(Long id) {
return (User) sessionFactory.getCurrentSession().get(User.class, id);
}

@SuppressWarnings("unchecked")
@Transactional
public List<User> getUsers() {
return sessionFactory.getCurrentSession().createQuery("from User user").list();
}

@Transactional
public void addUser(User user) {
sessionFactory.getCurrentSession().save(user);
}
}

All the code is available on google project with Apache License V2 : http://code.google.com/p/lin-mon-webapp/ 

Aucun commentaire:

Enregistrer un commentaire