JPA (Java Persistence API) 定義了一系列對(duì)象持久化的標(biāo)準(zhǔn),目前實(shí)現(xiàn)這一規(guī)范的產(chǎn)品有Hibernate各薇、TopLink等
直接上練習(xí)
項(xiàng)目結(jié)構(gòu)
一峭判、配置
在pom.xml中添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
在 application.yml 里 (這里用的 yaml 配置文件棕叫,一定要注意縮進(jìn),不然后果嚴(yán)重)
spring.jpa.hibernate.ddl-auto 有五個(gè)值
值 | 作用 |
---|---|
create | 每次運(yùn)行重新創(chuàng)建數(shù)據(jù)庫(kù)俺泣,會(huì)刪掉以前的數(shù)據(jù) |
create-drop | 程序停止的時(shí)候刪掉數(shù)據(jù)庫(kù) |
validate | 會(huì)驗(yàn)證現(xiàn)在的實(shí)體里面的參數(shù)和數(shù)據(jù)庫(kù)的參數(shù)是否一致伏钠,不一致會(huì)報(bào)錯(cuò) |
none | 什么也不做 |
update | 會(huì)保留以前的數(shù)據(jù)横漏,如果沒(méi)有表會(huì)創(chuàng)建表 |
spring:
profiles:
active: prod
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test
username: root
password: 123456
jpa:
hibernate:
ddl-auto: update
show-sql: true
在ManIfo里面
@Entity 數(shù)據(jù)庫(kù)映射實(shí)體
@Id 表明表里的id (一般主鍵什么的)
@GeneratedValue 自增長(zhǎng)
package com.alun;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* Created by Administrator on 2017/5/29.
*/
@Entity
public class ManInfo {
@Id
@GeneratedValue
private Integer id;
private String age;
private String nickname;
public ManInfo() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
}
運(yùn)行之后,數(shù)據(jù)庫(kù)就創(chuàng)建了一張表
![ spring boot jpa 創(chuàng)建數(shù)據(jù)庫(kù)1.png]
](http://upload-images.jianshu.io/upload_images/3044229-35b64d6f4da850dd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)