我如何使用 Jersey、Spring、Hibernate 和 maven 设置项目

How can i setup a Project using Jersey, Spring, Hibernate and maven

如何使用以下库配置 Java 项目?

  1. 球衣 2.25
  2. Spring 4.3.5 发布
  3. Hibernate 5.5.6 最终版本
  4. Apache Maven
  5. Java 8

项目基于 JERSEY 2.25,SPRING 4.3.5 RELEASE,HIBERNATE 5.5.6 Final,使用 MAVEN

我想分享我在创建基本设置方面的知识,以启动您的项目。我提出此请求,因为我找不到任何完整的解决方案JERSEY-SPRING-HIBERNATE 设置和配置。因为我经历了很多问题才能找到解决方案。 也可以参考我的Github项目Jersey-Spring-Hibernate-Project .


要启动项目,请打开 Eclipse IDE。

文件 -> 新建 -> 其他 -> Maven -> Maven 项目 -> 按下一步 -> 按下一步

在过滤器中,查找版本为 2.24 或更高版本的 jersey-quickstart-webapp。

如果找不到,请单击添加原型

原型组 ID:org.glassfish.jersey.archetypes

原型工件 ID:jersey-quickstart-webapp

原型版本:2.24

存储库URL:留空

按确定。

现在再次按照从头开始的步骤操作,现在您会发现 jersey-quickstart-webapp 的版本为 2.24.

select 然后按下一步。

提供您的群组ID:"which will be your package name",在我的例子中是org.pramod

提供您的 工件 ID: "This is your project name"

Package:在这个项目中是org.pramod

点击完成


要设置我们的项目,我们需要配置 4 个文件。

  1. web.xml
  2. pom.xml
  3. applicationContext.xml
  4. MyApplication.java

文件名:src/main/webapp/WEB-INF/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" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

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

  <!--  TO REGISTER THE BEANS -->  
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- TO REGISTER THE SERVLET which is mentioned in the MyApplication -->
    <init-param>
      <param-name>javax.ws.rs.Application</param-name>
      <param-value>org.pramod.config.MyApplication</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/webapi/*</url-pattern>
  </servlet-mapping>

</web-app>

文件名:src/main/resources/applicationContext.xml

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

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

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>org.pramod.model.Customer</value>
            </list>
        </property>
    </bean>

    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
    <bean id="customerService" class="org.pramod.service.CustomerServiceImpl"/>
    <bean id="customerDao" class="org.pramod.dao.CustomerDaoImpl"/>

</beans>

文件名:pom.xml

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

  <groupId>org.pramod</groupId>
  <artifactId>JerseySpringHibernate</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>JerseySpringHibernate</name>

  <build>
     <finalName>JerseySpringHibernate</finalName>
       <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.5.1</version>
            <inherited>true</inherited>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
      </plugins>
   </build>

   <dependencyManagement>
      <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey</groupId>
            <artifactId>jersey-bom</artifactId>
            <version>${jersey.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
      </dependencies>
   </dependencyManagement>

   <dependencies>
      <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet-core</artifactId>
      </dependency>

      <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-moxy</artifactId>
      </dependency>

      <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-spring3</artifactId>
      </dependency>
<!--         
      <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
        <exclusions>
            <exclusion>
                <artifactId>javax.servlet</artifactId>
                <groupId>servlet-api</groupId>
            </exclusion>
        </exclusions>
      </dependency>
 -->       
<!-- ******************************************************** -->       
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
      </dependency>

<!-- ********************** SPRING 4.3.4 *****************************  -->

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${spring.version}</version>
      </dependency>     
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
        <exclusions>
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
             </exclusion>
        </exclusions>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-instrument</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-instrument-tomcat</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jms</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-messaging</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-orm</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-oxm</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>${spring.version}</version>
      </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc-portlet</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>${spring.version}</version>
        </dependency>

<!-- ********************* HIBERNATE 5.5.6 ************************* -->  

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-search-orm</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

<!-- ********************* MY SQL CONNECTOR *************************  -->  

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

    </dependencies>

    <properties>    
        <jersey.version>2.25</jersey.version>
        <spring.version>4.3.5.RELEASE</spring.version>
        <hibernate.version>5.5.6.Final</hibernate.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

下面提到的文件都是java个文件,放在src/main/java/后面跟包名。包名称是 org.pramod。示例 src/main/java/org.pramod.*

文件名:org.pramod.config.MyApplication.java

package org.pramod.config;

import org.glassfish.jersey.server.ResourceConfig;

public class MyApplication extends ResourceConfig{

    public MyApplication(){
        register(MyResource.class);
        register(CustomerResource.class);
    }
}

这些是 SERVLET 资源。 1.MyResource和2.CustomerResource可以移动到org.pramod.resource package

文件名:org.pramod.config.MyResource.java

package org.pramod.config;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.pramod.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Root resource (exposed at "myresource" path)
 */
@Path("myresource")
public class MyResource {

    @Autowired
    CustomerService customerService;


    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getIt() {
        return customerService.getStringTest();
    }
}

文件名:org.pramod.config.CustomerResource.java

package org.pramod.config;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.pramod.model.Customer;
import org.pramod.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;

