在Spring MVC的帮助下开发Web应用程序意味着要创建几个逻辑架构层。 层之一是DAO(存储库)层。 它负责与数据库进行通信。 如果您至少开发了DAO层一次,则应该知道它涉及许多样板代码。 Spring Data本身就是与DAO相关的日常工作的一部分。

在帖子中,我将提供一个应用程序示例,它将结合Spring MVC,MySQL和Maven演示Spring Data(JPA)Hibernate将用作JPA的实现。 您可能知道,我是基于Java的配置的忠实拥护者,因此我将使用这种方法来配置Spring Data。 在本教程的最后,您可以找到GitHub上示例项目的链接。

制备

在本文中,我将重点介绍Spring数据,因此我将忽略所有超出主题的内容。 但首先,我想提供大量链接,这些链接可以在本教程的上下文中为您提供帮助。

  • 使用Maven在Eclipse中创建动态Web项目 。
  • 具有基于Java配置的简单Spring MVC应用程序 。
  • Spring MVC + Hibernate示例应用程序。

这些链接应针对阅读文章期间可能发生的90%的问题给出答案。 让我们从在MySQL中创建表开始:

CREATE TABLE `shops` (`id` int(6) NOT NULL AUTO_INCREMENT,`name` varchar(60) NOT NULL,`employees_number` int(6) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

现在,我们可以继续执行Java代码:

@Entity
@Table(name = "shops")
public class Shop {@Id@GeneratedValueprivate Integer id;private String name;@Column(name = "employees_number")private Integer emplNumber;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getEmplNumber() {return emplNumber;}public void setEmplNumber(Integer emplNumber) {this.emplNumber = emplNumber;}
}

Spring数据的配置

我相信该项目的屏幕截图将帮助您了解发生了什么。

在属性文件中集中所有配置数据:

#DB properties:
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/hibnatedb
db.username=hibuser
db.password=root#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
entitymanager.packages.to.scan=com.spr.model

WebAppConfig类包含所有基于Java的配置:

@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan("com.spr")
@PropertySource("classpath:application.properties")
@EnableJpaRepositories("com.spr.repository")
public class WebAppConfig {private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";private static final String PROPERTY_NAME_DATABASE_URL = "db.url";private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";@Resourceprivate Environment env;@Beanpublic DataSource dataSource() {DriverManagerDataSource dataSource = new DriverManagerDataSource();dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));return dataSource;}@Beanpublic LocalContainerEntityManagerFactoryBean entityManagerFactory() {LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();entityManagerFactoryBean.setDataSource(dataSource());entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class);entityManagerFactoryBean.setPackagesToScan(env.
getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));entityManagerFactoryBean.setJpaProperties(hibProperties());return entityManagerFactoryBean;}private Properties hibProperties() {Properties properties = new Properties();properties.put(PROPERTY_NAME_HIBERNATE_DIALECT,    env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));return properties;}@Beanpublic JpaTransactionManager transactionManager() {JpaTransactionManager transactionManager = new JpaTransactionManager();transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());return transactionManager;}@Beanpublic UrlBasedViewResolver setupViewResolver() {UrlBasedViewResolver resolver = new UrlBasedViewResolver();resolver.setPrefix("/WEB-INF/pages/");resolver.setSuffix(".jsp");resolver.setViewClass(JstlView.class);return resolver;}}

请注意@EnableJpaRepositories批注。 它允许使用JPA存储库。 com.spr.repository软件包将被扫描以检测存储库。 在entityManagerFactory bean中,我确定将Hibernate用作JPA实现。

初始化类将被省略。

DAO和服务层

Shop实体的存储库:

package com.spr.repository;import org.springframework.data.jpa.repository.JpaRepository;import com.spr.model.Shop;public interface ShopRepository extends JpaRepository<shop, integer=""> {}

无疑,它是本教程中最简单的代码段。 但这需要最高的关注。 JpaRepository接口包含可以用任何实体执行的基本操作(CRUD操作)。 您可以在官方文档页面上找到更多信息。

这是ShopService接口的代码:

public interface ShopService {public Shop create(Shop shop);public Shop delete(int id) throws ShopNotFound;public List findAll();public Shop update(Shop shop) throws ShopNotFound;public Shop findById(int id);}

并实现服务接口:

import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import com.spr.exception.ShopNotFound;
import com.spr.model.Shop;
import com.spr.repository.ShopRepository;@Service
public class ShopServiceImpl implements ShopService {@Resourceprivate ShopRepository shopRepository;@Override@Transactionalpublic Shop create(Shop shop) {Shop createdShop = shop;return shopRepository.save(createdShop);}@Override@Transactionalpublic Shop findById(int id) {return shopRepository.findOne(id);}@Override@Transactional(rollbackFor=ShopNotFound.class)public Shop delete(int id) throws ShopNotFound {Shop deletedShop = shopRepository.findOne(id);if (deletedShop == null)throw new ShopNotFound();shopRepository.delete(deletedShop);return deletedShop;}@Override@Transactionalpublic List findAll() {return shopRepository.findAll();}@Override@Transactional(rollbackFor=ShopNotFound.class)public Shop update(Shop shop) throws ShopNotFound {Shop updatedShop = shopRepository.findOne(shop.getId());if (updatedShop == null)throw new ShopNotFound();updatedShop.setName(shop.getName());updatedShop.setEmplNumber(shop.getEmplNumber());return updatedShop;}}

这样,就可以使用ShopRepository。

控制者

最后,我可以在控制器中使用ShopSrviceImpl类。 所有JSP页面将被省略,因此您可以在GitHub上找到它们的源代码。

@Controller
@RequestMapping(value="/shop")
public class ShopController {@Autowiredprivate ShopService shopService;@RequestMapping(value="/create", method=RequestMethod.GET)public ModelAndView newShopPage() {ModelAndView mav = new ModelAndView("shop-new", "shop", new Shop());return mav;}@RequestMapping(value="/create", method=RequestMethod.POST)public ModelAndView createNewShop(@ModelAttribute Shop shop, final RedirectAttributes redirectAttributes) {ModelAndView mav = new ModelAndView();String message = "New shop "+shop.getName()+" was successfully created.";shopService.create(shop);mav.setViewName("redirect:/index.html");redirectAttributes.addFlashAttribute("message", message);    return mav;     }@RequestMapping(value="/list", method=RequestMethod.GET)public ModelAndView shopListPage() {ModelAndView mav = new ModelAndView("shop-list");List shopList = shopService.findAll();mav.addObject("shopList", shopList);return mav;}@RequestMapping(value="/edit/{id}", method=RequestMethod.GET)public ModelAndView editShopPage(@PathVariable Integer id) {ModelAndView mav = new ModelAndView("shop-edit");Shop shop = shopService.findById(id);mav.addObject("shop", shop);return mav;}@RequestMapping(value="/edit/{id}", method=RequestMethod.POST)public ModelAndView editShop(@ModelAttribute Shop shop,@PathVariable Integer id,final RedirectAttributes redirectAttributes) throws ShopNotFound {ModelAndView mav = new ModelAndView("redirect:/index.html");String message = "Shop was successfully updated.";shopService.update(shop);redirectAttributes.addFlashAttribute("message", message);   return mav;}@RequestMapping(value="/delete/{id}", method=RequestMethod.GET)public ModelAndView deleteShop(@PathVariable Integer id,final RedirectAttributes redirectAttributes) throws ShopNotFound {ModelAndView mav = new ModelAndView("redirect:/index.html");      Shop shop = shopService.delete(id);String message = "The shop "+shop.getName()+" was successfully deleted.";redirectAttributes.addFlashAttribute("message", message);return mav;}}

摘要

Spring Data是非常强大的武器,它可以帮助您更快地开发应用程序,并避免数百个样板代码字符串。 使用Spring Data是在应用程序中创建DAO层的最便捷方法,因此请不要在项目中忽略它。

参考: Fruzenshtein的笔记博客中的Spring JPA Data + Hibernate + MySQL + Maven,来自我们的JCG合作伙伴 Alexey Zvolinskiy。

翻译自: https://www.javacodegeeks.com/2013/05/spring-jpa-data-hibernate-mysql-maven.html

