1. 程式人生 > >從零學springboot——spring boot快速整合hibernate

從零學springboot——spring boot快速整合hibernate

  • 匯入資料庫連線依賴及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>
  • 在application.properties檔案中新增資料庫連線屬性及jpa配置
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = 123456
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 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 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
  • 自定義一個javabean,並使用註解@Entity進行ORM,並在主鍵上新增@Id和@GeneratedValue
@Entity
public class Person {
    @Id
    @GeneratedValue
    private long id;
    private String name;
    private int age;
    ...

其中@Id是用來標識主鍵的,而@GeneratedValue則是用來指定主鍵策略的。

  • 編寫持久化介面:
public interface PersonRepository extends CrudRepository<Person,Long>{
}

泛型中的第一個為要操作的物件,第二個為主鍵的型別,此時我們只需要對Person物件進行簡單的操作,即可操作資料庫的crud了。

  • 呼叫dao介面
@Autowired
private PersonRepository personRepository;

public Person savePerson(){
    Person person = new Person();
    person.setName("zhangsan");
    person.setAge(18);
    return personRepository.save(person);
}

此時我們啟動程式,啟動完成後,我們發現,資料庫已經自動將Person表建好,當我們呼叫savePerson方法後,對應的資料也已經入庫了。