Spring Rest Hibernate示例


在这篇文章中,我们将扩展相同的示例并将其与hibernatemysql集成。 我们将使用以下注释进行 CRUD 操作。

方法 描述
Get 它用于读取资源
Post 它用于创建新资源。 它不是幂等方法
Put 它通常用于更新资源。是幂等方法
Delete 用于删除资源

Idempotent 是指多次请求成功的结果在初次申请后不会改变资源状态 例如: delete是幂等的方法,因为当你第一次使用delete时,它会删除资源(初次申请),但之后所有其他请求都没有结果,因为资源已被删除。

Post 不是幂等方法,因为当你使用 post 创建资源时,它会不断为每个新请求创建资源,因此多次成功请求的结果不会相同。

源代码:

下载Spring rest hibernate 示例

以下是使用休眠集成创建 Spring Restful Web 服务的步骤。

1) 在 Eclipse 中使用 maven创建一个 名为“SpringRestHibernateExample”的动态 Web 项目

Maven 依赖项

2) 我们需要在类路径中添加 Jackson json 实用程序。

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
             <version>2.4.1</version>
</dependency>

Spring 会自动将 Jackson2JsonMessageConverter 加载到其应用程序上下文中。每当您使用 accept headers=”Accept=application/json” 以 json 格式请求资源时,Jackson2JsonMessageConverter 就会出现并将资源转换为 json 格式。 现在改变 pom.xml 如下: 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>com.arpit.java2blog</groupId>
<artifactId>SpringRestHibernateExample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringRestHibernateExample Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.4.1</version>
  </dependency>
  <!-- Hibernate -->
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>${hibernate.version}</version>
  </dependency>
  <dependency>
     <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>${hibernate.version}</version>
  </dependency>

  <!-- Apache Commons DBCP -->
  <dependency>
   <groupId>commons-dbcp</groupId>
   <artifactId>commons-dbcp</artifactId>
   <version>1.4</version>
  </dependency>
  <!-- Spring ORM -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>${spring.version}</version>
  </dependency>

  <!-- AspectJ -->
  <dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjrt</artifactId>
   <version>${org.aspectj-version}</version>
  </dependency>
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
  </dependency>
</dependencies>
<build>
  <finalName>SpringRestHibernateExample</finalName>

  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
     <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
   </plugin>
  </plugins>

</build>
<properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <security.version>4.0.3.RELEASE</security.version>
  <jdk.version>1.7</jdk.version>
  <hibernate.version>4.3.5.Final</hibernate.version>
  <org.aspectj-version>1.7.4</org.aspectj-version>
</properties>
</project>

4) 在 /WEB-INF/ 文件夹中创建一个名为 spring-servlet.xml 的 xml 文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
  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-4.0.xsd">

<annotation-driven />

<resources mapping="/resources/**" location="/resources/" />

<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <beans:property name="url"
   value="jdbc:mysql://localhost:3306/CountryData" />
     <beans:property name="username" value="root" />
  <beans:property name="password" value="" />
</beans:bean>

<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory"
  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  <beans:property name="dataSource" ref="dataSource" />
  <beans:property name="annotatedClasses">
   <beans:list>
    <beans:value>org.arpit.java2blog.model.Country</beans:value>
   </beans:list>
  </beans:property>
  <beans:property name="hibernateProperties">
   <beans:props>
    <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
    </beans:prop>
    <beans:prop key="hibernate.show_sql">true</beans:prop>
   </beans:props>
  </beans:property>
</beans:bean>

<context:component-scan base-package="org.arpit.java2blog" />

<tx:annotation-driven transaction-manager="transactionManager"/>

<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>

</beans:beans>

在 Spring-servlet.xml 中,我们已经完成了休眠配置。 dataSource bean 用于指定java 数据源。我们需要提供驱动程序、URL、用户名和密码。 transactionManager bean 用于配置休眠事务管理器。hibernate4AnnotatedSessionFactory bean 用于配置创建 Hibernate SessionFactory 的 FactoryBean。这是在 Spring 应用程序上下文中设置共享 Hibernate SessionFactory 的常用方法,因此您可以使用此 SessionFactory 来注入 Hibernate 数据访问对象。

