Spring JPA Data + Hibernate + MySQL + Maven

Spring JPA Data + Hibernate + MySQL + Maven

 http://fruzenshtein.com/spring-jpa-data-hibernate-mysql/


------------------------------------------------------------

太他X好的一篇文章了。
基于java的配置
再也不用去写什么xml了
重点是代码全啊。而且还有代码可以借鉴!!!!!!!!!!
看spring in action 4这本鬼书真的他妈的蛋疼啊!!!!
看完完全写不出个项目来!!!草草草,怒了,很多内容都被忽略了,连到底是要import什么类,依赖那个库都没说,超级麻烦。
搜了好多天,才有这个大哥的这篇文章来拯救我于危难啊,太感动了,我这小白。


-----------------------------


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 demonstrate Spring Data (JPA) in conjunction withSpring MVC, MySQL and MavenHibernate 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:

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:

01 @Entity
02 @Table(name = "shops")
03 public class Shop {
04  
05     @Id
06     @GeneratedValue
07     private Integer id;
08  
09     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:

01 #DB properties:
02 db.driver=com.mysql.jdbc.Driver
04 db.username=hibuser
05 db.password=root
06  
07 #Hibernate Configuration:
08 hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
09 hibernate.show_sql=true
10 entitymanager.packages.to.scan=com.spr.model

The WebAppConfig class contains all java based configurations:

01 @Configuration
02 @EnableWebMvc
03 @EnableTransactionManagement
04 @ComponentScan("com.spr")
05 @PropertySource("classpath:application.properties")
06 @EnableJpaRepositories("com.spr.repository")
07 public class WebAppConfig {
08  
09     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 = newLocalContainerEntityManagerFactoryBean();
36         entityManagerFactoryBean.setDataSource(dataSource());
37         entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class);
38         entityManagerFactoryBean.setPackagesToScan(env.
39 getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
40  
41         entityManagerFactoryBean.setJpaProperties(hibProperties());
42  
43         return entityManagerFactoryBean;
44     }
45  
46     private Properties hibProperties() {
47         Properties properties = new Properties();
48         properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
49         properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
50         return properties;
51     }
52  
53     @Bean
54     public JpaTransactionManager transactionManager() {
55         JpaTransactionManager transactionManager = new JpaTransactionManager();
56         transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
57         return transactionManager;
58     }
59  
60     @Bean
61     public UrlBasedViewResolver setupViewResolver() {
62         UrlBasedViewResolver resolver = new UrlBasedViewResolver();
63         resolver.setPrefix("/WEB-INF/pages/");
64         resolver.setSuffix(".jsp");
65         resolver.setViewClass(JstlView.class);
66         return resolver;
67     }
68  
69 }

Pay your attention at @EnableJpaRepositories annotation. It enables usage of JPA repositories. The com.spr.repositorypackage 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:

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 }

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:

1 public interface ShopService {
2  
3     public Shop create(Shop shop);
4     public Shop delete(int id) throws ShopNotFound;
5     public List findAll();
6     public Shop update(Shop shop) throws ShopNotFound;
7     public Shop findById(int id);
8  
9 }

And the implementation of the service interface:

01 import java.util.List;
02  
03 import javax.annotation.Resource;
04  
05 import org.springframework.stereotype.Service;
06 import org.springframework.transaction.annotation.Transactional;
07  
08 import com.spr.exception.ShopNotFound;
09 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 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 }

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.

01 @Controller
02 @RequestMapping(value="/shop")
03 public class ShopController {
04  
05     @Autowired
06     private ShopService shopService;
07  
08     @RequestMapping(value="/create", method=RequestMethod.GET)
09     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 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 }

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.

好的,下面是一个简单的示例。 首先,在 pom.xml 文件中添加如下依赖: ```xml <dependencies> <!-- Spring Boot Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- Spring Data JPA --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> </dependency> </dependencies> ``` 然后在 application.properties 文件中配置数据库信息: ``` spring.datasource.url=jdbc:mysql://localhost:3306/db_name spring.datasource.username=root spring.datasource.password=123456 spring.jpa.hibernate.ddl-auto=update ``` 其中,db_name 是你的数据库名,root 和 123456 是你的 MySQL 用户名和密码。 接下来,创建一个实体类,比如 User: ```java @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String name; @Column(nullable = false) private Integer age; // 省略 getter 和 setter } ``` 然后,创建一个 UserRepository 接口,继承自 JpaRepository: ```java @Repository public interface UserRepository extends JpaRepository<User, Long> { } ``` 接下来,创建一个 UserController 类,处理用户的增删改查请求: ```java @RestController @RequestMapping("/users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping("/") public List<User> getAllUsers() { return userRepository.findAll(); } @PostMapping("/") public User createUser(@RequestBody User user) { return userRepository.save(user); } @PutMapping("/{id}") public User updateUser(@PathVariable Long id, @RequestBody User user) { User existingUser = userRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("User not found with id " + id)); existingUser.setName(user.getName()); existingUser.setAge(user.getAge()); return userRepository.save(existingUser); } @DeleteMapping("/{id}") public ResponseEntity<?> deleteUser(@PathVariable Long id) { User existingUser = userRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("User not found with id " + id)); userRepository.delete(existingUser); return ResponseEntity.ok().build(); } } ``` 其中,@GetMapping("/") 处理获取所有用户的请求,@PostMapping("/") 处理创建用户的请求,@PutMapping("/{id}") 处理更新用户的请求,@DeleteMapping("/{id}") 处理删除用户的请求。 最后,启动应用程序,访问 http://localhost:8080/users 即可查看所有用户的信息。可以使用 Postman 等工具测试其他请求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值