關係數據庫中數據類型和面嚮對象語言中類型的映射,有個完整的映射表:Hibernate-provided BasicTypes
這裏簡單記錄下,我做映射實驗的記錄,以功能點展開:
Configuration
spring:
application:
name: hibernate-playground
datasource:
username: root
password: xxxx
url: jdbc:mysql://192.168.124.30:3306/hibernate?serverTimezone=GMT%2B8
# schema creation control
jpa:
hibernate:
# 自動更新數據庫表結構
ddl-auto: update
show-sql: true
指定數據庫表名
@Entity(name = "booker") // 這裏指定表名爲booker
@Data // lombok,不用在意
public class Book {}
上面這種情況,假如沒有指定,表名就是book
.
指定數據庫列名
這裏指定name
屬性對應的列爲alias
// 指定對象屬性對應的數據庫列名
@Column(name = "alias")
private String name;
映射枚舉類型
枚舉類型可以映射爲字符串表示和數字表示。
下面例子展示如何使用兩種方式,其中Type就是一個簡單的枚舉類。
// 映射枚舉類
// 數字方式 表列數據類型爲int
@Enumerated(EnumType.ORDINAL)
private Type type;
// 字符串方式 varchar(255)
@Enumerated(EnumType.STRING)
private Type type2;
計算列
數據庫表中不存這個列,這個列是用sql語句計算出來的。
比如:表裏有a和b兩個列,使用sql語句:
select a,b, a+b as c from sample_table;
在hibernate當中使用Formula來構造計算列:
// 虛擬列(此列在數據庫中不存在)
@Formula(value = "length(alias)")
private int nameLen;
內嵌類型
比如位置對象需要在出版社和餐館兩個對象中使用,但是又不想每次都在實體中聲明,像這樣:
public class Publisher{
//..... other properties
int altitude; // 緯度
int longtitude; // 經度
}
爲了提高複用性,把位置對象分出來:
public class Location{
//..... other properties
int altitude; // 緯度
int longtitude; // 經度
}
public class Publisher{
private Location location;
}
下面這個例子展示如何做到:
在嵌入對象類上添加@Embeddable
註解,聲明這個對象可以被嵌入到其他實體(Entity)類中:
@Embeddable
public class Location{
//..... other properties
int altitude; // 緯度
int longtitude; // 經度
}
然後在使用 被嵌入對象類上使用:
public class Publisher{
private Location location;
}
被嵌入類中包含嵌入類的字段,比如在這個例子中publisher表包含altitude
列。
映射日期
java.util.Date
日期可以映射爲Date(日期),Time(時間),timestamp(日期加時間) ,參考:Mapping Date/Time Values
@Column(name = "timestamp")
@Temporal(TemporalType.TIMESTAMP) //可以在這裏改
private Date timestamp;
Appendix A: Maven Dependency
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--注意這個依賴的版本要對應-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.13</version>
</dependency>
<!--註解方式加setter和getter,toString-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>