Spring boot 四 JPA Hibernate
阿新 • • 發佈:2019-02-05
JPA : 資料庫持久化規範 (也是 關係對映設計的規範)
hibernate : 實現了 JPA 的框架。
spring-boot-jpa:在原有 hibernate 框架的基礎上在做繼續包裝,簡化。
下面是 spring-boot-jpa 的使用方式。、
1、在pom.xml 中新增 依賴包:
2、編寫 application.properties
3、建立 實體對映物件
4、建立 物件 Repository 介面
5、建立 物件服務
6、建立 物件 Controller
1、在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>
2、在 src/main/resouces 下建立 :
application.properties
#server.port=8080
# 資料庫訪問配置
# 主資料來源,預設的
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username= root
spring.datasource.password= root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
#指定資料庫
spring.jpa.database=mysql
# 是否顯示sql語句
spring.jpa.show-sql=true
# hibernate ddl auto (create create-drop update)
spring.jpa.hibernate.ddl-auto=update
# 選擇自己的 命名策略 ImprovedNamingStrategy (比如 orderItem >> order_item)
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy
3、建立 實體物件
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "userName")
private String name;
private String orderItem;
。。。get set 。。。
}
4、建立介面 PersonRepository 繼承 CrudRepository
/*這裡第一個泛型 Person 代表使用物件 Integer 代表 id型別*/
public interface PersonRepository extends CrudRepository<Person, Integer> {
}
5、建立 PersonService 注入 PersonRepository 類
@Service
public class PersonService {
@Resource
private PersonRepository mPersonReposity;
@Transactional//加入事物管理
public void save(Person p){
mPersonReposity.save(p);
}
@Transactional
public void delete(int id){
mPersonReposity.delete(id);
}
public Iterable<Person> getAll(){
return mPersonReposity.findAll();
}
}
6、建立 物件 Controller
@RestController
@RequestMapping("/person")
public class PersonController {
@Resource
public PersonService mPersonService;
@RequestMapping("/save")
public String save(){
Person p = new Person();
p.setName("zhang ");
p.setOrderItem("1");
mPersonService.save(p);
return "save OK";
}
@RequestMapping("/delete")
public String delete(){
mPersonService.delete(1);
return "delete Ok";
}
@RequestMapping("/getAll")
public Iterable<Person> getAll(){
return mPersonService.getAll();
}
}
測試:
127.0.0.1:8080/person/save 儲存
127.0.0.1:8080/person/getAll 查詢
127.0.0.1:8080/person/delete 刪除