连接mysql需要如下一些依赖
依赖项(maven -> pom.xml)。
<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>
在application.properties需要一些额外的配置设置,必须喜欢
application.properties (src/main/resources/application.properties)
# DataSource settings: set here your own configurations for the database
# connection. In this example we have "netgloo_blog" as database name and
# "root" as username and password.
spring.datasource.url = jdbc:mysql://localhost:8889/database_name
spring.datasource.username = mysql-userId
spring.datasource.password = mysql-pwd
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# 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 (Not necessary to add but you can use this too)
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
现在您的 EntityManager 对象将在您启动 Spring Boot 配置时构建。
以上定义的配置足以连接您的本地 mysql 数据库,但这里还有一些配置,您需要让您的代码更具可读性。
启用 JPARepositories,这样 CRUD 存储库必须在定义的包中定义。
像这样将@EnableJPARepositories("basepackage.*") 添加到您的SpringBootMainApplicationClass..
@SpringBootApplication
@EnableJPARepositories("com.demo.application.*.repositories")
@ComponentScan("com.demo.application.*")
public class SpringBootMainApplicationClass {
public static void main(String[] args) {
SpringApplication.run(SpringBootMainApplicationClass.class, args);
}
}
通过在MainClass 中添加@EnableJPARepositories 注释,用户可以使您的代码更具可读性,并且EntityManager 对象仅限于仅定义的包。