Spring Boot Hibernate示例


在这篇文章中,我们将看到如何创建 Spring Boot Hibernate 示例。

我们将使用 Spring boot 1.5.3 Release 版本,它带有 hibernate 5。我们将创建一个 Spring boot hibernate 应用程序,它将 JSP 作为用户界面。它将提供用户界面,您可以从中添加、更新或删除客户数据库。我们将使用控制器、服务和 DAO 类来实现这些功能。我们将使用休眠的 SessionFactory 类连接到 MySQL 数据库。

Github 源代码:

下载

Spring Boot Hibernate示例:

以下是创建 Spring Boot Hibernate 示例的步骤。

项目结构:

Spring Boot Hibernate 项目结构

用于创建以下项目的工具:

  1. Spring Boot 1.5.3.RELEASE
  2. Spring 4.3.8.RELEASE
  3. Tomcat Embed 8
  4. Maven 3
  5. java 8
  6. Eclipse
  7. hibernate 5.3.5
  8. MySQL 5.7.18

第 1 步: 在 Eclipse 中使用 maven创建一个 名为“SpringBootHibernateExample”的动态 Web 项目。 第二步:修改“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.arpit.java2blog</groupId>
    <artifactId>SpringBootHibernateExample</artifactId>

    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBootHibernateExample Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- JSTL for JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!-- For JSP compilation -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.threeten/threetenbp -->
        <dependency>
            <groupId>org.threeten</groupId>
            <artifactId>threetenbp</artifactId>
            <version>0.7.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>SpringBootHibernateExample</finalName>
    </build>
</project>

spring-boot-starter-parent 为您提供任何 spring 项目所需的所有 maven 默认值。 由于我们正在开发一个 web 应用程序,我们还需要添加 spring-boot-starter-web 依赖项,我们还需要包含 pring-boot-starter-data-jpa 来使用 hibernate 运行这个应用程序。你还需要把 mysql- connector-java 用于 MySql JDBC 驱动程序。如果您使用任何其他数据库,则需要使用不同的数据库连接器。 让我们先进行休眠配置。

hibernate Configuration

第 3 步:在包 .org.arpit.java2blog 中创建一个名为“HibernateConfiguration.java”的文件

package org.arpit.java2blog;  
import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class HibernateConfiguration {
    @Value("${db.driver}")
    private String DRIVER;

    @Value("${db.password}")
    private String PASSWORD;

    @Value("${db.url}")
    private String URL;

    @Value("${db.username}")
    private String USERNAME;

    @Value("${hibernate.dialect}")
    private String DIALECT;

    @Value("${hibernate.show_sql}")
    private String SHOW_SQL;

    @Value("${hibernate.hbm2ddl.auto}")
    private String HBM2DDL_AUTO;

    @Value("${entitymanager.packagesToScan}")
    private String PACKAGES_TO_SCAN;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(DRIVER);
        dataSource.setUrl(URL);
        dataSource.setUsername(USERNAME);
        dataSource.setPassword(PASSWORD);
        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(PACKAGES_TO_SCAN);
        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", DIALECT);
        hibernateProperties.put("hibernate.show_sql", SHOW_SQL);
        hibernateProperties.put("hibernate.hbm2ddl.auto", HBM2DDL_AUTO);
        sessionFactory.setHibernateProperties(hibernateProperties);

        return sessionFactory;
    }

    @Bean
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory().getObject());
        return transactionManager;
    }  
}

上面的类使用@Configuration 和@Bean 注解进行了注解。这些注解用于在 Spring 中定义 bean。

@Configuration类似于Spring XML 配置中 标记, @ Bean 类似于 标记。

@Value注释用于从属性文件中注入变量。在这种情况下,它将从我们将在下一步创建的 application.properties 中读取。

第 4 步:在包 /src/main/resources 中创建一个名为“application.properties”的文件

spring.mvc.view.prefix: /WEB-INF/
spring.mvc.view.suffix: .jsp

logging.level=DEBUG
# Database
db.driver: com.mysql.jdbc.Driver
db.url: jdbc:mysql://localhost:3306/CustomerData
db.username: root
db.password: admin

# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: create
entitymanager.packagesToScan: org

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

Model class

第 5 步:在包 .org.arpit.java2blog.model 中创建一个名为“Customer.java”的文件

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 Customer table in database
*/
@Entity
@Table(name="CUSTOMER")
public class Customer{

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

    @Column(name="customerName")
    String customerName;
     @Column(name="email")
    String email;

    public Customer() {
        super();
    }
    public Customer(String customerName,String email) {
        super();
        this.customerName=customerName;
        this.email=email;
    }
    public String getCustomerName() {
        return customerName;
    }
    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

}