创建 bean 类

4) 在 org.arpit.java2blog.bean 中创建一个名为“Country.java”的 bean。

package org.arpit.java2blog.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;

/*
* This is our model class and it corresponds to Country table in database
*/
@Entity
@Table(name="COUNTRY")
public class Country{

    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int id;

    @Column(name="countryName")
    String countryName;

    @Column(name="population")
    long population;

    public Country() {
        super();
    }
    public Country(int i, String countryName,long population) {
        super();
        this.id = i;
        this.countryName = countryName;
        this.population=population;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public long getPopulation() {
        return population;
    }
    public void setPopulation(long population) {
        this.population = population;
    }

}

@Entity用于制作持久化 pojo 类。对于这个 java 类,您将在数据库中拥有相应的表。@Column 用于将带注释的属性映射到表中的相应列。因此,使用以下代码在 mysql 数据库中创建 Country 表:

CREATE TABLE COUNTRY
(
   id int PRIMARY KEY NOT NULL AUTO_INCREMENT,
   countryName varchar(100) NOT NULL,
   population int NOT NULL
)
;

创建控制器

5)在包**org.arpit.java2blog.controller** 中创建一个名为“CountryController.java”的控制器

package org.arpit.java2blog.controller;

import java.util.List;
import org.arpit.java2blog.model.Country;
import org.arpit.java2blog.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CountryController {

    @Autowired
    CountryService countryService;

    @RequestMapping(value = "/getAllCountries", method = RequestMethod.GET, headers = "Accept=application/json")
    public List getCountries() {

        List listOfCountries = countryService.getAllCountries();
        return listOfCountries;
    }

    @RequestMapping(value = "/getCountry/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
    public Country getCountryById(@PathVariable int id) {
        return countryService.getCountry(id);
    }

    @RequestMapping(value = "/addCountry", method = RequestMethod.POST, headers = "Accept=application/json")
    public void addCountry(@RequestBody Country country) {
        countryService.addCountry(country);

    }

    @RequestMapping(value = "/updateCountry", method = RequestMethod.PUT, headers = "Accept=application/json")
    public void updateCountry(@RequestBody Country country) {
        countryService.updateCountry(country);
    }

    @RequestMapping(value = "/deleteCountry/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
    public void deleteCountry(@PathVariable("id") int id) {
        countryService.deleteCountry(id);
    }
}

创建 DAO 类

在包 org.arpit.java2blog.dao 中创建一个CountryDAO.java类。此类将在与数据库交互时执行休眠语句。

package org.arpit.java2blog.dao;

import java.util.List;

import org.arpit.java2blog.model.Country;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class CountryDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sf) {
        this.sessionFactory = sf;
    }

    public List getAllCountries() {
        Session session = this.sessionFactory.getCurrentSession();
        List countryList = session.createQuery("from Country").list();
        return countryList;
    }

    public Country getCountry(int id) {
        Session session = this.sessionFactory.getCurrentSession();
        Country country = (Country) session.load(Country.class, new Integer(id));
        return country;
    }

    public Country addCountry(Country country) {
        Session session = this.sessionFactory.getCurrentSession();
        session.persist(country);
        return country;
    }

    public void updateCountry(Country country) {
        Session session = this.sessionFactory.getCurrentSession();
        session.update(country);
    }

    public void deleteCountry(int id) {
        Session session = this.sessionFactory.getCurrentSession();
        Country p = (Country) session.load(Country.class, new Integer(id));
        if (null != p) {
            session.delete(p);
        }
    }
}

@Repository 是专门的组件注解,用于在 DAO 层创建 bean。我们使用 Autowired 注解将休眠 SessionFactory 注入 CountryDAO 类。我们已经在 Spring-Servlet.xml 文件中配置了休眠 SessionFactory 对象。

创建服务类

