扩展Spring Boot Web应用 - 连接MySQL数据库

2019-11-16  本文已影响0人  nzdxwl

之前建立了简单的Spring Boot Web 应用,又使用了Nacos做为数据配置以及服务注册和发现中心,这次再给应用加上连接到MySQL数据库的功能。

可以使用JPA或者MyBatis连接数据库,由于只是简单的示例,这里就使用JPA进行数据库连接。

配置

spring:
  datasource:
    url: "jdbc:mysql://192.168.43.104:3306/demo?serverTimezone=GMT%2B8&characterEncoding=utf8"
    username: "username"
    password: "password"

如果properties则使用以下格式:

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

关于数据库配置:

Production database connections can also be auto-configured by using a pooling DataSource. Spring Boot uses the following algorithm for choosing a specific implementation:
1. We prefer HikariCP for its performance and concurrency. If HikariCP is available, we always choose it.
2. Otherwise, if the Tomcat pooling DataSource is available, we use it.
3. If neither HikariCP nor the Tomcat pooling datasource are available and if Commons DBCP2 is available, we use it.
If you use the spring-boot-starter-jdbc or spring-boot-starter-data-jpa “starters”, you automatically get a dependency to HikariCP.

代码设置

Model

假设我们有个user表,主键是字符串类型的user_id, 那么我们创建对应的User类,指定该类是@Entity,并指明关联表 @Table(name="user"),再使用@Id指明主键,@Column做数据库表字段和类属性映射。

@Entity
@Table(name = "user")
public class User {
    
    @Id
    @Column(name = "user_id", nullable = false) 
    private String userId;
    //...
}

Dao

这里我们使用简单的crud接口,泛型参数一个是model类,一个是该类的主键数据类型

@Repository
public interface UserRepository extends CrudRepository<User, String>{
    public Optional<User> findById(String userId);
    //...
}

这样我们在Service类或者Controller注入UserRepository后即可操作MySQL数据库了。

常见问题

上一篇 下一篇

猜你喜欢

热点阅读