@Path("customers")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class CustomerResource {

  @Autowired
  CustomerService customerService;

  @GET
  public List<Customer> getCustomers(){
    return customerService.getAllCustomer();
  }

  @GET
  @Path("/{customerId}")
  public Customer getCustomer(@PathParam("customerId") int id){
    return customerService.getCustomerById(id);
  }

  @POST
  public Customer saveCustomer(Customer customer){
    return customerService.addCustomer(customer);
  }

  @PUT
  @Path("/{customerId}")
  public Customer updateCustomer(@PathParam("customerId") int id, Customer customer){
    return customerService.updateCustomer(id, customer);
  }

  @DELETE
  @Path("/{customerId}")
  public Customer removeCustomer(@PathParam ("customerId") int id ){
    return customerService.deleteCustomer(id);
  }
}

这些是 Spring 服务文件和接口。 1. CustomerService 和 2. CustomerServiceImpl

文件名:org.pramod.service.CustomerService.java

package org.pramod.service;

import java.util.List;

import org.pramod.model.Customer;

public interface CustomerService {

    String getStringTest();
    Customer addCustomer(Customer customer);
    Customer updateCustomer(int id, Customer customer);
    Customer deleteCustomer(int id);
    Customer getCustomerById(int id);
    List<Customer> getAllCustomer();
}

文件名:org.pramod.service.CustomerServiceImpl.java

package org.pramod.service;

import java.util.List;

import org.pramod.dao.CustomerDao;
import org.pramod.model.Customer;
import org.springframework.beans.factory.annotation.Autowired;

public class CustomerServiceImpl implements CustomerService {

  @Autowired
  private CustomerDao customerDao; 

  @Override
  public String getStringTest() {
    return customerDao.getStringTest();
  }

  @Override
  public Customer addCustomer(Customer customer) {
    return customerDao.addCustomer(customer);
  }

  @Override
  public Customer updateCustomer(int id, Customer customer) {
    return customerDao.updateCustomer(id, customer);
  }

  @Override
  public Customer deleteCustomer(int id) {
    return customerDao.deleteCustomer(id);
  }

  @Override
  public Customer getCustomerById(int id) {
    return customerDao.getCustomerById(id);
  }

  @Override
  public List<Customer> getAllCustomer() {
    return customerDao.getAllCustomer();
  }
}

这些是 Hibernate 实现文件和接口。

1. CustomerDao 和 2.CustomerDaoImpl.

如果你不想实现 HIBERNATE,那么你可以省略这两个文件并在 applicationContext.xml 文件中删除 ID 为 "dataSource" 和 "sessionFactory" 的 bean .去掉pom.xml

中HIBERNATE的依赖

文件名:org.pramod.dao.CustomerDao.java

package org.pramod.dao;

import java.util.List;

import org.pramod.model.Customer;

public interface CustomerDao {

    String getStringTest();
    Customer addCustomer(Customer customer);
    Customer updateCustomer(int id, Customer customer);
    Customer deleteCustomer(int id);
    Customer getCustomerById(int id);
    List<Customer> getAllCustomer();

}

文件名:org.pramod.dao.CustomerDaoImpl.java

package org.pramod.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.pramod.model.Customer;
import org.springframework.beans.factory.annotation.Autowired;

public class CustomerDaoImpl implements CustomerDao {

  @Autowired
  SessionFactory sessionFactory;

  @Override
  public String getStringTest(){
    String save = "Got it";
    return save;
  }

  @Override
  public Customer addCustomer(Customer customer) {      
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    try{
        session.save(customer);
        tx.commit();
        return customer;
    }catch(Exception e){
        tx.rollback();
        return null;
    }
  }

  @Override
  public Customer updateCustomer(int id, Customer cust) {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    try{
        Customer customer = cust;
        customer.setId(id);
        session.update(customer);
        tx.commit();
        return customer;
    }catch(Exception e){
        tx.rollback();
        return null;
    }
  }

  @Override
  public Customer deleteCustomer(int id) {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    try{
        Customer cust = session.get(Customer.class,id);
        session.delete(cust);
        tx.commit();
        return cust;
    }catch(Exception e){
        tx.rollback();
        return null;
    }
  }

  @Override
  public Customer getCustomerById(int id) {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    try{
        Customer cust = session.get(Customer.class,id);
        tx.commit();
        session.close();
        return cust;
    }catch(Exception e){
        tx.rollback();
        session.close();
        return null;
    }       
  }

  @Override
  public List<Customer> getAllCustomer() {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    try{
        Query query = session.createQuery("from Customer");
        List<Customer> customers = query.list();
        tx.commit();
        session.close();
        return customers;
    }catch(Exception e){
        tx.rollback();
        session.close();
        return null;
    }       
  }

}

这是客户类型的实体或对象。如果您不想使用 Hibernate。删除所有注释

文件名:org.pramod.model.Customer.java

package org.pramod.model;

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

@Entity
@Table(name="CUSTOMER")
public class Customer {

  @Id @GeneratedValue
  @Column(name="customer_id")
  private int id;
  @Column
  private String firstName;
  @Column
  private String lastName;
  @Column
  private String street;
  @Column
  private String city;
  @Column
  private String state;
  @Column
  private int pin;

  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public String getStreet() {
    return street;
  }
  public void setStreet(String street) {
    this.street = street;
  }
  public String getCity() {
    return city;
  }
  public void setCity(String city) {
    this.city = city;
  }
  public String getState() {
    return state;
  }
  public void setState(String state) {
    this.state = state;
  }
  public int getPin() {
    return pin;
  }
  public void setPin(int pin) {
    this.pin = pin;
  }
}