Introduced
?? This article describes how to connect and process a MySQL database in a spring project.
?? The project uses spring Data JPA and hibernate to connect and process the MySQL database, which is, of course, just one way, and you can use spring JDBC or mybatis.
?? Spring Data JPA is a sub-project of spring data, which is mainly used to simplify the implementation of the database access layer, using spring data JPA to easily make additions, deletions, pagination, sorting, and more. Spring data has many sub-projects, in addition to spring data JPA, as well as the following sub-projects.
- Spring Data Commons
- Spring Data MongoDB
- Spring Data Redis
- Spring Data SOLR
- Spring Data Gemfire
- Spring Data REST
- Spring Data neo4j
?? Hibernate is an open source object-relational mapping framework that provides JDBC with a very lightweight object encapsulation that maps Pojo to database tables, is a fully automated ORM framework, and Hibernate automatically generates SQL statements, automatically executes, So that Java programmers can use object programming thinking to manipulate the database at will. Hibernate can be applied to any JDBC application, both in Java client applications and in servlet/jsp Web applications, and most revolutionary of all, hibernate can replace CMP in the EE architecture of the EJB application. The task of achieving data persistence.
?? This article describes how to use spring Data JPA and hibernate to connect and process the MySQL database.
Get ready
?? First we need to do some preparation for MySQL. We are going to create the Db_example database in MySQL and create the Springuser user with all the operations rights to the Db_example database. Open MySQL and enter the following command:
mysql> create database db_example; -- 创建新数据库db_examplemysql> create user ‘springuser‘@‘localhost‘ identified by ‘pwd123‘; -- 创建新用户springuser,密码为pwd123mysql> grant all on db_example.* to ‘springuser‘@‘localhost‘; -- 给予springuser用户对db_example数据库的所有操作权限
Spring Boot program STEP1. Create Project Spring_mysql, and project layout:
mkdir spring_mysqlcd ./spring_mysqltouch build.gradlemkdir -p src/main/javamkdir -p src/main/resourcesmkdir -p src/test/javamkdir -p src/test/resources
STEP2 Writing Build.gradle
?? The Build.gradle code is as follows:
buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.0.RELEASE") }}apply plugin: ‘java‘apply plugin: ‘eclipse‘apply plugin: ‘idea‘apply plugin: ‘org.springframework.boot‘apply plugin: ‘io.spring.dependency-management‘bootJar { baseName = ‘gs-accessing-data-mysql‘ version = ‘0.1.0‘}repositories { mavenCentral()}sourceCompatibility = 1.8targetCompatibility = 1.8dependencies { compile("org.springframework.boot:spring-boot-starter-web") // JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) compile ‘org.springframework.boot:spring-boot-starter-data-jpa‘ // Use MySQL Connector-J compile ‘mysql:mysql-connector-java‘ testCompile(‘org.springframework.boot:spring-boot-starter-test‘)}
In the spring boot project above, the main use of Spring-boot-starter-web, SPRING-BOOT-STARTER-DATA-JPA and MySQL: Mysql-connector-java to implement MySQL in web-side operation.
STEP3 Configuration Properties File
?? To create a new src/main/resources/application.properties file, configure the relevant properties with the following code:
spring.jpa.hibernate.ddl-auto=createspring.datasource.url=jdbc:mysql://localhost:3306/db_examplespring.datasource.username=springuserspring.datasource.password=pwd123
In the preceding code, the primary database operation is new (create) because the implementation of the database does not exist in the corresponding table. Use MySQL's localhost server's 3306-port Db_example database, and set the user name and password.
Step4 Writing Java files
?? Create a Src/main/java/hello folder (package) where the new user.java,hibernate will automatically convert the entity class to a table in the database. The complete code for User.java is as follows:
package hello;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entity // This tells Hibernate to make a table out of this classpublic class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private String name; private String email; 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 String getEmail() { return email; } public void setEmail(String email) { this.email = email; }}
?? Create a new Userrepository.java in the above folder with the following code:
package hello;import org.springframework.data.repository.CrudRepository;import hello.User;// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository// CRUD refers Create, Read, Update, Deletepublic interface UserRepository extends CrudRepository<User, Long> {}
This is the repository interface, which will be automatically executed by the bean in spring.
?? Create a new Maincontroller.java in the above folder with the following code:
Package Hello;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.getmapping;import Org.springframework.web.bind.annotation.RequestParam; Import Org.springframework.web.bind.annotation.responsebody;import Hello. User;import Hello. Userrepository, @Controller//This means, this class is a controller@requestmapping (path= "/demo")//This means URL ' s start with/demo (after application path) public class Maincontroller {@Autowired//This means to get the beans call Ed Userrepository//which is auto-generated by Spring, we'll use it to handle the data private Userrep Ository userrepository; @GetMapping (path= "/add")//MAP only GET requests public @ResponseBody string Addnewuser (@RequestParam string name , @RequestParam string email) {//@ResponseBody means the returned string Is the response, not a view name//@RequestParam means it's a parameter from the GET or POST request User n = new User (); N.setname (name); N.setemail (email); Userrepository.save (n); return "Saved"; } @GetMapping (path= "/all") public @ResponseBody iterable<user> getAllUsers () {//This returns a JSON o R XML with the users return Userrepository.findall (); }}
This is the new Director (Controller) for spring applications.
?? Create a new Application.java in the above folder with the following code:
package hello;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}
This is the main program entry for the Spring Boot project.
Step5 Creating an executable jar package
cd spring_mysqlgradle build
After execution, the Gs-accessing-data-mysql-0.1.0.jar is generated under the Build/libs folder.
Operation and Testing
?? Use the following command to start the Spring boot project
java -jar build/libs/gs-accessing-data-mysql-0.1.0.jar
?? In the browser-side test, enter the following URL:
localhost:8080/demo/add?name=Alex&[email protected]localhost:8080/demo/add?name=Jclian&[email protected]localhost:8080/demo/add?name=Bob&[email protected]localhost:8080/demo/add?name=Cook&[email protected]localhost:8080/demo/add?name=Mark&[email protected]
The above program will parse the value of the name and email parameters into the records in the user table in the database and save the browser interface such as:
Enter the URL Localhost:8080/demo/all in the browser and just look at the records we inserted into MySQL (in JSON format):
Finally we went to MySQL to see if the data was inserted successfully, as shown in the following:
Conclusion
?? This article describes how to use spring Data JPA and hibernate to connect and process the MySQL database.
?? This is the end of this share, we will continue to update the spring boot content, you are welcome to Exchange ~ ~
Spring Boot Primer (2) using the MySQL database