@Entity 用于制作持久化 pojo 类。对于这个 java 类,您将在数据库中拥有相应的表。@Column 用于将带注释的属性映射到表中的相应列。

Create Customer table:

使用以下 DDL 在数据库中创建客户表。

CREATE TABLE CUSTOMER (
id int(11) NOT NULL AUTO_INCREMENT,
customerName varchar(255) DEFAULT NULL,
email varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
)

Controller class

第 6 步:在包 .org.arpit.java2blog.controller 中创建一个名为“CustomerController.java”的文件

package org.arpit.java2blog.controller;

import java.util.List;

import org.arpit.java2blog.model.Customer;
import org.arpit.java2blog.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class CustomerController {

    @Autowired
    CustomerService customerService;

    @RequestMapping(value = "/getAllCustomers", method = RequestMethod.GET, headers = "Accept=application/json")
    public String getAllCustomers(Model model) {

        List<Customer> listOfCustomers = customerService.getAllCustomers();
        model.addAttribute("customer", new Customer());
        model.addAttribute("listOfCustomers", listOfCustomers);
        return "customerDetails";
    }

    @RequestMapping(value = "/", method = RequestMethod.GET, headers = "Accept=application/json")
    public String goToHomePage() {
        return "redirect:/getAllCustomers";
    }

    @RequestMapping(value = "/getCustomer/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
    public Customer getCustomerById(@PathVariable int id) {
        return customerService.getCustomer(id);
    }

    @RequestMapping(value = "/addCustomer", method = RequestMethod.POST, headers = "Accept=application/json")
    public String addCustomer(@ModelAttribute("customer") Customer customer) {  
        if(customer.getId()==0)
        {
            customerService.addCustomer(customer);
        }
        else
        {  
            customerService.updateCustomer(customer);
        }

        return "redirect:/getAllCustomers";
    }

    @RequestMapping(value = "/updateCustomer/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
    public String updateCustomer(@PathVariable("id") int id,Model model) {
        model.addAttribute("customer", this.customerService.getCustomer(id));
        model.addAttribute("listOfCustomers", this.customerService.getAllCustomers());
        return "customerDetails";
    }

    @RequestMapping(value = "/deleteCustomer/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
    public String deleteCustomer(@PathVariable("id") int id) {
        customerService.deleteCustomer(id);
        return "redirect:/getAllCustomers";

    }  
}

Service Layer

第 7 步:在包 .org.arpit.java2blog.service 中创建一个名为“CustomerService.java”的文件

package org.arpit.java2blog.service;

import java.util.List;

import javax.transaction.Transactional;

import org.arpit.java2blog.dao.CustomerDao;
import org.arpit.java2blog.springboot.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("customerService")
public class CustomerService {

    @Autowired
    CustomerDao customerDao;

    @Transactional
    public List<Customer> getAllCustomers() {
        return customerDao.getAllCustomers();
    }

    @Transactional
    public Customer getCustomer(int id) {
        return customerDao.getCustomer(id);
    }

    @Transactional
    public void addCustomer(Customer customer) {
        customerDao.addCustomer(customer);
    }

    @Transactional
    public void updateCustomer(Customer customer) {
        customerDao.updateCustomer(customer);

    }

    @Transactional
    public void deleteCustomer(int id) {
        customerDao.deleteCustomer(id);
    }
}

DAO层

第 8 步:在包 .org.arpit.java2blog.dao 中创建一个名为“CustomerDao.java”的接口

package org.arpit.java2blog.dao;

import java.util.List;

import org.arpit.java2blog.springboot.Customer;

public interface CustomerDao {
    public List<Customer> getAllCustomers() ;

    public Customer getCustomer(int id) ;

    public Customer addCustomer(Customer customer);

    public void updateCustomer(Customer customer) ;

    public void deleteCustomer(int id) ;
}

第 9 步:在包 .org.arpit.java2blog.dao 中创建一个名为“CustomerDaoImpl.java”的文件

package org.arpit.java2blog.dao;

import java.util.List;

import org.arpit.java2blog.springboot.Customer;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class CustomerDaoImpl implements CustomerDao{

    @Autowired
    private SessionFactory sessionFactory;

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

    public List<Customer> getAllCustomers() {
        Session session = this.sessionFactory.getCurrentSession();
        List<Customer>  customerList = session.createQuery("from Customer").list();
        return customerList;
    }

    public Customer getCustomer(int id) {
        Session session = this.sessionFactory.getCurrentSession();
        Customer customer = (Customer) session.get(Customer.class, id);
        return customer;
    }

    public Customer addCustomer(Customer customer) {
        Session session = this.sessionFactory.getCurrentSession();
        session.save(customer);
        return customer;
    }

    public void updateCustomer(Customer customer) {
        Session session = this.sessionFactory.getCurrentSession();
        session.update(customer);
    }

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

意见

第 10 步:在包 /WEB-INF/ 中创建一个名为“customerDetails.jsp”的文件

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
<style>          
.blue-button{
    background: #25A6E1;
    filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#25A6E1',endColorstr='#188BC0',GradientType=0);
    padding:3px 5px;
    color:#fff;
    font-family:'Helvetica Neue',sans-serif;
    font-size:12px;
    border-radius:2px;
    -moz-border-radius:2px;
    -webkit-border-radius:4px;
    border:1px solid #1A87B9
}    
table {
  font-family: "Helvetica Neue", Helvetica, sans-serif;
   width: 50%;
}
th {
  background: SteelBlue;
  color: white;
}
td,th{
                border: 1px solid gray;
                width: 25%;
                text-align: left;
                padding: 5px 10px;
            }
</style>
</head>
<body>
<form:form method="post" modelAttribute="customer" action="${pageContext.request.contextPath}/addCustomer">
<table>
        <tr>
            <th colspan="2">Add Customer</th>
        </tr>
        <tr>
    <form:hidden path="id" />
          <td><form:label path="customerName">Customer Name:</form:label></td>
          <td><form:input path="customerName" size="30" maxlength="30"></form:input></td>
        </tr>
        <tr>
                <td><form:label path="email">Email:</form:label></td>
          <td><form:input path="email" size="30" maxlength="30"></form:input></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit"
                class="blue-button" /></td>
        </tr>
    </table>
</form:form>
</br>
<h3>Customer List</h3>
<c:if test="${!empty listOfCustomers}">
    <table class="tg">
    <tr>
        <th width="80">Id</th>
        <th width="120">Customer Name</th>
        <th width="120">Email</th>
        <th width="60">Edit</th>
        <th width="60">Delete</th>
    </tr>
    <c:forEach items="${listOfCustomers}" var="customer">
        <tr>
            <td>{customer.id}</td>
            <td>${customer.customerName}</td>
            <td>${customer.email}</td>
            <td><a href="<c:url value='/updateCustomer/${customer.id}' />" >Edit</a></td>
            <td><a href="<c:url value='/deleteCustomer/${customer.id}' />" >Delete</a></td>
        </tr>
    </c:forEach>
    </table>
</c:if>
</body>
</html>

spring启动主文件

第 11 步:在包 .org.arpit.java2blog 中创建一个名为“SpringBootHibernateApplication.java”的文件

package org.arpit.java2blog;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootHibernateApplication {

    public static void main(String[] args)
    {
        SpringApplication.run(SpringBootHibernateApplication.class, args);  
    }
}

我们刚刚添加了@SpringBootApplication,它完成了所有工作。 让我们更多地了解这个注释。 @SpringBootApplication是一个注释,它添加了以下所有内容:

@Configuration使该类成为应用程序上下文的 bean 定义的来源。 @EnableAutoConfiguration使 Spring Boot 能够添加存在于类路径设置和各种属性设置中的 bean。 通常你会为 Spring MVC 应用程序添加 @EnableWebMvc,但是当 Spring Boot 在类路径上看到 spring-webmvc 时会自动添加它。 这会将应用程序标记为 Web 应用程序并激活关键行为,例如设置 DispatcherServlet。

@ComponentScan 告诉 Spring 在默认包中查找其他组件、配置和服务,使其能够找到控制器。 如果未定义特定的包,则将从声明此注解的类的包中进行扫描。

运行应用程序

第12步:是时候做maven build了。

右键单击项目 -> 运行方式 -> Maven 构建 img 第 13 步:提供目标作为全新安装 spring-boot:run(如下所示)并单击运行

Spring Boot Hibernate Maven 构建

第 14 步:完成 Maven 构建后,让我们转到浏览器并输入以下 URL。

http://localhost:8080/getAllCustomers

您将看到下面的屏幕。

Spring boot 客户空白页

将以下详细信息添加到客户名称:作为“John”并发送电子邮件为“ John@gmail.com ”,然后单击提交。

Spring boot Hibernate 添加客户

现在我正在使用上述方法添加更多客户。

Spring Boot Hibernate 添加客户

让我们单击与名为 David 的客户 ID :3 对应的编辑链接。

我正在将电子邮件地址从“ david@gmail.com ”更改为“ change@gmail.com ”

Spring Boot Hibernate 编辑客户

当您单击提交时,您将看到以下屏幕。

Spring Boot Hibernate 编辑客户 2

如您所见,David 的电子邮件地址已更改为“ change@gmail.com ”。

让我们单击与名为 Martin 的客户 id :2 对应的删除链接,您将看到下面的屏幕。

Spring Boot Hibernate 删除客户

如您所见,Martin 已从列表中删除。

这就是 Spring Boot Hibernate 示例的全部内容。


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