JUGLviv

Meta


Share on:


Spring Data (JPA)

juglvivjuglviv
Spring-Data
Development of web-applications with the help of Spring MVC implies creation of several logical layers of architecture. One of the layers is a DAO (Repository) layer. It is responsible for communication with a database. If you developed the DAO layer at least once, you should know that it involves a lot of boilerplate code. A Spring Data take a part of the routine job related to the DAO on itself.

In the post I’m going to provide an example of application which will demonstrateSpring Data (JPA) in conjunction with Spring MVC, MySQL and Maven.Hibernate will be used as implementation of the JPA. As you probably know, I’m a real fan of java based configurations, so I will use this approach to configure the Spring Data. In the end of the tutorial you can find a link to the sample project on GitHub.

Preparation

In the article I want to concentrate on the Spring Data, so all stuff which is out topic I will omit. But in the start I want provide a bulk of links which can be helpful for you in context of this tutorial.
These links should give answers on 90% of questions which can occur during reading the post. Let’s start with table creation in the MySQL:
view plaincopy to clipboardprint?
  1. CREATE TABLE shops (  
  2.   id int(6) NOT NULL AUTO_INCREMENT,  
  3.   name varchar(60) NOT NULL,  
  4.   employees_number int(6) NOT NULL,  
  5.   PRIMARY KEY (id)  
  6. ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;  
Now we can go ahead with a java code:
view plaincopy to clipboardprint?
  1. @Entity  
  2. @Table(name = “shops”)  
  3. public class Shop {  
  4.   
  5.     @Id  
  6.     @GeneratedValue  
  7.     private Integer id;  
  8.   
  9.     private String name;  
  10.   
  11.     @Column(name = “employees_number”)  
  12.     private Integer emplNumber;  
  13.   
  14.     public Integer getId() {  
  15.         return id;  
  16.     }  
  17.   
  18.     public void setId(Integer id) {  
  19.         this.id = id;  
  20.     }  
  21.   
  22.     public String getName() {  
  23.         return name;  
  24.     }  
  25.   
  26.     public void setName(String name) {  
  27.         this.name = name;  
  28.     }  
  29.   
  30.     public Integer getEmplNumber() {  
  31.         return emplNumber;  
  32.     }  
  33.   
  34.     public void setEmplNumber(Integer emplNumber) {  
  35.         this.emplNumber = emplNumber;  
  36.     }  
  37. }  

Configuration of Spring Data

I believe that a screenshot of the project will help you to understand what’s going on.
spring-data-jpa-project-structure
In the property file concentrated all configuration data:
view plaincopy to clipboardprint?
  1. #DB properties:  
  2. db.driver=com.mysql.jdbc.Driver  
  3. db.url=jdbc:mysql://localhost:3306/hibnatedb  
  4. db.username=hibuser  
  5. db.password=root  
  6.   
  7. #Hibernate Configuration:  
  8. hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect  
  9. hibernate.show_sql=true  
  10. entitymanager.packages.to.scan=com.spr.model  
The WebAppConfig class contains all java based configurations:
view plaincopy to clipboardprint?
  1. @Configuration  
  2. @EnableWebMvc  
  3. @EnableTransactionManagement  
  4. @ComponentScan(“com.spr”)  
  5. @PropertySource(“classpath:application.properties”)  
  6. @EnableJpaRepositories(“com.spr.repository”)  
  7. public class WebAppConfig {  
  8.   
  9.     private static final String PROPERTY_NAME_DATABASE_DRIVER = “db.driver”;  
  10.     private static final String PROPERTY_NAME_DATABASE_PASSWORD = “db.password”;  
  11.     private static final String PROPERTY_NAME_DATABASE_URL = “db.url”;  
  12.     private static final String PROPERTY_NAME_DATABASE_USERNAME = “db.username”;  
  13.   
  14.     private static final String PROPERTY_NAME_HIBERNATE_DIALECT = “hibernate.dialect”;  
  15.     private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = “hibernate.show_sql”;  
  16.     private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = “entitymanager.packages.to.scan”;  
  17.   
  18.     @Resource  
  19.     private Environment env;  
  20.   
  21.     @Bean  
  22.     public DataSource dataSource() {  
  23.         DriverManagerDataSource dataSource = new DriverManagerDataSource();  
  24.   
  25.         dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));  
  26.         dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));  
  27.         dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));  
  28.         dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));  
  29.   
  30.         return dataSource;  
  31.     }  
  32.   
  33.     @Bean  
  34.     public LocalContainerEntityManagerFactoryBean entityManagerFactory() {  
  35.         LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();  
  36.         entityManagerFactoryBean.setDataSource(dataSource());  
  37.         entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class);  
  38.         entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));  
  39.           
  40.         entityManagerFactoryBean.setJpaProperties(hibProperties());  
  41.           
  42.         return entityManagerFactoryBean;  
  43.     }  
  44.   
  45.     private Properties hibProperties() {  
  46.         Properties properties = new Properties();  
  47.         properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));  
  48.         properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));  
  49.         return properties;  
  50.     }  
  51.   
  52.     @Bean  
  53.     public JpaTransactionManager transactionManager() {  
  54.         JpaTransactionManager transactionManager = new JpaTransactionManager();  
  55.         transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());  
  56.         return transactionManager;  
  57.     }  
  58.   
  59.     @Bean  
  60.     public UrlBasedViewResolver setupViewResolver() {  
  61.         UrlBasedViewResolver resolver = new UrlBasedViewResolver();  
  62.         resolver.setPrefix(“/WEB-INF/pages/”);  
  63.         resolver.setSuffix(“.jsp”);  
  64.         resolver.setViewClass(JstlView.class);  
  65.         return resolver;  
  66.     }  
  67.   
  68. }  
