Detail the use of Mysql and JPA in Spring Boot

  • 2020-07-21 07:32:24
  • OfStack

This article shows you how to use the Mysq database in Spring Boot's Web applications and shows you the full benefits of Spring Boot (with as little code and configuration as possible). For the data access layer we will use Spring Data JPA and Hibernate (implementation 1 of JPA).

1. Maven pom xml file

Add the following dependency files to your project


<dependencies>
 <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>
</dependencies>

2. Properties profile application. properties

In src/main/resources/application properties set in the data source and jpa configuration.


spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

All configuration is in the above file and no additional XML and Java configurations are required.

In the above database configuration, you need to change your database address and username password.

ddl-auto =update configuration table name for hibernate, tables and columns of the database are automatically created (based on familiarity with Java entities), you can see more hibernate configuration here.

3. User entities

Create 1 User entity, User contains 3 attributes id,email and name. The User entity corresponds to the users table in the Mysql database.


@Entity
@Table(name = "users")
public class User {
 // ==============
 // PRIVATE FIELDS
 // ==============
 // An autogenerated id (unique for each user in the db)
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private long id;
 // The user email
 @NotNull
 private String email;
 // The user name
 @NotNull
 private String name;
 // ==============
 // PUBLIC METHODS
 // ==============
 public User() { }
 public User(long id) {
  this.id = id;
 }
 // Getter and setter methods
 // ...
} // class User

4. Data access layer for User entities UserDao

This case UserDao is very simple, you just need to inherit CrudRespositroy, has achieved save CrudRespositroy, delete, deleteAll, findOne and findAll. (compare the magic in these methods actually CrudRespositroy actually did not realize, and through to the dao method name can also achieve new method)


@Transactional
public interface UserDao extends CrudRepository<User, Long> {
 public User findByEmail(String email);
} 

5. Test controller UserController

Create a new query controller UserController


@Controller
public class UserController {
  @RequestMapping("/get-by-email")
  @ResponseBody
  public String getByEmail(String email) {
   String userId;
   User user = userDao.findByEmail(email);
   if (user != null) {
    userId = String.valueOf(user.getId());
    return "The user id is: " + userId;
   }
   return "user " + email + " is not exist.";
  }
 }

You can use a browser to access url http: / / 127.0.0.1:8080 / get - by - email & # 63; email=qiyadeng@gmail.com, you can get the user's Id (you can add 1 record to the Mysql database first).


Related articles: