-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 
Author Message
 Post subject: Tutorial maven+spring+hibernate+web services(cxf)+mysql
PostPosted: Tue Apr 30, 2013 1:40 am 
Newbie

Joined: Sat Nov 26, 2011 4:05 am
Posts: 5
I'm not such a pro with Java, Spring, Web services, etc...
To be honest to create a full project with maven + spring + hibernate (with annotations) + cxf was a little bit difficult :
- find the right dependencies for maven for all libraries to work together was not so easy
- using spring beans with cxf (even if easier than axis2)
- etc...
In fact, every step was always full of bad surprises and I never found a complete tutorial, it was always incomplete.
Then I would like to share my experience even if I still have some issues :
- many-to-many did not work (always pb with foreign keys) => Then I managed the relationship table directly with sql queries without hibernate
- test class don't rollback in case of errors : I'm still searching...


The tutorial is with 3 tables :
Code:
CREATE TABLE `book` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `isbn` varchar(20) NOT NULL,
  `year` int(4) DEFAULT NULL,
  `lang` varchar(3) DEFAULT NULL,
  `edition` varchar(100) DEFAULT NULL,
  `title` varchar(255) DEFAULT NULL,
  `publisher` varchar(1000) DEFAULT NULL,
  `city` varchar(1000) DEFAULT NULL,
  `url` varchar(1000) DEFAULT NULL,
  `authors_desc` varchar(1000) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `UI_BOOK1` (`isbn`),
  KEY `I_BOOK_1` (`title`)
) ENGINE=InnoDB AUTO_INCREMENT=167 DEFAULT CHARSET=latin1


Code:
CREATE TABLE `author` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `UI_AUTHOR1` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=79 DEFAULT CHARSET=latin1


