Hardcore!

Hello everyone, meet again, I am your friend Quanzhanjun.

Table of contents

  • 1. Add dependencies to pom.xml
  • 2. application.properties add data library configuration
  • 3. Add entity class
  • 4. Add Dao
  • 5. Add Controller
  • 6. Create a new database
  • 7. Test

Part 1 Just two steps! Eclipse+Maven quickly builds the first Spring Boot project A Spring Boot project has been built, and this article is based on this to connect the MySQL database.

1. Add dependencies to pom.xml

        <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

2. application.properties add database configuration

spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
copy

If the database connection is written as spring.datasource.url= jdbc:mysql://localhost:3306/spring_boot , due to the problem of MySQL version, there may be the following errors, add "?serverTimezone=GMT%2B8" at the back, set the time zone, and solve.

set the driver, spring.datasource.driver-class-name=com.mysql.jdbc.Driver will have the following red warning message. It is said that com.mysql.jdbc.Driver' is deprecated, to use a new driver com.mysql.cj.jdbc.Driver', after changing to `com.mysql.cj.jdbc.Driver' everything works fine.

Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class iscom.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

[External link image transfer failed, the source site may have an anti-leech mechanism, it is recommended to save the image and upload it directly (img-pK7xJNKu-1623641171427)(https://upload-images.jianshu.io/upload_images/24195226-b8c397570ac08893.png ?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]

3. Add entity class

@Entity represents an entity class, @Table(name=”user”) is used to correspond to the use table in the database, @Id is used to express the primary key, and @Column(name=”id”) is used to indicate an id attribute.

@GeneratedValue makes the primary key increment automatically. If you have any questions, please refer to @GeneratedValue source code analysis.

package com.example.demo.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long id;
    @Column(name = "username")
    private String userName;
    @Column(name = "password")
    private String passWord;

    public User() {
        super();
    }

    public User(String userName, String passWord) {
        super();
        this.userName = userName;
        this.passWord = passWord;
    }

    public Long getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

}
copy

4. Add Dao

The Dao layer is mainly used to add, delete, check and modify the database. dao only needs to inherit the JpaRepository class, almost no need to write methods, and can automatically generate SQL according to the method name. For example, findByUserName will automatically generate a query method with userName as a parameter.

package com.example.demo.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.example.demo.domain.User;

public interface UserRepository extends JpaRepository<User, Long> {

    User findByUserName(String userName);

}
copy

5. Add Controller

package com.example.demo.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.dao.UserRepository;
import com.example.demo.domain.User;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping("/getAllUser")
    @ResponseBody
    public List<User> findAll() {
        List<User> list = new ArrayList<User>();
        list = userRepository.findAll();
        return list;
    }

    @RequestMapping("/getByUserName")
    @ResponseBody
    public User getByUserName(String userName) {
        User user = userRepository.findByUserName(userName);
        return user;
    }

}
copy

Project structure diagram after adding files to the project:

6. Create a new database

new database mysql://localhost:3306/spring_boot , a required step. Although hibernate will automatically create new tables, the database still needs to be built manually.

Use Navicat to create a new local database, right click on the connection name -> New Database -> Fill in the database information -> OK.

In the user table, insert two test data:

7. Test

Startup project. Send a request with Postman for testing:

http://localhost:8080//user/getAllUser :

http://localhost:8080//user/getByUserName?userName=Turing :

at last

The editor will share some of my usual learning materials here. Due to space limitations, the detailed information of the pdf document is too comprehensive, and the details are too much, so I only take screenshots of some knowledge points for a rough introduction, and each small node contains There are more detailed content! Programmers (yuan) in need can follow + like, Click here to get it for free

Programmer code interview guide IT famous enterprise algorithm and data structure problem optimal solution

This is the "Book of Programmer Interviews"! The book summarizes the optimal solutions for various topics in the code interviews of famous IT companies, and provides relevant code implementations. In view of the lack of authoritative topics in the current programmer interviews - the pain point, this book The book selects nearly 200 classic code interview questions that have actually appeared to help the majority of programmers prepare for interviews without fail. After "writing" the book, you are the "Title King"!

"TCP-IP Protocol Suite (4th Edition)"

This book is the latest edition of the classic book that introduces the TCP/IP protocol family. This book has been well received by readers since its first edition was published.

The latest edition of this book is "Protect Yuan", which reflects the latest development of computer network technology. The book has seven major parts, a total of 30 chapters and seven appendices: The first part introduces some basic concepts and basic underlying technologies: The second part introduces the network Layer Protocol: The third part introduces the transport layer protocol; the fourth part introduces the application layer protocol: the fifth part introduces the next generation protocol, namely the IPv6 protocol: the sixth part introduces the network security issues: the seventh part gives seven appendices.

Java Development Manual (Songshan Edition)

Needless to say, Ali's development manual, I will read it every time it is updated, this is the latest update in early August (Songshan version)**

MySQL 8 from entry to proficient

The main contents of this book include MySQL installation and configuration, database creation, data table creation, data types and operators, MySQL functions, query data, data table operations (insert, update and delete data), indexes, stored procedures and Function, view, trigger, user management, data backup and restore, MySQL log, performance optimization, MySQL Replication, MySQL Workbench, MySQL Utilities, MySQL Proxy, PHP operation MySQL database and PDO database abstract class library, etc. Finally, through the database design of 3 comprehensive cases, the progress tells about the application of MySQL in practical work.

Spring5 Advanced Programming (5th Edition)

Covering all of Spring 5, this book is the most comprehensive Spring reference and practical guide if you want to take full advantage of the power of this leading enterprise Java application development framework.

This 5th edition covers core Spring and its integration with other leading Java technologies such as Hibemate JPA 2.Tls, Thymeleaf, and WebSocket. The focus of this book is on how to use Java configuration classes, lambda expressions, Spring Boot, and reactive programming. At the same time, some insights and real-world experience will be shared with enterprise-level application developers, including remoting, transactions, Web and presentation tiers, and more.

JAVA core knowledge points + 1000 Internet Java engineer interview questions

The Way of Enterprise IT Architecture Transformation Alibaba's Middle-Taiwan Strategic Thought and Architecture Practice

This book tells the history of Alibaba's technology development, as well as the practice and development history of the Internet technology architecture.

b and the presentation layer, etc.

[External link image dumping...(img-FHal6G3Y-1623641171438)]

JAVA core knowledge points + 1000 Internet Java engineer interview questions

[External link image dumping...(img-OebqJQiK-1623641171439)]

[External link image dumping...(img-lG7tUg8V-1623641171439)]

The Way of Enterprise IT Architecture Transformation Alibaba's Middle-Taiwan Strategic Thought and Architecture Practice

This book tells the history of Alibaba's technology development, as well as the practice and development history of the Internet technology architecture.

Publisher: Full-stack programmer, please indicate the source: https://javaforall.cn/152876.html Original link: https://javaforall.cn

Posted by cneale on Mon, 12 Sep 2022 21:35:43 +0530