1. 程式人生 > >SpringBoot(2) JPA-Hibernate

SpringBoot(2) JPA-Hibernate

start cati lec 生成 ats ava -a 實體 service

1)pom.xml添加MySQL,spring-data-jpa依賴

  <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>

 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId></dependency>

2)在application.properties文件中配置MySQL連接配置文件  

########################################################
###datasource
########################################################
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10

3)在application.properties文件中配置JPA配置信息

########################################################
### Java Persistence Api
########################################################
# Specify the DBMS
spring.jpa.database = MYSQL
# 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
#[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy]
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

4)測試

  實體類:@Entity標註類上,進行實體類的持久化操作,當JPA檢測到我們的實體類當中有@Entity 註解的時候,會在數據庫中生成對應的表結構信息。使用@Id指定主鍵, 使用代碼@GeneratedValue(strategy=GenerationType.AUTO) 指定主鍵的生成策略,mysql默認的是自增長,例:@Id @GeneratedValue(strategy=GenerationType.AUTO)private int id;//主鍵.

  service接口:

    public interface CatRepository extends CrudRepository<Cat, Integer>{}

  service實現類:  

    @Service
    public class CatService {
      @Resource
      private CatRepository catRepository;//service的接口
      @Transactional//事務的綁定.
      public void save(Cat cat){
        catRepository.save(cat);
      }
    }

SpringBoot(2) JPA-Hibernate