首頁 > Java > java教程 > 主體

java透過JPA進行資料庫操作的實例詳解

Y2J
發布: 2017-05-06 13:19:15
原創
2955 人瀏覽過

今天要來跟大家介紹如何SpringBoot中連接Mysql資料庫,並使用JPA進行資料庫的相關操作。

今天要來跟大家介紹如何SpringBoot連接Mysql資料庫,並使用JPA進行資料庫的相關操作。

步驟一:在pom.xml檔案中加入MYSQl和JPA的相關Jar套件依賴,具體新增位置在dependencies中,具體新增的內容如下所示。

<!--数据库相关配置--> 
    <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-web</artifactId> 
    </dependency> 
    <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-data-jpa</artifactId> 
    </dependency> 
    <dependency> 
      <groupId>mysql</groupId> 
      <artifactId>mysql-connector-java</artifactId> 
    </dependency> 
    <dependency> 
      <groupId>org.apache.poi</groupId> 
      <artifactId>poi</artifactId> 
      <version>3.11</version> 
    </dependency>
登入後複製

步驟二:在application.properties設定檔中加入資料庫的相關配置,設定資訊如下所示。

spring.datasource.url = jdbc:mysql://localhost:3306/webtest 
spring.datasource.username = root 
spring.datasource.password = 220316 
spring.datasource.driverClassName = com.mysql.jdbc.Driver 
# Specify the DBMS 
spring.jpa.database = MYSQL 
# Show or not log for each sql query 
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
登入後複製

這裡跟大家解釋一下:webtest代表資料庫名稱、root是使用者名稱、220316是密碼

步驟三:資料庫操作的實體類,實體類別具體資訊如下:

package example.entity; 
import javax.persistence.*; 
import javax.validation.constraints.NotNull; 
import java.math.BigDecimal; 
import java.util.Date; 
@Entity 
@Table(name = "user") 
public class User { 
  @Id 
  @GeneratedValue(strategy = GenerationType.AUTO) 
  private int id; 
 
  @Column(name = "name", nullable = true, length = 30) 
  private String name; 
 
  @Column(name = "height", nullable = true, length = 10) 
  private int height; 
 
  @Column(name = "sex", nullable = true, length = 2) 
  private char sex; 
 
  @Temporal(TemporalType.DATE) 
  private Date birthday; 
 
  @Temporal(TemporalType.TIMESTAMP) 
  private Date sendtime; // 日期类型,格式:yyyy-MM-dd HH:mm:ss 
 
  @Column(name = "price", nullable = true, length = 10) 
  private BigDecimal price; 
 
  @Column(name = "floatprice", nullable = true, length = 10) 
  private float floatprice; 
 
 
  @Column(name = "doubleprice", nullable = true, length = 10) 
  private double doubleprice; 
 
  public Date getSendtime() { 
    return sendtime; 
  } 
 
  public void setSendtime(Date sendtime) { 
    this.sendtime = sendtime; 
  } 
 
  public BigDecimal getPrice() { 
    return price; 
  } 
 
  public void setPrice(BigDecimal price) { 
    this.price = price; 
  } 
 
  public float getFloatprice() { 
    return floatprice; 
  } 
 
  public void setFloatprice(float floatprice) { 
    this.floatprice = floatprice; 
  } 
 
  public double getDoubleprice() { 
    return doubleprice; 
  } 
 
  public void setDoubleprice(double doubleprice) { 
    this.doubleprice = doubleprice; 
  } 
 
  public User() { } 
 
  public char getSex() { 
    return sex; 
  } 
 
  public void setSex(char sex) { 
    this.sex = sex; 
  } 
 
  public Date getBirthday() { 
    return birthday; 
  } 
 
  public void setBirthday(Date birthday) { 
    this.birthday = birthday; 
  } 
 
  public User(int id) { 
    this.id = id; 
  } 
 
  public int getId() { 
    return id; 
  } 
 
  public void setId(int id) { 
    this.id = id; 
  } 
 
  public String getName() { 
    return name; 
  } 
 
  public void setName(String name) { 
    this.name = name; 
  } 
 
  public int getHeight() { 
    return height; 
  } 
 
  public void setHeight(int height) { 
    this.height = height; 
  } 
}
登入後複製

大家這裡要注意的是:實體類別中的類別名稱和欄位屬性都要和資料庫中表格和字段相互對應。以下給出一張MYSQL-JAVA各種屬性的對應關係圖:

步驟四:編寫dao層的資料操作類,dao數據操作類別如下:

package example.dao; 
import example.entity.User; 
import org.springframework.data.repository.CrudRepository; 
import javax.transaction.Transactional; 
import java.math.BigDecimal; 
import java.util.Date; 
import java.util.List; 
 
@Transactional 
public interface UserDao extends CrudRepository<User, Integer> { 
  public List<User> findByName(String name); 
  public List<User> findBySex(char sex); 
  public List<User> findByBirthday(Date birthday); 
  public List<User> findBySendtime(Date sendtime); 
  public List<User> findByPrice(BigDecimal price); 
  public List<User> findByFloatprice(float floatprice); 
  public List<User> findByDoubleprice(double doubleprice); 
}
登入後複製

大家這裡可能會有疑問,為什麼要繼承CrudRepository,具體有什麼作用呢?