Spring JPA数据+Hibernate+ MySQL + Maven相关推荐

  1. Spring JPA数据+休眠+ MySQL + Maven

    在Spring MVC的帮助下开发Web应用程序意味着要创建几个逻辑架构层. 层之一是DAO(存储库)层. 它负责与数据库进行通信. 如果您至少开发了DAO层一次,则应该知道它涉及许多样板代码. Sp ...

  2. hibernate mysql 读写分离_SpringBoot集成Spring Data JPA及读写分离

    JPA是什么 JPA(Java Persistence API)是Sun官方提出的Java持久化规范,它为Java开发人员提供了一种对象/关联映射工具 来管理Java应用中的关系数据.它包括以下几方面 ...

  3. 一文搞懂 Spring JPA

    作者 | 阿文 责编 | 屠敏 什么是 JPA 大家好,今天我和大家聊一下关于Spring JPA 的相关知识,我们先来了解下什么是 JPA ? JPA (Java Persistence API) ...

  4. Spring JPA 开启原生sql打印

    2019独角兽企业重金招聘Python工程师标准>>> 原生spring项目,使用配置文件(非Spring boot项目) <!-- 配置EntityManagerFactor ...

  5. hibernate mysql 注解_【译】Spring 4 + Hibernate 4 + Mysql + Maven集成例子(注解 + XML)

    前言 本文将基于注解配置, 集成Spring 4和Hibernate 4,开发一个增删改查应用,涉及以下内容: 创建Hibernate实体 保存数据到mysql数据库中 在事务transaction内 ...

  6. Spring 4 MVC+Hibernate 4+MySQL+Maven使用注解集成实例

    Spring 4 MVC+Hibernate 4+MySQL+Maven使用注解集成实例 转自:通过注解的方式集成Spring 4 MVC+Hibernate 4+MySQL+Maven,开发项目样例 ...

  7. 【Spring 数据访问终篇】Spring + Hibernate + Mysql

    说来惭愧,数月没有更新博客,今天带来spring访问数据的最终篇,spring + hibernate. 本篇文章将用maven创建一个简答的java项目,并结合spring框架中的hibernate ...

  8. gwt-2.8.2下载_GWT 2 Spring 3 JPA 2 Hibernate 3.5教程– Eclipse和Maven 2展示

    gwt-2.8.2下载 不久前,我的一个朋友和同事向我飞过,说"世界上只有一半在使用Maven ". 当我意识到最受欢迎的文章(到目前为止) GWT 2 Spring 3 JPA ...

  9. GWT 2 Spring 3 JPA 2 Hibernate 3.5教程– Eclipse和Maven 2展示

    不久前,我的一个朋友和同事向我飞过,说"世界上只有一半在使用Maven ". 当我意识到最受欢迎的文章(到目前为止) GWT 2 Spring 3 JPA 2 Hibernate ...

最新文章

  1. Linux图形分区编辑器 GParted Live 1.0 Beta 发布
  2. 如何利用cnocr 识别七段数码?
  3. 企业价值观念形成的四个阶段
  4. linux ssh 隧道 tunnel 一般场景用法
  5. 机器学习入门学习笔记:(4.1)SVM算法
  6. 【英语天天读】I want I do I get
  7. Tengine HTTPS原理解析、实践与调试【转】
  8. matplotlib.patches.Polygon
  9. 【 58沈剑 架构师之路】4种事务的隔离级别,InnoDB如何巧妙实现?
  10. cve-2018-2893 WebLogic
  11. Ubuntu安装FreeSWITCH亲测
  12. 基于SSM高校教师教务信息管理系统
  13. This request has been blocked; the content must be served over HTTPS
  14. 【汇正财经】两市缩量下跌
  15. 计算机excel中钱的符号,在excel中输入钱的符号
  16. 抗渗等级p6是什么意思_抗渗等级P6什么意思?
  17. C# winform Excel导入保存数据两种方法
  18. 算法基础部分-二叉树
  19. uni-app 开发微信公众号(H5)JSSDK 的使用方式
  20. html手机输入框键盘弹起顶起背景图

热门文章

  1. SpringBoot shedlock MongoDb锁配置
  2. dayjs​​​​​​​文档
  3. 数据库 - 事务管理(ACID)隔离级别 事务传播行为
  4. Spring 获取 request 的几种方法及其线程安全性分析
  5. 从Java类到对象的创建过程都做了些啥?内存中的对象是啥样的?
  6. mysq和mysqli关系
  7. 单例模式懒汉式(线程安全写法)
  8. 微信消息提醒与消息数字提示之BadgeView
  9. 实现滚到div时淡入效果
  10. apache.camel_Apache Camel 3.1 – XML路由的快速加载