springBoot+Jpa(hibernate)資料庫基本操作
阿新 • • 發佈:2019-02-09
Jpa是什麼?
JPA是一套規範,不是一套產品,那麼像Hibernate,TopLink,JDO他們是一套產品,如果說這些產品實現了這個JPA規範,那麼我們就可以叫他們為JPA的實現產品。
Spring-data-jpa依賴於Hibernate,具體的示例如下:
專案配置
在pom.xml中新增相關依賴,加入內容如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId></dependency>
在application.xml中配置,資料庫連線資訊如下:
server.port=8081spring.datasource.url = jdbc:mysql://localhost:3306/student?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull spring.datasource.username = root spring.datasource.password = root spring.datasource.driverClassName = com.mysql.jdbc.Driver# Specify the DBMS spring.jpa.database = MYSQL # Show or not log for each sql query輸入sql語句 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
注:spring.jpa.show-sql =true 是在控制檯輸入sql語句
對spring.jpa.hibernate.ddl-auto 這個屬性,主要作用 是:自動建立、更新、驗證資料表結構,該引數的幾種配置如下:
create
:每次載入hibernate時都會刪除上一次的生成的表,然後根據你的model類再重新來生成新表,哪怕兩次沒有任何改變也要這樣執行,這就是導致資料庫表資料丟失的一個重要原因。create-drop
:每次載入hibernate時根據model類生成表,但是sessionFactory一關閉,表就自動刪除。update
:最常用的屬性,第一次載入hibernate時根據model類會自動建立起表的結構(前提是先建立好資料庫),以後載入hibernate時根據model類自動更新表結構,即使表結構改變了但表中的行仍然存在不會刪除以前的行。要注意的是當部署到伺服器後,表結構是不會被馬上建立起來的,是要等應用第一次執行起來後才會。validate
:每次載入hibernate時,驗證建立資料庫表結構,只會和資料庫中的表進行比較,不會建立新表,但是會插入新值。
@Entity @Table(name = "t_bank_account") public class BankAccount extends JpaRepositoriesAutoConfiguration{ @Id @GeneratedValue(strategy = GenerationType.AUTO) private String cardno; private String name; private Long id; private BigDecimal money; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCardno() { return cardno; } public void setCardno(String cardno) { this.cardno = cardno; } public String getName() { return name; } public void setName(String name) { this.name = name; } public BigDecimal getMoney() { return money; } public void setMoney(BigDecimal money) { this.money = money; } }
建立服務訪問資料庫的DAO:
public interface BankAccountDao extends CrudRepository<BankAccount, Long> { //根據編號查詢 public BankAccount findById(Long id); @Query(value = "select * from t_bank_account where name like %?1%",nativeQuery = true) @Modifying public List<BankAccount> findByNameLike(String name);//NotLike --- 等價於 SQL 中的 "not like",比如 findByNameNotLike(String name); public Page<BankAccount> findAll(Pageable pageable); //聯合查詢資料 @Query(value = "SELECT b.id,a.name as name,b.name,a.age,b.cardno,b.money from user a LEFT JOIN t_bank_account b on a.id=b.id and b.id=?1",nativeQuery = true) @Modifying public List<BankAccount> findOrderById(Integer id); //源生sql插入 @Query(value = "insert into t_bank_account(cardno,name,money) value(?1,?2,?3)",nativeQuery = true) @Modifying @Transactional public void insertBank_account(String cardNo, String name, BigDecimal money); //源生sql修改 @Query(value = "update t_bank_account set name = ?2 where id=?1",nativeQuery = true) @Modifying @Transactional public void updateOne(Long id,String name); //源生sql 刪除 @Query(value = "delete from t_bank_account where id = ?1",nativeQuery = true) @Modifying @Transactional public void deteteBankAccountById(Long id); }
該類繼承CrudRepository,通過檢視CrudRepository介面的API文件,可以看到該介面本身實現了建立(save),更新(save),刪除(delete),查詢(findId,findAll)等基本的操作函式,因此我們在開發過程中,就沒有必要在繼續進行開發定義了
上面還有使用源生的sql進行查詢,注意的是提交的時候@Trancational是必須要寫的。
Controller控制檯示例如下:
public class BankAccountController{ @Resource BankAccountDao accountDao; @ApiOperation(value = "查詢銀行使用者") @RequestMapping(value = "/findById" , method = RequestMethod.GET) public Object findById(@RequestParam(value = "id",required = false) Long id){ Iterable<BankAccount> bList; if(id!=null){ BankAccount user = accountDao.findById(id); if(user == null){ return "該資料項不存在"; }else{ return "cardNo:" + user.getCardno() + " , name:" + user.getName()+",money:"+user.getMoney(); } }else{ bList = accountDao.findAll(); } return bList; } @ApiOperation(value = "姓名查詢銀行使用者資訊") @RequestMapping(value = "findName",method = RequestMethod.GET) public List<BankAccount> findName(@RequestParam(value = "name")String name){ List<BankAccount> bList = accountDao.findByNameLike(name); return bList; } @ApiOperation(value = "查詢銀行使用者資料") @RequestMapping(value = "findIds",method = RequestMethod.GET) public List<BankAccount> findIds(@RequestParam(value = "id")Integer id){ List<BankAccount> bList = accountDao.findOrderById(id); return bList; } @ApiOperation(value = "新增銀行資料") @RequestMapping(value = "saveBankAccount",method = RequestMethod.POST) public String addBankAccount(@RequestParam(value ="cardNo") String cardNo, @RequestParam(value = "name") String name, @RequestParam(value = "money")BigDecimal money){ BankAccount account = new BankAccount(); account.setMoney(money); account.setName(name); account.setCardno(cardNo); accountDao.insertBank_account(cardNo,name,money); //accountDao.save(account); return " Add success!";// } @ApiOperation(value = "修改銀行資料") @RequestMapping(value = "updateBankAccount",method = RequestMethod.POST) public String updateBankAccount(@RequestParam(value ="id") Long id, @RequestParam(value = "name") String name){ accountDao.updateOne(id,name); return " update success!"; } @ApiOperation(value = "刪除銀行資料") @RequestMapping(value = "delAccountId",method = RequestMethod.POST) public String delBankAccount(@RequestParam(value = "id") Long id){ BankAccount user = accountDao.findById(id); if(user==null){ return "該資料項不存在!"; }else{ // accountDao.delete(id);//jar自帶的刪除方法 accountDao.deteteBankAccountById(id);//源生的刪除方法 } return "success!"; }
具體的原始碼可以在這裡進行下載如有需要的
http://download.csdn.net/download/juanmiao/10113527