我這裡給大家簡單的介紹一下JPA中一些常用的用法和使用準則:

1.首先就是要繼承CrudRepository這個方法,裡麵包含的兩個參數的具體意義是:第一個參數表示所操作的實體類別名稱,第二個參數表示實體類別中主鍵的類型。

2.繼承完之後就可以使用一些繼承自父類別的方法了,例如上面所示可以使用findBy+“你要查詢的欄位名稱”,透過這樣的方法就可以輕輕鬆鬆實作SQL查詢的功能了。

說這裡可能大家還是有點迷糊,給大家一個例子就知道了:

例如上面的findByName(String name)其實等價於SQL語句中的select *from user where name=? 。這樣一對比大家是不是馬上就清楚這個方法到底代表什麼意義了吧。

步驟五:寫controller這個控制類,控制類具體資訊如下所示:

package example.controller; 
import example.dao.UserDao; 
import example.entity.User; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.ResponseBody; 
import java.math.BigDecimal; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.util.List; 
@Controller 
public class UserController { 
  @Autowired 
  private UserDao userDao; 
  @RequestMapping("/getName") 
  @ResponseBody 
  public String getByName(String name) { 
    List<User> userList = userDao.findByName(name); 
    if (userList != null && userList.size()!=0) { 
      return "The user length is: " + userList.size(); 
    } 
    return "user " + name + " is not exist."; 
  } 
 
  @RequestMapping("/getSex") 
  @ResponseBody 
  public String getBySex(char sex) { 
    List<User> userList = userDao.findBySex(sex); 
    if (userList != null && userList.size()!=0) { 
      return "The user length is: " + userList.size(); 
    } 
    return "user " + sex + " is not exist."; 
  } 
 
  @RequestMapping("/getBirthday") 
  @ResponseBody 
  public String findByBirthday(String birthday) { 
    System.out.println("birthday:"+birthday); 
    SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd"); 
    List<User> userList = null; 
    try { 
      userList = userDao.findByBirthday(formate.parse(birthday)); 
    } catch (ParseException e) { 
      e.printStackTrace(); 
    } 
    if (userList != null && userList.size()!=0) { 
      return "The user length is: " + userList.size(); 
    } 
    return "user " + birthday + " is not exist."; 
  } 
 
  @RequestMapping("/getSendtime") 
  @ResponseBody 
  public String findBySendtime(String sendtime) { 
    System.out.println("sendtime:"+sendtime); 
    SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    List<User> userList = null; 
    try { 
      userList = userDao.findBySendtime(formate.parse(sendtime)); 
    } catch (ParseException e) { 
      e.printStackTrace(); 
    } 
    if (userList != null && userList.size()!=0) { 
      return "The user length is: " + userList.size(); 
    } 
    return "user " + sendtime + " is not exist."; 
  } 
 
  @RequestMapping("/getPrice") 
  @ResponseBody 
  public String findByPrice(BigDecimal price) { 
    List<User> userList = null; 
    userList = userDao.findByPrice(price); 
    if (userList != null && userList.size()!=0) { 
      return "The user length is: " + userList.size(); 
    } 
    return "user " + price + " is not exist."; 
  } 
 
  @RequestMapping("/getFloatprice") 
  @ResponseBody 
  public String findFloatprice(float floatprice) { 
    List<User> userList = null; 
    userList = userDao.findByFloatprice(floatprice); 
    if (userList != null && userList.size()!=0) { 
      return "The user length is: " + userList.size(); 
    } 
    return "user " + floatprice + " is not exist."; 
  } 
 
  @RequestMapping("/getDoubleprice") 
  @ResponseBody 
  public String findByPrice(double doubleprice) { 
    List<User> userList = null; 
    userList = userDao.findByDoubleprice(doubleprice); 
    if (userList != null && userList.size()!=0) { 
      return "The user length is: " + userList.size(); 
    } 
    return "user " + doubleprice + " is not exist."; 
  } 
}
登入後複製

大家這裡可能會有一個很大的疑問,我當初也對這個問題深深的不理,那就是userDao沒有實例化為什麼能夠直接使用呢?

現在我要為大家解釋為什麼會這樣:

其實不是這個userDao沒有實例化,只是實例化是由系統自動完成的。只要在userDao的上方加入@Autowired屬性就可以實作介面自動的實例化了,完全不需要像以前一樣需要去寫什麼userDaoImp之類的實作類別了。這樣做就可以大大的挺高程式碼的簡易程度,開發速度大大的挺高。

我知道現在可能還會有人問這樣一個問題:那就是自動實例化了,可是實例化怎麼知道dao類別要實現什麼的增刪改查的功能呀,dao程式碼裡面壓根就沒說啊?其實有心人可能已經發現了,上一步的時候我們解釋了一下findBy+「字段名」的具體作用是什麼,這其實就是這個問題的答案。其實dao層中各種方法就是daoimp中各種實作類別中的SQl指令,具體是怎麼對應的我會再下一節給大家詳細的介紹一下,現在先賣個關子。

步驟六:資料庫的表名與欄位資訊如下所示:


 

##【相關推薦】

1.

Java免費影片教學

2.

極客學院Java影片教學

3.

L巴巴Java開發手冊

以上是java透過JPA進行資料庫操作的實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!