springboot数据库配置MySQL
时间: 2024-10-04 14:00:25 浏览: 32
在Spring Boot项目中配置MySQL数据库通常涉及以下几个步骤:
1. 添加依赖:首先,在项目的pom.xml文件中添加Spring Data JPA、Spring JDBC以及MySQL的驱动依赖。例如:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!-- 如果是Spring Boot 2.x以上版本 -->
<scope>runtime</scope>
</dependency>
</dependencies>
```
2. 配置application.properties或application.yml:在这个文件中,你需要指定数据库的相关信息,如URL、用户名、密码等:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase?useSSL=false
spring.datasource.username=myusername
spring.datasource.password=mypassword
spring.jpa.hibernate.ddl-auto=update
```
或者在YAML格式下:
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydatabase?useSSL=false
username: myusername
password: mypassword
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
```
3. 定义数据源和JPA实体:创建一个DataSource bean,并告诉Spring如何映射实体到数据库表:
```java
@Configuration
public class DataSourceConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl(...);
dataSource.setUsername(...);
dataSource.setPassword(...);
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
JpaPlatformTransactionManager transactionManager = new JpaPlatformTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory());
return transactionManager;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan("com.example.myapp.entity"); // 替换为你应用的实体包名
factoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
return factoryBean;
}
}
```
4. 创建实体类(Entity):定义一个或多个继承自`@Entity`的类,表示数据库中的表。
完成上述步骤后,你可以通过`@Repository`注解的类操作数据库,Spring会自动管理连接池和事务处理。
阅读全文