Pay your attention at @EnableJpaRepositories annotation. It enables usage of JPA repositories. The com.spr.repository package will be scaned to detect repositories. In the entityManagerFactory bean I determined that Hibernate will be used as JPA implementation.
Initializer class will be omitted.

DAO & Service layers

The repository for the Shop entity:
view plaincopy to clipboardprint?
  1. package com.spr.repository;  
  2.   
  3. import org.springframework.data.jpa.repository.JpaRepository;  
  4.   
  5. import com.spr.model.Shop;  
  6.   
  7. public interface ShopRepository extends JpaRepository<shop, integer=“”> {  
  8.   
  9. }  
  10. </shop,>  
Definitely it is the most simplest code snippet in the tutorial. But it requires the most high attention. The JpaRepository interface contains the basic operations which can be performed with any entity (CRUD operations). More information you can find on the official documentation page.
Here is a code of the ShopService interface:
view plaincopy to clipboardprint?
  1. public interface ShopService {  
  2.       
  3.     public Shop create(Shop shop);  
  4.     public Shop delete(int id) throws ShopNotFound;  
  5.     public List<shop> findAll();  
  6.     public Shop update(Shop shop) throws ShopNotFound;  
  7.     public Shop findById(int id);  
  8.   
  9. }  
  10. </shop>  
And the implementation of the service interface:
view plaincopy to clipboardprint?
  1. import java.util.List;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Service;  
  6. import org.springframework.transaction.annotation.Transactional;  
  7.   
  8. import com.spr.exception.ShopNotFound;  
  9. import com.spr.model.Shop;  
  10. import com.spr.repository.ShopRepository;  
  11.   
  12. @Service  
  13. public class ShopServiceImpl implements ShopService {  
  14.       
  15.     @Resource  
  16.     private ShopRepository shopRepository;  
  17.   
  18.     @Override  
  19.     @Transactional  
  20.     public Shop create(Shop shop) {  
  21.         Shop createdShop = shop;  
  22.         return shopRepository.save(createdShop);  
  23.     }  
  24.       
  25.     @Override  
  26.     @Transactional  
  27.     public Shop findById(int id) {  
  28.         return shopRepository.findOne(id);  
  29.     }  
  30.   
  31.     @Override  
  32.     @Transactional(rollbackFor=ShopNotFound.class)  
  33.     public Shop delete(int id) throws ShopNotFound {  
  34.         Shop deletedShop = shopRepository.findOne(id);  
  35.           
  36.         if (deletedShop == null)  
  37.             throw new ShopNotFound();  
  38.           
  39.         shopRepository.delete(deletedShop);  
  40.         return deletedShop;  
  41.     }  
  42.   
  43.     @Override  
  44.     @Transactional  
  45.     public List<shop> findAll() {  
  46.         return shopRepository.findAll();  
  47.     }  
  48.   
  49.     @Override  
  50.     @Transactional(rollbackFor=ShopNotFound.class)  
  51.     public Shop update(Shop shop) throws ShopNotFound {  
  52.         Shop updatedShop = shopRepository.findOne(shop.getId());  
  53.           
  54.         if (updatedShop == null)  
  55.             throw new ShopNotFound();  
  56.           
  57.         updatedShop.setName(shop.getName());  
  58.         updatedShop.setEmplNumber(shop.getEmplNumber());  
  59.         return updatedShop;  
  60.     }  
  61.   
  62. }  
  63. </shop>  
