我们在Spring Boot下使用Spring Data JPA,在项目的Maven依赖里添加spring-boot-stater-data-jpa,然后只需定义DataSource、实体类和数据访问层,并在需要使用数据访问的地方注入数据访问层的Bean即可,无须任何额外配置。
pom.xml引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency><!-- mysql连接的jar包 -->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
application.properties配置:
# 配置连接池,默认使用的是tomcat的连接池,但实际很少用tomcat的连接池
spring.datasource.url=jdbc:mysql://localhost:3306/NewData?useUnicode=true&characterEncoding=UTF8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 配置方言 否则提示:Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
# 自动更新数据库表结构,也可以是 validate | update | create | create-drop
spring.jpa.hibernate.hbm2ddl.auto=update
# 显示sql语句
spring.jpa.show-sql=true
spring.jpa.open-in-view=false
spring.jackson.serialization.indent-output=true
定义实体映射