Spring JPA数据+Hibernate+ MySQL + Maven
在Spring MVC的幫助下開發(fā)Web應(yīng)用程序意味著要創(chuàng)建幾個邏輯架構(gòu)層。 層之一是DAO(存儲庫)層。 它負(fù)責(zé)與數(shù)據(jù)庫進(jìn)行通信。 如果您至少開發(fā)了DAO層一次,則應(yīng)該知道它涉及許多樣板代碼。 Spring Data本身就是與DAO相關(guān)的日常工作的一部分。
在帖子中,我將提供一個應(yīng)用程序示例,它將結(jié)合Spring MVC,MySQL和Maven演示Spring Data(JPA) 。 Hibernate將用作JPA的實現(xiàn)。 您可能知道,我是基于Java的配置的忠實擁護(hù)者,因此我將使用這種方法來配置Spring Data。 在本教程的最后,您可以找到GitHub上示例項目的鏈接。
制備
在本文中,我將重點(diǎn)介紹Spring數(shù)據(jù),因此我將忽略所有超出主題的內(nèi)容。 但首先,我想提供大量鏈接,這些鏈接可以在本教程的上下文中為您提供幫助。
- 使用Maven在Eclipse中創(chuàng)建動態(tài)Web項目 。
- 具有基于Java配置的簡單Spring MVC應(yīng)用程序 。
- Spring MVC + Hibernate示例應(yīng)用程序。
這些鏈接應(yīng)針對閱讀文章期間可能發(fā)生的90%的問題給出答案。 讓我們從在MySQL中創(chuàng)建表開始:
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;現(xiàn)在,我們可以繼續(xù)執(zhí)行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數(shù)據(jù)的配置
我相信該項目的屏幕截圖將幫助您了解發(fā)生了什么。
在屬性文件中集中所有配置數(shù)據(jù):
#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.modelWebAppConfig類包含所有基于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實現(xiàn)。
初始化類將被省略。
DAO和服務(wù)層
Shop實體的存儲庫:
package com.spr.repository;import org.springframework.data.jpa.repository.JpaRepository;import com.spr.model.Shop;public interface ShopRepository extends JpaRepository<shop, integer=""> {}無疑,它是本教程中最簡單的代碼段。 但這需要最高的關(guān)注。 JpaRepository接口包含可以用任何實體執(zhí)行的基本操作(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);}并實現(xiàn)服務(wù)接口:
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是非常強(qiáng)大的武器,它可以幫助您更快地開發(fā)應(yīng)用程序,并避免數(shù)百個樣板代碼字符串。 使用Spring Data是在應(yīng)用程序中創(chuàng)建DAO層的最便捷方法,因此請不要在項目中忽略它。 
翻譯自: https://www.javacodegeeks.com/2013/05/spring-jpa-data-hibernate-mysql-maven.html
總結(jié)
以上是生活随笔為你收集整理的Spring JPA数据+Hibernate+ MySQL + Maven的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 朋友圈设置一个月可见怎么设置
- 下一篇: X-Mas Musings –在Grai
