Springboot和vue框架中怎么连接数据库的
时间: 2024-05-08 13:21:47 浏览: 129
web计算机网上销售系统(使用springboot作为后端,vue作为前端,mysql为数据库).zip
在Spring Boot中,可以使用JPA(Java Persistence API)或者MyBatis等ORM框架进行数据库操作,同时Spring Boot也支持多种数据库连接池,如HikariCP、Druid等。
在Vue中,可以通过axios或者fetch等HTTP客户端库与后端进行交互,从而实现与数据库的连接。
以下是一个简单的Spring Boot和Vue连接MySQL数据库的示例:
1. 在Spring Boot中配置MySQL数据库连接池和JPA:
```java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.example.repository")
public class DatabaseConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setPackagesToScan("com.example.entity");
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setJpaProperties(additionalProperties());
return entityManagerFactoryBean;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
private Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return properties;
}
}
```
2. 创建一个简单的实体类和对应的Repository:
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String email;
// getters and setters
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
3. 在Vue中使用axios发送HTTP请求获取数据:
```javascript
<script>
import axios from 'axios';
export default {
data() {
return {
users: []
};
},
mounted() {
axios.get('/users')
.then(response => {
this.users = response.data;
})
.catch(error => {
console.log(error);
});
}
}
</script>
```
以上示例中,我们在Spring Boot中使用JPA连接MySQL数据库,并且在Vue中使用axios发送HTTP请求获取数据。当然,如果你更喜欢MyBatis或者其他ORM框架,同样可以配置并使用。
阅读全文