JPA:Java Persistence API是一個標準規範及接口(API)來實現ORM(object-relational mapping)框架,JPA通過註解(annotation) [如:@Entity、@Table、@Column等註解] 或XML描述物件-關係表的對映關係,並將執行期的實體物件持久化到資料庫中。
接續上一個文章:
JDBCtamplate 要新增實體類別是這樣:
@Data
public class User implements RowMapper<User> {
private int id;
private String username;
private String password;
// 必需重寫mapRow方法 新增實體類別方法
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
return user;
}
}
JPA簡化成這樣:
@Data
@Entity
public class User{
private int id;
@Id
//ID 自動增加由資料庫自動管理
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String username;
private String password;
}
JPA的底層基本依賴設定,設定資料庫連接:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependency>
#設定資料庫連接資訊:
####springboot用mysql等關聯式資料庫,需要設定連接資訊。application.properties檔案中設定
spring.datasource.url=jdbc:mysql://127.0.0.1/book?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true//主控台顯示sql敘述與否
server.port=8080
用實例介紹jpa建置物件 與 關係對應的實體模型
這裡撰寫
這是自動產生一份報紙裡面欄位有標題\圖文還有虛擬欄位(@Transient)
ID\title\enum\keywordlists
@Entity
@Data
public class Paper implements Serializable {
@Id
/**
* Description: 由数据库控制,auto是程序统一控制
*/
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(nullable = false, unique = true)
@NotEmpty(message = "标题不能为空")
private String title;
/**
* Description: 枚举类型
*/
@Column(columnDefinition="enum('图','图文','文')")
private String type;//类型
/**
* Description: Boolean类型默认false
*/
private Boolean available = Boolean.FALSE;
@Size(min=0, max=20)
private String keyword;
@Size(max = 255)
private String description;
@Column(nullable = false)
private String body;
//如想建立虛擬欄位就在屬性上方加入這個註解@Transient。專案執行後會自動產生資料表。
@Transient
private List keywordlists;
public List getKeywordlists() {
return Arrays.asList(this.keyword.trim().split("|"));
}
public void setKeywordlists(List keywordlists) {
this.keywordlists = keywordlists;
}
}
JpaEntityDemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JpaEntityDemoApplication {
public static void main(String[] args) {
SpringApplication.run(JpaEntityDemoApplication.class, args);
}
}