In this way the ShopRepository is used.

Controller

Finally I can use ShopSrviceImpl class in the controller. All JSP pages will be omitted, so you can find them source code on the GitHub.
view plaincopy to clipboardprint?
  1. @Controller  
  2. @RequestMapping(value=“/shop”)  
  3. public class ShopController {  
  4.       
  5.     @Autowired  
  6.     private ShopService shopService;  
  7.   
  8.     @RequestMapping(value=“/create”, method=RequestMethod.GET)  
  9.     public ModelAndView newShopPage() {  
  10.         ModelAndView mav = new ModelAndView(“shop-new”“shop”new Shop());  
  11.         return mav;  
  12.     }  
  13.       
  14.     @RequestMapping(value=“/create”, method=RequestMethod.POST)  
  15.     public ModelAndView createNewShop(@ModelAttribute Shop shop,   
  16.             final RedirectAttributes redirectAttributes) {  
  17.           
  18.         ModelAndView mav = new ModelAndView();  
  19.         String message = “New shop “+shop.getName()+” was successfully created.”;  
  20.           
  21.         shopService.create(shop);  
  22.         mav.setViewName(“redirect:/index.html”);  
  23.                   
  24.         redirectAttributes.addFlashAttribute(“message”, message);     
  25.         return mav;       
  26.     }  
  27.       
  28.     @RequestMapping(value=“/list”, method=RequestMethod.GET)  
  29.     public ModelAndView shopListPage() {  
  30.         ModelAndView mav = new ModelAndView(“shop-list”);  
  31.         List<shop> shopList = shopService.findAll();  
  32.         mav.addObject(“shopList”, shopList);  
  33.         return mav;  
  34.     }  
  35.       
  36.     @RequestMapping(value=“/edit/{id}”, method=RequestMethod.GET)  
  37.     public ModelAndView editShopPage(@PathVariable Integer id) {  
  38.         ModelAndView mav = new ModelAndView(“shop-edit”);  
  39.         Shop shop = shopService.findById(id);  
  40.         mav.addObject(“shop”, shop);  
  41.         return mav;  
  42.     }  
  43.       
  44.     @RequestMapping(value=“/edit/{id}”, method=RequestMethod.POST)  
  45.     public ModelAndView editShop(@ModelAttribute Shop shop,  
  46.             @PathVariable Integer id,  
  47.             final RedirectAttributes redirectAttributes) throws ShopNotFound {  
  48.           
  49.         ModelAndView mav = new ModelAndView(“redirect:/index.html”);  
  50.         String message = “Shop was successfully updated.”;  
  51.   
  52.         shopService.update(shop);  
  53.           
  54.         redirectAttributes.addFlashAttribute(“message”, message);     
  55.         return mav;  
  56.     }  
  57.       
  58.     @RequestMapping(value=“/delete/{id}”, method=RequestMethod.GET)  
  59.     public ModelAndView deleteShop(@PathVariable Integer id,  
  60.             final RedirectAttributes redirectAttributes) throws ShopNotFound {  
  61.           
  62.         ModelAndView mav = new ModelAndView(“redirect:/index.html”);          
  63.           
  64.         Shop shop = shopService.delete(id);  
  65.         String message = “The shop “+shop.getName()+” was successfully deleted.”;  
  66.           
  67.         redirectAttributes.addFlashAttribute(“message”, message);  
  68.         return mav;  
  69.     }  
  70.       
  71. }  
  72. </shop>  
spring-data-jpa-application

Summary

The Spring Data is very powerful weapon, it helps you develop an application more faster and avoid hundreds of boilerplate strings of code. Usage of Spring Data is the most convenient way to create a DAO layer in an application, so don’t ignore it in your projects.
Оригінал: http://fruzenshtein.com/spring-jpa-data-hibernate-mysql/
Bitnami