6)在包**org.arpit.java2blog.service** 中创建一个类 CountryService.java ,它是服务级类。它将调用 DAO 层类。

package org.arpit.java2blog.service;

import java.util.List;
import org.arpit.java2blog.dao.CountryDAO;
import org.arpit.java2blog.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("countryService")
public class CountryService {

    @Autowired
    CountryDAO countryDao;

    @Transactional
    public List getAllCountries() {
        return countryDao.getAllCountries();
    }

    @Transactional
    public Country getCountry(int id) {
        return countryDao.getCountry(id);
    }

    @Transactional
    public void addCountry(Country country) {
        countryDao.addCountry(country);
    }

    @Transactional
    public void updateCountry(Country country) {
        countryDao.updateCountry(country);

    }

    @Transactional
    public void deleteCountry(int id) {
        countryDao.deleteCountry(id);
    }
}

@Service 是专门的组件注解,用于在 Service 层创建 bean。 7) 是时候做 Maven 构建了。

右键单击项目-> 运行方式-> Maven 构建

Maven 在 Eclipse 中构建

8) 提供全新安装的目标(如下所示),然后单击运行

Maven 在 Eclipse 中构建

运行应用程序

9) 右键单击项目->运行为->在服务器上运行

选择apache tomcat并点击finish

img

10) 我们将在 postman中测试这个应用程序 ,基于 UI 的客户端来测试 restful web 应用程序。它是 chrome 插件。启动邮递员。如果您想要基于 java 的客户端,那么您还可以使用 如何在 java 中发送 get 或 post 请求。

发布方法

12) Post 方法用于创建新资源。在这里,我们将新的 Country India 添加到国家/地区列表中,因此您可以看到我们在帖子正文中使用了新的国家/地区 json。 URL:http://localhost:8080/SpringRestHibernateExample/addCountry”。

img

让我们看看数据库中 Country 表中的相应条目。

img

让我们以类似的方式再创建 3 个国家,即中国、尼泊尔和美国。

放置方法

13) Put 方法用于更新资源。这里将使用 put 方法更新尼泊尔的人口。 我们将在请求正文中更新国家/地区 json。 网址:http://localhost:8080/SpringRestHibernateExample/updateCountry”

img

让我们在数据库中检查尼泊尔的人口。

img

删除方法

14) Delete方法用于删除资源。我们将需要删除的国家ID作为PathParam传递。我们将删除 id:3 即尼泊尔来演示删除方法。

网址:http://localhost:8080/SpringRestHibernateExample/deleteCountry/3”

img

现在让我们检查数据库中的条目。

img

如您所见,我们删除 了 id 为 3 的国家,即尼泊尔

项目结构:

img

我们完成了 Spring Restful Web 服务 json CRUD 示例。如果您仍然遇到任何问题,请发表评论。

如果您在上述步骤中遇到 404 错误,您可能需要按照以下步骤操作:

**1)** 如果您在 Tomcat 启动控制台日志中收到此警告,则可能会导致问题

警告:[SetPropertiesRule]{Server/Service/Engine/Host/Context} 将属性 'source' 设置为 'org.eclipse.jst.j2ee.server: JAXRSJsonCRUDExample' 没有找到匹配的属性。

这个特定的警告基本上意味着 Tomcat 的 server.xml 中的元素包含未知的属性源,并且 Tomcat 不知道如何处理该属性,因此将忽略它。

要在eclipse中解决这个问题,

从服务器视图中从服务器中删除项目。右键单击服务器->添加和删除

img

然后从服务器配置中删除项目。

然后在同一台服务器下运行项目。现在应该删除警告

或者如果警告仍然存在,那么

  • 转到服务器视图
  • 双击您的 Tomcat 服务器。它将打开服务器配置。
  • 在服务器选项下选中“将模块内容发布到单独的 XML 文件”复选框。
  • 重新启动您的服务器。这次您的页面将没有任何问题。

2) 尝试更新Maven项目。

右键项目->Maven->更新项目

更新 Maven 项目

然后

img

这应该可以解决您的问题。


原文链接:https://codingdict.com/