├── .gitignore
├── README.md
├── pom.xml
└── src
├── main
├── java
│ └── guru
│ │ └── springframework
│ │ ├── SpringBootRabbitMQApplication.java
│ │ ├── commands
│ │ └── ProductForm.java
│ │ ├── controllers
│ │ └── ProductController.java
│ │ ├── converters
│ │ ├── ProductFormToProduct.java
│ │ └── ProductToProductForm.java
│ │ ├── domain
│ │ └── Product.java
│ │ ├── listener
│ │ └── ProductMessageListener.java
│ │ ├── repositories
│ │ └── ProductRepository.java
│ │ └── services
│ │ ├── ProductService.java
│ │ └── ProductServiceImpl.java
└── resources
│ ├── application.properties
│ └── templates
│ └── product
│ ├── list.html
│ ├── productform.html
│ └── show.html
└── test
└── java
└── guru
└── springframework
├── SpringBootMySqlApplicationTests.java
└── repositories
└── ProductRepositoryTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 |
3 | # Mobile Tools for Java (J2ME)
4 | .mtj.tmp/
5 |
6 | # Package Files #
7 | *.jar
8 | *.war
9 | *.ear
10 |
11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
12 | hs_err_pid*
13 |
14 | target
15 |
16 | # IDE files
17 | .idea
18 | *.iml
19 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Spring Boot RabbitMQ Example
2 |
3 |
4 | Things to be checked before starting the application:
5 |
6 | * Update the application.properties file with your MySQL username and password
7 | * Create a new database schema with name springboot_rabbitmq_example
8 | * If you wish to used a different database / schema, you will need to override values in application.properties
9 | * Ensure that you have a rabbitmq server running and correctly configured in application.properties (default is localhost:5671) )
10 |
11 | Application flow:
12 |
13 | * Once the application is started, a browser at http://localhost:8080
14 | * Create a new Product record
15 | * Notice that the value for "Is Message Sent" in the http://localhost:8080/product/show/1 is currently set to false.
16 | * There is a link at the bottom of this record "Send messages through queue listener"
17 | * When this link is clicked, a message is put in a rabbitmq queue, the browser is redirected back to the product show page without getting blocked.
18 | * This message is read and processed by MessageSender class.
19 | * On the browser, keep refreshing the page: http://localhost:8080/product/show/1
20 | * You will notice that the value for "Are Messages Sent" changes to true in a second or so.
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | guru.springframework
7 | spring-boot-rabbitmq
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | spring-boot-rabbitmq
12 | Demo project for Spring Boot and RabbitMQ
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.0.0.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-amqp
31 |
32 |
33 |
34 | mysql
35 | mysql-connector-java
36 |
37 |
38 |
39 | org.springframework.boot
40 | spring-boot-starter-data-jpa
41 |
42 |
43 |
44 | org.springframework.boot
45 | spring-boot-starter-thymeleaf
46 |
47 |
48 | org.springframework.boot
49 | spring-boot-starter-web
50 |
51 |
52 |
53 | org.springframework.boot
54 | spring-boot-starter-test
55 | test
56 |
57 |
58 |
59 |
60 |
61 |
62 | org.springframework.boot
63 | spring-boot-maven-plugin
64 |
65 |
66 |
67 |
68 |
69 | spring-snapshots
70 | Spring Snapshots
71 | https://repo.spring.io/snapshot
72 |
73 | true
74 |
75 |
76 |
77 | spring-milestones
78 | Spring Milestones
79 | https://repo.spring.io/milestone
80 |
81 | false
82 |
83 |
84 |
85 |
86 |
87 |
88 | spring-snapshots
89 | Spring Snapshots
90 | https://repo.spring.io/snapshot
91 |
92 | true
93 |
94 |
95 |
96 | spring-milestones
97 | Spring Milestones
98 | https://repo.spring.io/milestone
99 |
100 | false
101 |
102 |
103 |
104 |
105 |
106 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/SpringBootRabbitMQApplication.java:
--------------------------------------------------------------------------------
1 | package guru.springframework;
2 |
3 | import guru.springframework.listener.ProductMessageListener;
4 | import org.springframework.amqp.core.Binding;
5 | import org.springframework.amqp.core.BindingBuilder;
6 | import org.springframework.amqp.core.Queue;
7 | import org.springframework.amqp.core.TopicExchange;
8 | import org.springframework.amqp.rabbit.connection.ConnectionFactory;
9 | import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
10 | import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
11 | import org.springframework.boot.SpringApplication;
12 | import org.springframework.boot.autoconfigure.SpringBootApplication;
13 | import org.springframework.context.annotation.Bean;
14 |
15 | @SpringBootApplication
16 | public class SpringBootRabbitMQApplication {
17 |
18 | public final static String SFG_MESSAGE_QUEUE = "sfg-message-queue";
19 |
20 | @Bean
21 | Queue queue() {
22 | return new Queue(SFG_MESSAGE_QUEUE, false);
23 | }
24 |
25 | @Bean
26 | TopicExchange exchange() {
27 | return new TopicExchange("spring-boot-exchange");
28 | }
29 |
30 | @Bean
31 | Binding binding(Queue queue, TopicExchange exchange) {
32 | return BindingBuilder.bind(queue).to(exchange).with(SFG_MESSAGE_QUEUE);
33 | }
34 |
35 | @Bean
36 | SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
37 | MessageListenerAdapter listenerAdapter) {
38 | SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
39 | container.setConnectionFactory(connectionFactory);
40 | container.setQueueNames(SFG_MESSAGE_QUEUE);
41 | container.setMessageListener(listenerAdapter);
42 | return container;
43 | }
44 |
45 | @Bean
46 | MessageListenerAdapter listenerAdapter(ProductMessageListener receiver) {
47 | return new MessageListenerAdapter(receiver, "receiveMessage");
48 | }
49 |
50 | public static void main(String[] args) {
51 | SpringApplication.run(SpringBootRabbitMQApplication.class, args);
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/commands/ProductForm.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.commands;
2 |
3 |
4 | import java.math.BigDecimal;
5 |
6 | /**
7 | * Created by jt on 1/10/17.
8 | */
9 | public class ProductForm {
10 | private Long id;
11 | private String description;
12 | private BigDecimal price;
13 | private String imageUrl;
14 |
15 | public Long getId() {
16 | return id;
17 | }
18 |
19 | public void setId(Long id) {
20 | this.id = id;
21 | }
22 |
23 | public String getDescription() {
24 | return description;
25 | }
26 |
27 | public void setDescription(String description) {
28 | this.description = description;
29 | }
30 |
31 | public BigDecimal getPrice() {
32 | return price;
33 | }
34 |
35 | public void setPrice(BigDecimal price) {
36 | this.price = price;
37 | }
38 |
39 | public String getImageUrl() {
40 | return imageUrl;
41 | }
42 |
43 | public void setImageUrl(String imageUrl) {
44 | this.imageUrl = imageUrl;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/controllers/ProductController.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.controllers;
2 |
3 | import guru.springframework.commands.ProductForm;
4 | import guru.springframework.converters.ProductToProductForm;
5 | import guru.springframework.domain.Product;
6 | import guru.springframework.services.ProductService;
7 | import org.apache.logging.log4j.LogManager;
8 | import org.apache.logging.log4j.Logger;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.stereotype.Controller;
11 | import org.springframework.ui.Model;
12 | import org.springframework.validation.BindingResult;
13 | import org.springframework.web.bind.annotation.PathVariable;
14 | import org.springframework.web.bind.annotation.RequestMapping;
15 | import org.springframework.web.bind.annotation.RequestMethod;
16 |
17 | import javax.validation.Valid;
18 |
19 | /**
20 | * Created by jt on 1/10/17.
21 | */
22 | @Controller
23 | public class ProductController {
24 |
25 | private static final Logger log = LogManager.getLogger(ProductController.class);
26 |
27 | private ProductService productService;
28 |
29 | private ProductToProductForm productToProductForm;
30 |
31 |
32 |
33 | @Autowired
34 | public void setProductToProductForm(ProductToProductForm productToProductForm) {
35 | this.productToProductForm = productToProductForm;
36 | }
37 |
38 | @Autowired
39 | public void setProductService(ProductService productService) {
40 | this.productService = productService;
41 | }
42 |
43 | @RequestMapping("/")
44 | public String redirToList(){
45 | return "redirect:/product/list";
46 | }
47 |
48 | @RequestMapping({"/product/list", "/product"})
49 | public String listProducts(Model model){
50 | model.addAttribute("products", productService.listAll());
51 | return "product/list";
52 | }
53 |
54 | @RequestMapping("/product/show/{id}")
55 | public String getProduct(@PathVariable String id, Model model){
56 | model.addAttribute("product", productService.getById(Long.valueOf(id)));
57 | return "product/show";
58 | }
59 |
60 | @RequestMapping("product/edit/{id}")
61 | public String edit(@PathVariable String id, Model model){
62 | Product product = productService.getById(Long.valueOf(id));
63 | ProductForm productForm = productToProductForm.convert(product);
64 |
65 | model.addAttribute("productForm", productForm);
66 | return "product/productform";
67 | }
68 |
69 | @RequestMapping("/product/new")
70 | public String newProduct(Model model){
71 | model.addAttribute("productForm", new ProductForm());
72 | return "product/productform";
73 | }
74 |
75 | @RequestMapping(value = "/product", method = RequestMethod.POST)
76 | public String saveOrUpdateProduct(@Valid ProductForm productForm, BindingResult bindingResult){
77 |
78 | if(bindingResult.hasErrors()){
79 | return "product/productform";
80 | }
81 |
82 | Product savedProduct = productService.saveOrUpdateProductForm(productForm);
83 |
84 | return "redirect:/product/show/" + savedProduct.getId();
85 | }
86 |
87 | @RequestMapping("/product/delete/{id}")
88 | public String delete(@PathVariable String id){
89 | productService.delete(Long.valueOf(id));
90 | return "redirect:/product/list";
91 | }
92 |
93 | @RequestMapping("/product/indexProduct/{id}")
94 | public String indexProduct(@PathVariable String id){
95 | productService.sendProductMessage(id);
96 | return "redirect:/product/show/"+id;
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/converters/ProductFormToProduct.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.converters;
2 |
3 | import guru.springframework.commands.ProductForm;
4 | import guru.springframework.domain.Product;
5 | import org.springframework.core.convert.converter.Converter;
6 | import org.springframework.stereotype.Component;
7 | import org.springframework.util.StringUtils;
8 |
9 | /**
10 | * Created by jt on 1/10/17.
11 | */
12 | @Component
13 | public class ProductFormToProduct implements Converter {
14 |
15 | @Override
16 | public Product convert(ProductForm productForm) {
17 | Product product = new Product();
18 | if (productForm.getId() != null && !StringUtils.isEmpty(productForm.getId())) {
19 | product.setId(new Long(productForm.getId()));
20 | }
21 | product.setDescription(productForm.getDescription());
22 | product.setPrice(productForm.getPrice());
23 | product.setImageUrl(productForm.getImageUrl());
24 | return product;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/converters/ProductToProductForm.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.converters;
2 |
3 | import guru.springframework.commands.ProductForm;
4 | import guru.springframework.domain.Product;
5 | import org.springframework.core.convert.converter.Converter;
6 | import org.springframework.stereotype.Component;
7 |
8 | /**
9 | * Created by jt on 1/10/17.
10 | */
11 | @Component
12 | public class ProductToProductForm implements Converter {
13 | @Override
14 | public ProductForm convert(Product product) {
15 | ProductForm productForm = new ProductForm();
16 | productForm.setId(product.getId());
17 | productForm.setDescription(product.getDescription());
18 | productForm.setPrice(product.getPrice());
19 | productForm.setImageUrl(product.getImageUrl());
20 | return productForm;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/domain/Product.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.domain;
2 |
3 | import javax.persistence.Entity;
4 | import javax.persistence.GeneratedValue;
5 | import javax.persistence.Id;
6 | import java.math.BigDecimal;
7 |
8 | /**
9 | * Created by jt on 1/10/17.
10 | */
11 | @Entity
12 | public class Product {
13 |
14 | @Id
15 | @GeneratedValue
16 | private Long id;
17 | private String description;
18 | private BigDecimal price;
19 | private String imageUrl;
20 | private boolean messageReceived;
21 | private Integer messageCount = 0; //init to zero
22 |
23 | public Long getId() {
24 | return id;
25 | }
26 |
27 | public void setId(Long id) {
28 | this.id = id;
29 | }
30 |
31 | public String getDescription() {
32 | return description;
33 | }
34 |
35 | public void setDescription(String description) {
36 | this.description = description;
37 | }
38 |
39 | public BigDecimal getPrice() {
40 | return price;
41 | }
42 |
43 | public void setPrice(BigDecimal price) {
44 | this.price = price;
45 | }
46 |
47 | public String getImageUrl() {
48 | return imageUrl;
49 | }
50 |
51 | public void setImageUrl(String imageUrl) {
52 | this.imageUrl = imageUrl;
53 | }
54 |
55 | public boolean isMessageReceived() {
56 | return messageReceived;
57 | }
58 |
59 | public void setMessageReceived(boolean messageReceived) {
60 | this.messageReceived = messageReceived;
61 | }
62 |
63 | public Integer getMessageCount() {
64 | return messageCount;
65 | }
66 |
67 | public void setMessageCount(Integer messageCount) {
68 | this.messageCount = messageCount;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/listener/ProductMessageListener.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.listener;
2 |
3 | import guru.springframework.domain.Product;
4 | import guru.springframework.repositories.ProductRepository;
5 | import org.springframework.stereotype.Component;
6 | import org.apache.logging.log4j.LogManager;
7 | import org.apache.logging.log4j.Logger;
8 | import java.util.Map;
9 |
10 | /**
11 | * This is the queue listener class, its receiveMessage() method ios invoked with the
12 | * message as the parameter.
13 | */
14 | @Component
15 | public class ProductMessageListener {
16 |
17 | private ProductRepository productRepository;
18 |
19 | private static final Logger log = LogManager.getLogger(ProductMessageListener.class);
20 |
21 | public ProductMessageListener(ProductRepository productRepository) {
22 | this.productRepository = productRepository;
23 | }
24 |
25 | /**
26 | * This method is invoked whenever any new message is put in the queue.
27 | * See {@link guru.springframework.SpringBootRabbitMQApplication} for more details
28 | * @param message
29 | */
30 | public void receiveMessage(Map message) {
31 | log.info("Received <" + message + ">");
32 | Long id = Long.valueOf(message.get("id"));
33 | Product product = productRepository.findById(id).orElse(null);
34 | product.setMessageReceived(true);
35 | product.setMessageCount(product.getMessageCount() + 1);
36 |
37 | productRepository.save(product);
38 | log.info("Message processed...");
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/repositories/ProductRepository.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.repositories;
2 |
3 | import guru.springframework.domain.Product;
4 | import org.springframework.data.repository.CrudRepository;
5 |
6 | /**
7 | * Created by jt on 1/10/17.
8 | */
9 | public interface ProductRepository extends CrudRepository {
10 | }
11 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/services/ProductService.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.services;
2 |
3 | import guru.springframework.commands.ProductForm;
4 | import guru.springframework.domain.Product;
5 |
6 | import java.util.List;
7 |
8 | /**
9 | * Created by jt on 1/10/17.
10 | */
11 | public interface ProductService {
12 |
13 | List listAll();
14 |
15 | Product getById(Long id);
16 |
17 | Product saveOrUpdate(Product product);
18 |
19 | void delete(Long id);
20 |
21 | Product saveOrUpdateProductForm(ProductForm productForm);
22 |
23 | void sendProductMessage(String id);
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/services/ProductServiceImpl.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.services;
2 |
3 | import guru.springframework.SpringBootRabbitMQApplication;
4 | import guru.springframework.commands.ProductForm;
5 | import guru.springframework.converters.ProductFormToProduct;
6 | import guru.springframework.domain.Product;
7 | import guru.springframework.repositories.ProductRepository;
8 | import org.slf4j.Logger;
9 | import org.slf4j.LoggerFactory;
10 | import org.springframework.amqp.rabbit.core.RabbitTemplate;
11 | import org.springframework.beans.factory.annotation.Autowired;
12 | import org.springframework.stereotype.Service;
13 |
14 | import java.util.ArrayList;
15 | import java.util.HashMap;
16 | import java.util.List;
17 | import java.util.Map;
18 |
19 | /**
20 | * Created by jt on 1/10/17.
21 | */
22 | @Service
23 | public class ProductServiceImpl implements ProductService {
24 |
25 | private static final Logger log = LoggerFactory.getLogger(ProductServiceImpl.class);
26 |
27 | private ProductRepository productRepository;
28 | private ProductFormToProduct productFormToProduct;
29 | private RabbitTemplate rabbitTemplate;
30 |
31 | @Autowired
32 | public ProductServiceImpl(ProductRepository productRepository, ProductFormToProduct productFormToProduct,
33 | RabbitTemplate rabbitTemplate) {
34 | this.productRepository = productRepository;
35 | this.productFormToProduct = productFormToProduct;
36 | this.rabbitTemplate = rabbitTemplate;
37 | }
38 |
39 |
40 | @Override
41 | public List listAll() {
42 | List products = new ArrayList<>();
43 | productRepository.findAll().forEach(products::add); //fun with Java 8
44 | return products;
45 | }
46 |
47 | @Override
48 | public Product getById(Long id) {
49 | return productRepository.findById(id).orElse(null);
50 | }
51 |
52 | @Override
53 | public Product saveOrUpdate(Product product) {
54 | productRepository.save(product);
55 | return product;
56 | }
57 |
58 | @Override
59 | public void delete(Long id) {
60 | productRepository.deleteById(id);
61 |
62 | }
63 |
64 | @Override
65 | public Product saveOrUpdateProductForm(ProductForm productForm) {
66 | Product savedProduct = saveOrUpdate(productFormToProduct.convert(productForm));
67 |
68 | System.out.println("Saved Product Id: " + savedProduct.getId());
69 | return savedProduct;
70 | }
71 |
72 | @Override
73 | public void sendProductMessage(String id) {
74 | Map actionmap = new HashMap<>();
75 | actionmap.put("id", id);
76 | log.info("Sending the index request through queue message");
77 | rabbitTemplate.convertAndSend(SpringBootRabbitMQApplication.SFG_MESSAGE_QUEUE, actionmap);
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | # ===============================
2 | # = DATA SOURCE
3 | # ===============================
4 | # Set here configurations for the database connection
5 | spring.datasource.url=jdbc:mysql://localhost:3306/springboot_rabbitmq_example
6 | spring.datasource.username=root
7 | spring.datasource.password=
8 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver
9 | # Keep the connection alive if idle for a long time (needed in production)
10 | spring.datasource.testWhileIdle=true
11 | spring.datasource.validationQuery=SELECT 1
12 |
13 | spring.rabbitmq.host = 127.0.0.1
14 | spring.rabbitmq.port = 5672
15 | spring.rabbitmq.username = guest
16 | spring.rabbitmq.password = guest
17 |
18 | # ===============================
19 | # = JPA / HIBERNATE
20 | # ===============================
21 | # Show or not log for each sql query
22 | spring.jpa.show-sql=true
23 | # Hibernate ddl auto (create, create-drop, update): with "create-drop" the database
24 | # schema will be automatically created afresh for every start of application
25 | spring.jpa.hibernate.ddl-auto=create-drop
26 | # Naming strategy
27 | spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
28 | # Allows Hibernate to generate SQL optimized for a particular DBMS
29 | spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
--------------------------------------------------------------------------------
/src/main/resources/templates/product/list.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Spring Core Online Tutorial - List Products
5 |
6 |
7 |
10 |
11 |
13 |
14 |
16 |
17 |
18 |
19 |
20 |
Product List
21 |
22 |
23 | Id |
24 | Description |
25 | Price |
26 | Image URL |
27 | List |
28 | Edit |
29 | Delete |
30 |
31 |
32 | |
33 | |
34 | |
35 | |
36 | View |
37 | Edit |
38 | Delete |
39 |
40 |
41 |
42 |
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/src/main/resources/templates/product/productform.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Spring Core Online Tutorial - Product Form
5 |
6 |
7 |
10 |
11 |
13 |
14 |
16 |
17 |
18 |
19 |
20 |
Product Details
21 |
73 |
74 |
75 |
76 |
--------------------------------------------------------------------------------
/src/main/resources/templates/product/show.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Spring Core Online Tutorial - Show Product
5 |
6 |
7 |
10 |
11 |
13 |
14 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
Show Product
23 |
24 |
25 |
73 |
74 |
75 |
76 |
--------------------------------------------------------------------------------
/src/test/java/guru/springframework/SpringBootMySqlApplicationTests.java:
--------------------------------------------------------------------------------
1 | package guru.springframework;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class SpringBootMySqlApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/test/java/guru/springframework/repositories/ProductRepositoryTest.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.repositories;
2 |
3 | import guru.springframework.domain.Product;
4 | import org.junit.Assert;
5 | import org.junit.Before;
6 | import org.junit.Test;
7 | import org.junit.runner.RunWith;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.boot.test.context.SpringBootTest;
10 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
11 |
12 | import java.math.BigDecimal;
13 |
14 | @RunWith(SpringJUnit4ClassRunner.class)
15 | @SpringBootTest
16 | public class ProductRepositoryTest {
17 |
18 | private static final BigDecimal BIG_DECIMAL_100 = BigDecimal.valueOf(100.00);
19 | private static final String PRODUCT_DESCRIPTION = "a cool product";
20 | private static final String IMAGE_URL = "http://an-imageurl.com/image1.jpg";
21 |
22 | @Autowired
23 | private ProductRepository productRepository;
24 |
25 | @Before
26 | public void setUp() throws Exception {
27 |
28 | }
29 |
30 | @Test
31 | public void testPersistence() {
32 | //given
33 | Product product = new Product();
34 | product.setDescription(PRODUCT_DESCRIPTION);
35 | product.setImageUrl(IMAGE_URL);
36 | product.setPrice(BIG_DECIMAL_100);
37 |
38 | //when
39 | productRepository.save(product);
40 |
41 | //then
42 | Assert.assertNotNull(product.getId());
43 | Product newProduct = productRepository.findById(product.getId()).orElse(null);
44 | Assert.assertEquals((Long) 1L, newProduct.getId());
45 | Assert.assertEquals(PRODUCT_DESCRIPTION, newProduct.getDescription());
46 | Assert.assertEquals(BIG_DECIMAL_100.compareTo(newProduct.getPrice()), 0);
47 | Assert.assertEquals(IMAGE_URL, newProduct.getImageUrl());
48 | }
49 | }
--------------------------------------------------------------------------------