Preface:

Hi, everyone. Recently, I have been learning the SpringDataJPA framework integrated with SpringBoot. I was a little careful and wanted to share it with you. Just today, July 12, 2020 is my 27th birthday (entering middle age). I would like to send you this SpringBoot integration SpringDataJPA tutorial. I hope you like not to talk more and we will officially start

Preparations:

1. Install the eclispe + STS development environment. 2. Install maven and configure the environment. How to use idea to create springBoot projects in one click? Springboot structures, zero based tutorial: www.jianshu.com/p/c48595fdb…

The tripartite library you need to use

<! Java Web services dependency --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <! --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>Copy the code

The configuration of application.ymal is shown below:

server:
  port: 8081
  servlet:
    context-path:
limit: minMoney: 0.01 maxMoney: 9999 Description: At least${limit.minMoney}Yuan, the most${limit.maxMoney}Yuan spring: a datasource: driver - class - name: the mysql. Cj.. JDBC driver url: JDBC: mysql: / / 127.0.0.1:3306 / luckymoney? characterEncoding=utf-8&serverTimezone=UTC username: root password: 123456 jpa: hibernate: ddl-auto: update show-sql:true
Copy the code

Set utF-8 encoding and serverTimezone=UTC and time zone as well as database account and password for the JDBC driver

package com.imooc.luckymoney; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.Map; /** * Created by xuqing * 2020年7月12 10:40:43 * @controller + @responseBody = @restController ** */ @restController @RequestMapping("/hello")
public class HelloController {

	@Autowired
	private LimitConfig limitConfig;

	@PostMapping("/say")
	public String say(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myId) {
	//	return "Explanation:" + limitConfig.getDescription();
	return "id:" + myId;
	}

    @GetMapping("/index")
	public  Object index(){
		Map<String,Object> map=new HashMap<>();
		map.put("msg"."Deployment successful");
		return  map;
	}

    @GetMapping("/getsay")
	public  String say() {return "Explanation:" + limitConfig.getDescription(); }}Copy the code

We visit the index this method request interface address is: http://localhost:8081/luckymoney/hello/index

Concrete implementation:

1 Create bean class (data model)

package com.imooc.luckymoney; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.math.BigDecimal; /** * Created by xuqing * 2020年7月12日10:40:18 */ @entity Public class Luckymoney {@id @generatedValue private Integer id; private BigDecimal money; /** * private String producer; /** * private String consumer; publicLuckymoney() {
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public BigDecimal getMoney() {
		return money;
	}

	public void setMoney(BigDecimal money) {
		this.money = money;
	}

	public String getProducer() {
		return producer;
	}

	public void setProducer(String producer) {
		this.producer = producer;
	}

	public String getConsumer() {
		return consumer;
	}

	public void setConsumer(String consumer) { this.consumer = consumer; }}Copy the code

So on top of the class name we’re going to add the @entity annotation so that the code will automatically create Luckymoney for me in MySQL and then we’re going to add that to the header ID of the table

@Id 
@GeneratedValue 
Copy the code

This two-line annotation so that in MySQL created tables, the header ID is non-null and is increment

2 inheritance jpa

package com.imooc.luckymoney; import org.springframework.data.jpa.repository.JpaRepository; /** * Created by xuqing */ public interface LuckmoneyRepository extends JpaRepository<Luckymoney, Integer> { }Copy the code

We just need to write a class that inherits JpaRepository and pass in our data model bean class (corresponding to the table of the database) to add, delete, change, and check the database

3 Specific business logic implementation of controller layer:

First we need to inject our LuckmoneyRepository class integrating JpaRepository with the @AutoWired annotation

@Autowired
private LuckmoneyRepository repository;
Copy the code

We can then call some of the methods in the LuckmoneyRepository parent class to operate on the database. 1 query database call finaAll(); Method to query the data of the entire table

/** * get the red envelope list */ @getMapping ("/luckymoneys")
public List<Luckymoney> list() {
   return repository.findAll();
}
Copy the code

Request effect:

Call save to pass in the object

/** * create a red envelope */ @postmapping ("/luckymoneys")
public Luckymoney create(@RequestParam("producer") String producer,
							 @RequestParam("money") BigDecimal money) {
		Luckymoney luckymoney = new Luckymoney();
		luckymoney.setProducer(producer);
		luckymoney.setMoney(money);
		return repository.save(luckymoney);
}
Copy the code

Request effect:

/** * PutMapping(@putMapping)"/luckymoneys/{id}")
public Luckymoney update(@PathVariable("id") Integer id,
							 @RequestParam("consumer") String consumer) {
		Optional<Luckymoney> optional = repository.findById(id);
		if (optional.isPresent()) {
			Luckymoney luckymoney = optional.get();
			luckymoney.setConsumer(consumer);
			return repository.save(luckymoney);
		}
		return null;
	}
Copy the code

Request effect:

Operation data before update

Manipulate the updated data

Conclusion:

Compared to the way Java Web JSPS were written in the past, this SpringBoot integration with SpringDataJPA is much simpler to write and basically doesn’t need to write SQL to operate on the database. But it’s important to note that if there is a complex business logic with multiple table queries we still need to introduce SQL statements, so we won’t go into this article and leave comments below if you’re interested and I’ll take some time later to update the complex business logic with SpringBoot and how SpringDataJPA works. Finally, I hope my article can help you solve the problem, and I will contribute more useful code to share with you in the future. If you think the article is good, please pay attention to it and star. Thank you and you can also add my personal QQ/ wechat (1693891473).

The project address

Making: github.com/xq19930522/… Code cloud address: gitee.com/qiuyu123/sp…