Code:
CREATE TABLE `authorBooks` (
  `author_id` int(20) NOT NULL,
  `book_id` int(20) NOT NULL,
  PRIMARY KEY (`author_id`,`book_id`),
  KEY `book_id` (`book_id`),
  CONSTRAINT `authorBooks_ibfk_2` FOREIGN KEY (`book_id`) REFERENCES `book` (`id`),
  CONSTRAINT `authorBooks_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `author` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1


There are 3 maven projects with the following poms :
- one "xidclient" not interesting for the tutorial (only for the dependencies inheretied by other poms)
- one "myLibraryServices" with model, BO & DAO of the tables + a few services
- one "myLibraryCxf" for deploying web services with cxf and testing with jetty directly with maven

all projects are build with hudson/sonar with a simple : maven clean install site site:deploy sonar:sonar -Dmaven.test.failure.ignore=true
Code:
<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>

    <!-- The Basics -->
    <groupId>org.oclc.xid.client</groupId>
    <artifactId>xidclient</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>${logback.version}</version>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <compileSource>1.6</compileSource>
        <slf4j.version>1.7.5</slf4j.version>
        <logback.version>1.0.11</logback.version>
        <sonar.host.url>http://www.cambyze.com:9000</sonar.host.url>
    </properties>

    <!-- Build Settings -->
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>${compileSource}</source>
                    <target>${compileSource}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-site-plugin</artifactId>
                <version>3.0</version>
            </plugin>
        </plugins>
        <extensions>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-webdav-jackrabbit</artifactId>
                <version>2.2</version>
            </extension>
        </extensions>
    </build>

    <reporting>
        <plugins>
            <plugin>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>2.0.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jxr-plugin</artifactId>
                <version>2.3</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.9</version>
            </plugin>
            <plugin>
                <groupId>org.codehaus.sonar-plugins</groupId>
                <artifactId>maven-report</artifactId>
                <version>0.1</version>
            </plugin>
        </plugins>
    </reporting>



    <!-- More Project Information -->
    <name>xidclient</name>
    <url>http://xisbn.worldcat.org/</url>

    <!-- Environment Settings -->
    <distributionManagement>
        <site>
            <id>xidclient.website</id>
            <name>xidclient Website</name>
            <url>dav://www.cambyze.com/distrib/xidclient</url>
        </site>
    </distributionManagement>

</project>


Code:
<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>

    <!-- The Basics -->
    <groupId>com.cambyze.my-library</groupId>
    <artifactId>myLibraryServices</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.oclc.xid.client</groupId>
            <artifactId>xidclient</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-asm</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>3.1.2.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <!-- Spring AOP dependency -->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>
        <!-- MySQL database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>3.6.9.Final</version>
            <!-- will come with Hibernate core -->
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <compileSource>1.6</compileSource>
        <sonar.host.url>http://www.cambyze.com:9000</sonar.host.url>
    </properties>


    <!-- Build Settings -->
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>${compileSource}</source>
                    <target>${compileSource}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-site-plugin</artifactId>
                <version>3.0</version>
            </plugin>
        </plugins>
        <extensions>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-webdav-jackrabbit</artifactId>
                <version>2.2</version>
            </extension>
        </extensions>
    </build>

    <reporting>
        <plugins>
            <plugin>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>2.0.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jxr-plugin</artifactId>
                <version>2.3</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.9</version>
            </plugin>
            <plugin>
                <groupId>org.codehaus.sonar-plugins</groupId>
                <artifactId>maven-report</artifactId>
                <version>0.1</version>
            </plugin>
        </plugins>
    </reporting>

    <!-- More Project Information -->
    <name>myLibraryServices</name>
    <url>http://www.cambyze.com</url>

    <!-- Environment Settings -->
    <distributionManagement>
        <site>
            <id>myLibraryServices.website</id>
            <name>my Library Services Website</name>
            <url>dav://www.cambyze.com/distrib/myLibraryServices</url>
        </site>
    </distributionManagement>

</project>


Code:
<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!-- The Basics -->
    <groupId>com.cambyze.my-library</groupId>
    <artifactId>myLibraryCxf</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.cambyze.my-library</groupId>
            <artifactId>myLibraryServices</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <!-- Jetty is needed if you're are not using the CXFServlet -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http-jetty</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>3.1.2.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <compileSource>1.6</compileSource>
        <sonar.host.url>http://www.cambyze.com:9000</sonar.host.url>
        <cxf.version>2.6.1</cxf.version>
    </properties>


    <!-- Build Settings -->
    <build>
        <finalName>myLibraryCxf</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>${compileSource}</source>
                    <target>${compileSource}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.26</version>
                <configuration>
                    <scanIntervalSeconds>5</scanIntervalSeconds>
                    <stopPort>9966</stopPort>
                    <stopKey>foo</stopKey>
                    <connectors>
                        <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                            <port>9080</port>
                            <maxIdleTime>60000</maxIdleTime>
                        </connector>
                    </connectors>
                </configuration>
                <executions>
                    <execution>
                        <id>start-jetty</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <daemon>true</daemon>
                        </configuration>
                    </execution>
                    <execution>
                        <id>stop-jetty</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>stop</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>**/*Test.java
                        </exclude>
                    </excludes>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-tests</id>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>test</goal>
                        </goals>
                        <configuration>
                            <skip>false</skip>
                            <excludes>
                                <exclude>none</exclude>
                            </excludes>
                            <includes>
                                <include>**/*Test.java
                                </include>
                            </includes>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-site-plugin</artifactId>
                <version>3.0</version>
            </plugin>
        </plugins>
        <extensions>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-webdav-jackrabbit</artifactId>
                <version>2.2</version>
            </extension>
        </extensions>
    </build>



    <reporting>
        <plugins>
            <plugin>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>2.0.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jxr-plugin</artifactId>
                <version>2.3</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.9</version>
            </plugin>
            <plugin>
                <groupId>org.codehaus.sonar-plugins</groupId>
                <artifactId>maven-report</artifactId>
                <version>0.1</version>
            </plugin>
        </plugins>
    </reporting>

    <!-- More Project Information -->
    <name>myLibraryCxf WS</name>
    <url>http://www.cambyze.com</url>

</project>


For sonar, put the file settings.xml in the m2 repository to specify how contact sonar, for instance :
Code:
...
        <profile>
            <id>sonar</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <!-- EXAMPLE FOR MYSQL -->
                <sonar.jdbc.url>
                    jdbc:mysql://www.xxx.com:3306/sonar?useUnicode=true&amp;characterEncoding=utf8
                </sonar.jdbc.url>
                <sonar.jdbc.driverClassName>com.mysql.jdbc.Driver</sonar.jdbc.driverClassName>
                <sonar.jdbc.username>xxx</sonar.jdbc.username>
                <sonar.jdbc.password>xxx</sonar.jdbc.password>

                <!-- optional URL to server. Default value is http://localhost:9000 -->
                <sonar.host.url>
                    http://www.xxx.com:9000
                </sonar.host.url>
            </properties>
        </profile>
...


Last edited by cambyze on Tue Apr 30, 2013 2:42 am, edited 2 times in total.

Top
 Profile  
 
 Post subject: Re: Tutorial maven+spring+hibernate+web services(cxf)+mysql
PostPosted: Tue Apr 30, 2013 2:24 am 
Newbie

Joined: Sat Nov 26, 2011 4:05 am
Posts: 5
main sources of the myLibraryServices project :

src/main/resources :
database.properties
Code:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://xxx.com:3306/databasename
jdbc.username=xxx
jdbc.password=xxx


DataSource.xml
Code:
<beans xmlns="http://www.springframework.org/schema/beans" 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.2.xsd">

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>classpath:database.properties</value>
        </property>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
</beans>


Hibernate.xml
Code:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">


    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
   
    <tx:annotation-driven transaction-manager="transactionManager"/>


    <!-- Hibernate session factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">


        <property name="dataSource">
            <ref bean="dataSource" />
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLInnoDBDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.connection.autocommit">false</prop>
            </props>
        </property>

        <property name="annotatedClasses">
            <list>
                <value>com.cambyze.my_library.services.model.Book</value>
                <value>com.cambyze.my_library.services.model.Author</value>
            </list>
        </property>
    </bean>

</beans>


BeanLocations.xml
Code:
<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"
    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">

    <!-- Database Configuration -->
    <import resource="../database/DataSource.xml" />
    <import resource="../database/Hibernate.xml" />

    <!-- Auto scan the components -->
    <context:component-scan base-package="com.cambyze.my_library.services" />

</beans>


src/main/java :
CustomHibernateDaoSupport.java
Code:
package com.cambyze.my_library.util;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public abstract class CustomHibernateDaoSupport extends HibernateDaoSupport {
    @Autowired
    public void anyMethodName(SessionFactory sessionFactory) {
        setSessionFactory(sessionFactory);
    }
}


Book.java
Code:
package com.cambyze.my_library.services.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
* @SuppressWarnings("serial")
* @author admin
*
*/
@SuppressWarnings("serial")
@Entity
@Table(name = "book")
public class Book implements java.io.Serializable {

    /**
     * Constant to identify invalid book.
     */
    public static final String INVALID_ISBN = "-1";

    /**
     * unique DB id.
     */
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    /**
     * isbn.
     */
    @Column(name = "isbn")
    private String isbn;

    /**
     * year.
     */
    @Column(name = "year")
    private Integer year;

    /**
     * language.
     */
    @Column(name = "lang")
    private String language;

    /**
     * edition.
     */
    @Column(name = "edition")
    private String edition;

    /**
     * title.
     */
    @Column(name = "title")
    private String title;

    /**
     * publisher.
     */
    @Column(name = "publisher")
    private String publisher;

    /**
     * city.
     */
    @Column(name = "city")
    private String city;

    /**
     * url of OLCL.
     */
    @Column(name = "url")
    private String url;

    /**
     * authors as a composite string.
     */
    @Column(name = "authors_desc")
    private String authorsDesc;

    public Book() {
        super();
    }

    public final Long getId() {
        return id;
    }

    public final void setId(final Long id) {
        this.id = id;
    }

    public final String getIsbn() {
        return isbn;
    }

    public final void setIsbn(final String isbn) {
        this.isbn = isbn;
    }

    public final Integer getYear() {
        return year;
    }

    public final void setYear(final Integer year) {
        this.year = year;
    }

    public final String getLanguage() {
        return language;
    }

    public final void setLanguage(final String language) {
        this.language = language;
    }

    public final String getEdition() {
        return edition;
    }

    public final void setEdition(final String edition) {
        this.edition = edition;
    }

    public final String getTitle() {
        return title;
    }

    public final void setTitle(final String title) {
        this.title = title;
    }

    public final String getPublisher() {
        return publisher;
    }

    public final void setPublisher(final String publisher) {
        this.publisher = publisher;
    }

    public final String getCity() {
        return city;
    }

    public final void setCity(final String city) {
        this.city = city;
    }

    public final String getUrl() {
        return url;
    }

    public final void setUrl(final String url) {
        this.url = url;
    }

    public final String getAuthorsDesc() {
        return authorsDesc;
    }

    public final void setAuthorsDesc(final String authorsDesc) {
        this.authorsDesc = authorsDesc;
    }

    @Override
    public final String toString() {
        String result = "Book [";
        if (this.id != null) {
            result = result + "dbid=" + Long.toString(id) + " ";
        }
        if (this.isbn != null) {
            result = result + "isbn=" + isbn + " ";
        }
        if (this.title != null) {
            result = result + "title=" + title + " ";
        }
        if (this.authorsDesc != null) {
            result = result + "authors=" + authorsDesc + " ";
        }
        result = result + "]";
        return result;
    }
}


Author.java
Code:
package com.cambyze.my_library.services.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
* @SuppressWarnings("serial")
* @author admin
*
*/
@SuppressWarnings("serial")
@Entity
@Table(name = "author")
public class Author implements java.io.Serializable {

    /**
     * Constant to identify invalid author.
     */
    public static final String INVALID_AUTHOR = "-1";

    /**
     * unique DB id.
     */
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    /**
     * name of the author.
     */
    @Column(name = "name")
    private String name;

    public Author() {
        super();
    }

    public final Long getId() {
        return id;
    }

    public final void setId(final Long id) {
        this.id = id;
    }

    public final String getName() {
        return name;
    }

    public final void setName(final String name) {
        this.name = name;
    }

    @Override
    public final String toString() {
        String result = "Author [";
        if (this.id != null) {
            result = result + "dbid=" + Long.toString(id) + " ";
        }
        if (this.name != null) {
            result = result + "name=" + name + " ";
        }
        result = result + "]";
        return result;
    }
}


AuthorDao.java
Code:
package com.cambyze.my_library.services.dao;

import java.util.List;

import com.cambyze.my_library.services.model.Author;
import com.cambyze.my_library.services.model.Book;

/**
* Data Access Object (DAO) for the author.
*
* @author admin
*
*/
public interface AuthorDao {
    /**
     * Save the author in DB.
     *
     * @param author
     *            author to store.
     * @return id of the author.
     */
    Long save(Author author);

    /**
     * Update the author in DB.
     *
     * @param author
     *            author to update (known by its id).
     */
    void update(Author author);

    /**
     * @param author
     *            author to delete (known by its id).
     */
    void delete(Author author);

    /**
     * Find book in the DB with its name.
     *
     * @param name
     *            name to search.
     * @return author from DB.
     */
    Author findByName(String name);

    /**
     * Find author in the DB with its id.
     *
     * @param id
     *            id of the author.
     * @return author from DB.
     */
    Author findById(Long id);

    /**
     * Find the books of an author in the DB.
     *
     * @param author
     *            author.
     * @return list of books.
     */
    List<Book> getBooks(Author author);

}


BookDao.java
Code:
package com.cambyze.my_library.services.dao;

import java.util.List;

import com.cambyze.my_library.services.model.Author;
import com.cambyze.my_library.services.model.Book;

/**
* Data Access Object (DAO) for the book.
*
* @author admin
*
*/
public interface BookDao {
    /**
     * Save the book in DB.
     *
     * @param book
     *            book to store.
     * @return if of the book.
     */
    Long save(Book book);

    /**
     * Update the book in DB.
     *
     * @param book
     *            book to update (known by its id).
     */
    void update(Book book);
   
    /**
     * Add the list of authors of the book.
     * @param book book.
     * @param list list of authors.
     */
    void addAuthors(Book book, List<Author> list);

    /**
     * @param book
     *            book to delete (known by its id).
     */
    void delete(Book book);

    /**
     * Find book in the DB with its isbn.
     *
     * @param isbn
     *            isbn to search.
     * @return book from DB.
     */
    Book findByIsbn(String isbn);

    /**
     * Find book in the DB with its id.
     *
     * @param id
     *            id of the book.
     * @return book from DB.
     */
    Book findById(Long id);

}


AuthorDaoImpl.java
Code:
package com.cambyze.my_library.services.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cambyze.my_library.services.dao.AuthorDao;
import com.cambyze.my_library.services.dao.BookDao;
import com.cambyze.my_library.services.model.Author;
import com.cambyze.my_library.services.model.Book;
import com.cambyze.my_library.util.CustomHibernateDaoSupport;

/**
* Data Access Object (DAO) for the author.
*
* @author admin
*
*/
@Repository("authorDao")
@Transactional(readOnly = false, propagation = Propagation.MANDATORY, rollbackFor = Exception.class)
public class AuthorDaoImpl extends CustomHibernateDaoSupport implements AuthorDao {

    /**
     * Declaration of a logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthorDaoImpl.class);

    /**
     * Session factory.
     */
    @Autowired
    private transient SessionFactory sessionFactory;

    /**
     * DAO for books.
     */
    @Autowired
    private transient BookDao bookDao;

    /**
     * {@inheritDoc}
     *
     * @return
     */
    public final Long save(final Author author) {
        final Long authorId = (Long) getHibernateTemplate().save(author);
        LOGGER.debug("author {} inserted with id {}", author.getName(), authorId);
        return authorId;
    }

    /**
     * {@inheritDoc}
     */
    public void update(final Author author) {
        getHibernateTemplate().update(author);

    }

    /**
     * {@inheritDoc}
     */
    public void delete(final Author author) {
        getHibernateTemplate().delete(author);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("rawtypes")
    public Author findByName(String name) {
        Author author;
        final List list = getHibernateTemplate().find("from Author where name='" + name + "'");
        LOGGER.debug("findByName name:{} nb:{}", name, list.size());
        if (list.isEmpty()) {
            author = new Author();
            author.setName(Author.INVALID_AUTHOR);
        } else {
            author = (Author) list.get(0);
        }
        LOGGER.debug("author sent : {}", author.toString());
        return author;
    }

    /**
     * {{@inheritDoc}
     */
    @SuppressWarnings("rawtypes")
    public Author findById(final Long id) {
        Author author;
        final List list = getHibernateTemplate().find("from Author where id=?", id);
        LOGGER.debug("findByIsbn id:{} nb:{}", id, list.size());
        if (list.isEmpty()) {
            author = new Author();
            author.setName(Author.INVALID_AUTHOR);
        } else {
            author = (Author) list.get(0);
        }
        return author;
    }

    /**
     * {{@inheritDoc}
     */
    @SuppressWarnings({ "unchecked", "deprecation" })
    public List<Book> getBooks(Author author) {
        List<Book> list = new ArrayList<Book>();
        String query = "select book_id from authorBooks where author_id=" + Long.toString(author.getId());
        LOGGER.debug("select query : {}", query);
        SQLQuery sqlQuery = sessionFactory.getCurrentSession().createSQLQuery(query).addScalar("book_id", Hibernate.LONG);
        List<Long> rows = sqlQuery.list();
        LOGGER.debug("result query : {}", rows.size());
        for (Long row : rows) {
            LOGGER.debug("book to find : {}",row);
            Book book = bookDao.findById(row);
            list.add(book);
        }
        LOGGER.debug("result list : {}", list.toString());
        return list;
    }

}


BookDaoImpl.java
Code:
package com.cambyze.my_library.services.dao.impl;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cambyze.my_library.services.dao.BookDao;
import com.cambyze.my_library.services.model.Author;
import com.cambyze.my_library.services.model.Book;
import com.cambyze.my_library.util.CustomHibernateDaoSupport;

/**
* Data Access Object (DAO) for the book.
*
* @author admin
*
*/
@Repository("bookDao")
@Transactional(readOnly = false, propagation = Propagation.MANDATORY, rollbackFor = Exception.class)
public class BookDaoImpl extends CustomHibernateDaoSupport implements BookDao {

    /**
     * Session factory.
     */
    @Autowired
    private transient SessionFactory sessionFactory;

    /**
     * Declaration of a logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(BookDaoImpl.class);

    /**
     * {@inheritDoc}
     */
    public final Long save(final Book book) {
        Long bookId = (Long) getHibernateTemplate().save(book);
        LOGGER.debug("book {} inserted with id {}", book.getTitle(), bookId);
        return bookId;
    }

    /**
     * {@inheritDoc}
     */
    public void update(final Book book) {
        getHibernateTemplate().update(book);
    }

    /**
     * {@inheritDoc}
     */
    public void delete(final Book book) {
        // delete links with authors.
        String query = "delete from authorBooks where book_id=" + Long.toString(book.getId());
        LOGGER.debug("delete query : {}", query);
        SQLQuery sqlQuery = sessionFactory.getCurrentSession().createSQLQuery(query);
        int deleted = sqlQuery.executeUpdate();
        LOGGER.debug("delete authorBooks : {}", deleted);

        // then delete the book.
        getHibernateTemplate().delete(book);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("rawtypes")
    public Book findByIsbn(final String isbn) {
        Book book;
        final List list = getHibernateTemplate().find("from Book where isbn='" + isbn + "'");
        LOGGER.debug("findByIsbn isbn:{} nb:{}", isbn, list.size());
        if (list.isEmpty()) {
            book = new Book();
            book.setIsbn(Book.INVALID_ISBN);
        } else {
            book = (Book) list.get(0);
        }
        LOGGER.debug("book sent : {}", book.toString());
        return book;
    }

    /**
     * {{@inheritDoc}
     */
    @SuppressWarnings("rawtypes")
    public Book findById(final Long id) {
        Book book;
        final List list = getHibernateTemplate().find("from Book where id=?", id);
        LOGGER.debug("findById id:{} nb:{}", id, list.size());
        if (list.isEmpty()) {
            book = new Book();
            book.setIsbn(Book.INVALID_ISBN);
        } else {
            book = (Book) list.get(0);
        }
        return book;
    }

    /**
     * {{@inheritDoc}
     */
    public void addAuthors(Book book, List<Author> list) {
        LOGGER.debug("addAuthors for book : {} list of authors : {}", book.getId(), list.toString());
        for (Author author : list) {
            String query = "insert into authorBooks(author_id,book_id) values (" + Long.toString(author.getId()) + ","
                    + Long.toString(book.getId()) + ")";
            LOGGER.debug("insert query : {}", query);
            SQLQuery sqlQuery = sessionFactory.getCurrentSession().createSQLQuery(query);
            int inserted = sqlQuery.executeUpdate();
            LOGGER.debug("inserted authorBooks : {}", inserted);
        }
    }

}


AuthorBo.java
Code:
package com.cambyze.my_library.services.bo;

import java.util.List;

import com.cambyze.my_library.services.model.Author;
import com.cambyze.my_library.services.model.Book;

/**
* Business Object (BO) for the authors.
*
* @author admin
*
*/
public interface AuthorBo {
    /**
     * Save the author in DB.
     *
     * @param author
     *            author to store.
     * @return generated id of the author in DB.
     */
    Long save(Author author);

    /**
     * Update the author in DB.
     *
     * @param author
     *            author to update (known by its id).
     */
    void update(Author author);

    /**
     * Delete the author from the DB.
     *
     * @param author
     *            author to delete (known by its id).
     */
    void delete(Author author);

    /**
     * Find author in the DB with its name.
     *
     * @param name
     *            name to search.
     * @return author from DB.
     */
    Author findByName(String name);

    /**
     * Find author in the DB with its id.
     *
     * @param id
     *            id of the author.
     * @return author from DB.
     */
    Author findById(Long id);

    /**
     * Find the books of an author in the DB.
     *
     * @param author
     *            author.
     * @return list of books.
     */
    List<Book> getBooks(Author author);

}


BookBo.java
Code:
package com.cambyze.my_library.services.bo;

import java.util.List;

import com.cambyze.my_library.services.model.Author;
import com.cambyze.my_library.services.model.Book;

/**
* Business Object (BO) for the books.
*
* @author admin
*
*/
public interface BookBo {
    /**
     * Save the book in DB.
     *
     * @param book
     *            book to store.
     * @return id of the book.
     */
    Long save(Book book);

    /**
     * save the book in DB with its authors.
     *
     * @param book
     *            book to store.
     * @param listAuthor
     *            authors of the book.
     * @return id of the book generated in DB.
     */
    Long saveWithAuthors(Book book, List<Author> listAuthor);

    /**
     * Update the book in DB.
     *
     * @param book
     *            book to update (known by its id).
     */

    void update(Book book);

    /**
     * Delete the book from the DB.
     *
     * @param book
     *            book to delete (known by its id).
     */
    void delete(Book book);

    /**
     * Find book in the DB with its isbn.
     *
     * @param isbn
     *            isbn to search.
     * @return book from DB.
     */
    Book findByIsbn(String isbn);

    /**
     * Find book in the DB with its id.
     *
     * @param id
     *            id of the book.
     * @return book from DB.
     */
    Book findById(Long id);

}


AuthorBoImpl.java
Code:
package com.cambyze.my_library.services.bo.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cambyze.my_library.services.bo.AuthorBo;
import com.cambyze.my_library.services.dao.AuthorDao;
import com.cambyze.my_library.services.model.Author;
import com.cambyze.my_library.services.model.Book;

/**
* Business Object (BO) for the authors.
*
* @author admin
*
*/
@Service("authorBo")
public class AuthorBoImpl implements AuthorBo {

    /**
     * DAO used to manage book in the DB.
     */
    @Autowired
    private transient AuthorDao authorDao;

    /**
     * {@inheritDoc}
     */
    public Long save(final Author author) {
        return authorDao.save(author);
    }

    /**
     * {@inheritDoc}
     */
    public void update(final Author author) {
        authorDao.update(author);
    }

    /**
     * {@inheritDoc}
     */
    public void delete(final Author author) {
        authorDao.delete(author);
    }

    /**
     * {@inheritDoc}
     */
    public Author findByName(final String name) {
        return authorDao.findByName(name);
    }

    /**
     * {@inheritDoc}
     */
    public Author findById(final Long id) {
        return authorDao.findById(id);
    }

    /**
     * {@inheritDoc}
     */
    public List<Book> getBooks(Author author) {
        return authorDao.getBooks(author);
    }
}


BookBoImpl.java
Code:
package com.cambyze.my_library.services.bo.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cambyze.my_library.services.bo.BookBo;
import com.cambyze.my_library.services.dao.AuthorDao;
import com.cambyze.my_library.services.dao.BookDao;
import com.cambyze.my_library.services.model.Author;
import com.cambyze.my_library.services.model.Book;

/**
* Business Object (BO) for the books.
*
* @author admin
*
*/
@Service("bookBo")
public class BookBoImpl implements BookBo {

    /**
     * Declaration of a logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(BookBoImpl.class);

    /**
     * DAO used to manage book in the DB.
     */
    @Autowired
    private transient BookDao bookDao;

    /**
     * DAO used to manage author in the DB.
     */
    @Autowired
    private transient AuthorDao authorDao;

    /**
     * {@inheritDoc}
     */
    public Long save(final Book book) {
        return bookDao.save(book);
    }

    /**
     * {@inheritDoc}
     */
    public void update(final Book book) {
        bookDao.update(book);
    }

    /**
     * {@inheritDoc}
     */
    public void delete(final Book book) {
        bookDao.delete(book);
    }

    /**
     * {@inheritDoc}
     */
    public Book findByIsbn(final String isbn) {
        return bookDao.findByIsbn(isbn);
    }

    /**
     * {@inheritDoc}
     */
    public Book findById(final Long id) {
        return bookDao.findById(id);
    }

    /**
     * {@inheritDoc}
     */
    public Long saveWithAuthors(final Book book, final List<Author> listAuthor) {
        // save book.
        Long bookId = null;
        bookId = bookDao.save(book);
        LOGGER.debug("book saved with id : {}", bookId);

        // Add authors if not exist.
        List<Author> authors = new ArrayList<Author>();
        LOGGER.debug("saveWithAuthors called for the book : {} and {} authors", book.toString(), listAuthor.size());
        for (Author author : listAuthor) {
            LOGGER.debug("one of the author : {}", author.getName());
            Author authorDB = authorDao.findByName(author.getName());
            // if INVALID_AUTHOR, it means not in DB.
            if (authorDB.getName() == Author.INVALID_AUTHOR) {
                // store the author in DB.
                Long authorId = authorDao.save(author);
                LOGGER.debug("author id created : {}", authorId);
                authors.add(author);
            } else {
                // retrieve the id of the author in DB.
                Long authorId = authorDB.getId();
                LOGGER.debug("author id retrieved : {}", authorId);
                authors.add(authorDB);
            }
        }
        // update book with relationship
        bookDao.addAuthors(book, authors);
        LOGGER.debug("book updated with its authors : {}", authors.toString());
        return bookId;
    }
}


src/test/java
MyLibraryTest.java
Code:
package com.cambyze.my_library.services;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.oclc.xid.client.jdk14.ClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cambyze.my_library.services.bo.AuthorBo;
import com.cambyze.my_library.services.bo.BookBo;
import com.cambyze.my_library.services.model.Author;
import com.cambyze.my_library.services.model.Book;
import com.cambyze.my_library.services.xisbn.Xisbn;

/**
* Unit test for books management
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:/test-spring-services.xml" })
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class MyLibraryTest {

    @Autowired
    @Qualifier("bookBo")
    private BookBo bookBo;

    @Autowired
    @Qualifier("authorBo")
    private AuthorBo authorBo;

    /**
     * Declaration of a logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MyLibraryTest.class);

    /**
     * Test Book database management.
     */
    @Test
    @Rollback(true)
    public void testBookDB() {

        Book book = new Book();
        book.setIsbn("0000");
        book.setTitle("Test spring-hibernate");
        if (bookBo == null) {
            LOGGER.error("No spring injection of bookBo");
        }
        Long bookId = bookBo.save(book);
        LOGGER.info("Book inserted with id : {}", bookId);

        book = bookBo.findByIsbn("0000");
        LOGGER.info("Book retrieved : " + book.toString());
        assertEquals("id should be equal", bookId, book.getId());

        bookBo.delete(book);
        LOGGER.info("Book deleted");

        book = bookBo.findByIsbn("0000");
        LOGGER.info("book from db after deletion : {}", book.toString());
        LOGGER.debug("isbn invalid : {}", book.getIsbn());
        assertEquals("isbn should be invalid", Book.INVALID_ISBN, book.getIsbn());
    }

    /**
     * Test Book database management.
     */
    @Test
    @Rollback(true)
    public void testBookDB2() {

        // now test with authors
        // two books
        Book book1 = new Book();
        book1.setIsbn("0001");
        book1.setTitle("Test spring-hibernate 1");

        Book book2 = new Book();
        book2.setIsbn("0002");
        book2.setTitle("Test spring-hibernate 2");
        // two authors
        Author author1 = new Author();
        author1.setName("foo1");
        Author author2 = new Author();
        author2.setName("foo2");
        // link between them
        ArrayList<Author> list1 = new ArrayList<Author>();
        list1.add(author1);
        ArrayList<Author> list2 = new ArrayList<Author>();
        list2.add(author1);
        list2.add(author2);
        // now store the books
        Long bookId1 = bookBo.saveWithAuthors(book1, list1);
        LOGGER.debug("1st book : {} inserted with id : {}", book1.toString(), bookId1);
        Long bookId2 = bookBo.saveWithAuthors(book2, list2);
        LOGGER.debug("2nd book : {} inserted with id : {}", book2.toString(), bookId2);

        // list of books of the author1
        Author author = authorBo.findByName("foo1");
        List<Book> listBooks = authorBo.getBooks(author);
        if (listBooks == null) {
            LOGGER.error("nb of books of 1st author is null");
            fail("nb of books of 1st author is null");
        } else {
            LOGGER.debug("nb of books of 1st author : {} content : {}", listBooks.size(), listBooks.toString());
            assertEquals("Nb of books should be 2", 2, listBooks.size());
        }
        // now deleting books & authors
        bookBo.delete(book1);
        Book book = bookBo.findByIsbn("0001");
        LOGGER.info("book from db after deletion : {}", book.toString());
        LOGGER.debug("isbn invalid : {}", book.getIsbn());
        assertEquals("isbn should be invalid", Book.INVALID_ISBN, book.getIsbn());

        bookBo.delete(book2);
        book = bookBo.findByIsbn("0002");
        LOGGER.info("book from db after deletion : {}", book.toString());
        LOGGER.debug("isbn invalid : {}", book.getIsbn());
        assertEquals("isbn should be invalid", Book.INVALID_ISBN, book.getIsbn());

        authorBo.delete(author1);
        author = authorBo.findByName("foo1");
        LOGGER.info("author from db after deletion : {}", author.toString());
        assertEquals("name should be invalid", Author.INVALID_AUTHOR, author.getName());

        authorBo.delete(author2);
        author = authorBo.findByName("foo2");
        LOGGER.info("author from db after deletion : {}", author.toString());
        assertEquals("name should be invalid", Author.INVALID_AUTHOR, author.getName());
    }

...
}


Top
 Profile  
 
 Post subject: Re: Tutorial maven+spring+hibernate+web services(cxf)+mysql
PostPosted: Tue Apr 30, 2013 2:36 am 
Newbie

Joined: Sat Nov 26, 2011 4:05 am
Posts: 5
main sources of the myLibraryCxf project :

src/main/webapp/WEB-INF
web.xml
Code:
<!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>Archetype Created Web Application</display-name>

    <context-param>
        <!-- La localisation du fichier applicationContext.xml -->
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/spring-cxf.xml</param-value>
    </context-param>

    <!-- Configuration de CXF -->
    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <display-name>CXF Servlet</display-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

    <!-- Le listener Spring qui va charger le fichier applicationContext.xml -->
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

</web-app>


spring-cxf.xml
Code:
<?xml version="1.0" encoding="UTF-8"?>
<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" xmlns:jaxws="http://cxf.apache.org/jaxws"
    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
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd">

    <!-- Auto scan the components -->
    <context:component-scan base-package="com.cambyze.my_library.services.ws" />

    <import resource="classpath:spring/config/BeanLocations.xml" />

    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

    <!-- Auto scan the components -->
    <!--<context:component-scan base-package="com.cambyze.my_library.services.ws" /> -->

    <jaxws:endpoint id="WebServices" implementor="com.cambyze.my_library.services.ws.WebServicesImpl" address="/WebServices">
    </jaxws:endpoint>

</beans>


src/main/java
WebServices.java
Code:
package com.cambyze.my_library.services.ws;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

import com.cambyze.my_library.services.model.Book;

@WebService
public interface WebServices {

    /**
     * constant indicates that book is inserted in DB.
     */
    int INSERTED = 1;

    /**
     * constant indicates that book already exists in DB.
     */
    int ALREADY_EXISTS = 2;

    /**
     * constant indicates that ISBN not found.
     */
    int ISBN_NOT_FOUND = 3;

    /**
     * constant indicates that an error occured.
     */
    int ERROR = 4;

    /**
     * Web service for find book by its isbn.
     *
     * @param isbn
     *            isbn
     * @return book corresponding to the isbn else null if isbn invalid
     */
    @WebMethod
    Book findBookByIsbn(@WebParam(name = "isbn") final String isbn);

    /**
     * Web service for find book by its isbn then store in DB.
     *
     * @param isbn isbn
     * @return constant depending on the result see above
     */
    @WebMethod
    int storeBookByIsbn(@WebParam(name = "isbn") final String isbn);
}



WebServicesImpl.java
Code:
package com.cambyze.my_library.services.ws;

import javax.jws.WebService;

import org.oclc.xid.client.jdk14.ClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.cambyze.my_library.services.bo.BookBo;
import com.cambyze.my_library.services.model.Book;
import com.cambyze.my_library.services.xisbn.Xisbn;

/**
* Webservices to handle books in DB & Xisbn
*
* @author admin
*
*/
@WebService(endpointInterface = "com.cambyze.my_library.services.ws.WebServices", serviceName = "WebServices")
public class WebServicesImpl implements WebServices {

    /**
     * Declaration of a logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebServices.class);

    /**
     * BO used to manage book in the DB.
     */
    @Autowired
    private transient BookBo bookBo;


    /**
     * {@inheritDoc}
     */
    public Book findBookByIsbn(final String isbn) {
        LOGGER.debug("WS findBookByIsbn called for : {}", isbn);
        Book book;
        try {
            book = Xisbn.findBookByIsbn(isbn);
            LOGGER.debug("book retrieved : {}", book.toString());
        } catch (ClientException e) {
            book = new Book();
            LOGGER.error(e.getMessage());
        }
        return book;
    }

    /**
     * {@inheritDoc}
     */
    public int storeBookByIsbn(final String isbn) {
        LOGGER.debug("WS storeBookByIsbn called for : {}", isbn);
        int result = 0;

        try {
            Book book = bookBo.findByIsbn(isbn);
            LOGGER.debug("book retrieved from DB : {}", book.toString());
            if (book.getIsbn() == Book.INVALID_ISBN) {
                book = Xisbn.findBookByIsbn(isbn);
                LOGGER.debug("book retrieved from isbn : {}", book.toString());
                if (book.getIsbn() == Book.INVALID_ISBN) {
                    result = WebServices.ISBN_NOT_FOUND;
                } else {
                    bookBo.save(book);
                    book = bookBo.findByIsbn(isbn);
                    LOGGER.debug("book saved with id = {}", book.getId());
                    result = WebServices.INSERTED;
                }
            } else {
                LOGGER.debug("book already in DB with id : {}", book.getId());
                result = WebServices.ALREADY_EXISTS;
            }
        } catch (ClientException e) {
            LOGGER.error(e.getMessage());
            result = WebServices.ERROR;
        }

        return result;

    }
}


src/test/java
WebServicesTest.java
Code:
package com.cambyze.my_library.services.ws;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.cambyze.my_library.services.model.Book;

/**
* Unit test for books management
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring-cxf-test.xml" })
public class WebServicesTest {

    /**
     * Declaration of a logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebServicesTest.class);

    @Autowired
    @Qualifier("WebServicesClient")
    private transient WebServices webServices;
 

    /**
     * Test Book search by isbn.
     */
    @Test
    public void testBookXisbn() {
        LOGGER.debug("Start testBookXisbn");
        Book book = webServices.findBookByIsbn("9782756025698");
        LOGGER.debug("Book retrieved : {}", book.toString());
        assertEquals("isbn should be 9782756025698", "9782756025698", book.getIsbn());
    }
   
    /**
     * Test Book search by isbn in DB.
     */
    @Test
    public void testBookDB() {
        LOGGER.debug("Start testBookDB");
        int result = webServices.storeBookByIsbn("0000");
        LOGGER.debug("Result : {}", result);
        assertEquals("Result should be ISBN_NOT_FOUND", WebServices.ISBN_NOT_FOUND, result);
    }
}



With this third posts, the tutorial is finished.
I hope it will help even if this code has to be improved.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.