全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

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<User, Integer>,具体有什么作用呢?

我这里给大家简单的介绍一下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命令,具体是怎么对应的我会再下一节中给大家详细的介绍一下,现在先卖个关子。

步骤六:数据库的表名和字段信息如下所示:


 

到这里关于SpringBoot中连接MYSQL数据库,并使用JPA进行数据库的相关操作就介绍完毕了,希望对大家的学习有所帮助,也希望大家多多支持。


# jpa连接mysql数据库  # spring  # boot连接mysql  # boot使用mysql  # JPA之映射mysql text类型的问题  # Springboot2.0配置JPA多数据源连接两个mysql数据库方式  # Spring boot基于JPA访问MySQL数据库的实现  # 解决springboot的JPA在Mysql8新增记录失败的问题  # Spring Data Jpa Mysql使用utf8mb4编码的示例代码  # springboot使用spring-data-jpa操作MySQL数据库  # Spring-Data-JPA整合MySQL和配置的方法  # Spring Boot 添加MySQL数据库及JPA实例  # 在JPA项目启动时如何新增MySQL字段  # 所示  # 给大家  # 就可以  # 介绍一下  # 类中  # 这个问题  # 大大的  # 实体类  # 的是  # 那就是  # 有什么  # 我就  # 我会  # 第一个  # 都要  # 你要  # 是由  # 还会  # 是怎么  # 第二个 


相关文章: 网站制作公司,橙子建站是合法的吗?  jQuery 常见小例汇总  已有域名和空间如何快速搭建网站?  建站主机选择指南:服务器配置与SEO优化实战技巧  清除minerd进程的简单方法  学校建站服务器如何选型才能满足性能需求?  网站制作和推广的区别,想自己建立一个网站做推广,有什么快捷方法马上做好一个网站?  武汉外贸网站制作公司,现在武汉外贸前景怎么样啊?  山东网站制作公司有哪些,山东大源集团官网?  建站之星安装后如何配置SEO及设计样式?  php json中文编码为null的解决办法  实例解析Array和String方法  太原网站制作公司有哪些,网约车营运证查询官网?  建站之星如何配置系统实现高效建站?  定制建站流程步骤详解:一站式方案设计与开发指南  如何通过多用户协作模板快速搭建高效企业网站?  如何用wdcp快速搭建高效网站?  小米网站链接制作教程,请问miui新增网页链接调用服务有什么用啊?  建站之星导航菜单设置与功能模块配置全攻略  股票网站制作软件,网上股票怎么开户?    大连网站制作费用,大连新青年网站,五年四班里的视频怎样下载啊?  建站主机空间推荐 高性价比配置与快速部署方案解析  武清网站制作公司,天津武清个人营业执照注销查询系统网站?  广东企业建站网站优化与SEO营销核心策略指南  公司网站建设制作费用,想建设一个属于自己的企业网站,该如何去做?  天河区网站制作公司,广州天河区如何办理身份证?需要什么资料有预约的网站吗?  北京的网站制作公司有哪些,哪个视频网站最好?  哈尔滨网站建设策划,哈尔滨电工证查询网站?  武汉网站如何制作,黄黄高铁武穴北站途经哪些村庄?  h5网站制作工具有哪些,h5页面制作工具有哪些?  制作门户网站的参考文献在哪,小说网站怎么建立?  如何选择可靠的免备案建站服务器?  如何在Windows环境下新建FTP站点并设置权限?  网页设计与网站制作内容,怎样注册网站?  建站之星如何实现PC+手机+微信网站五合一建站?  婚礼视频制作网站,学习*后期制作的网站有哪些?  如何在新浪SAE免费搭建个人博客?  个人摄影网站制作流程,摄影爱好者都去什么网站?  打鱼网站制作软件,波克捕鱼官方号怎么注册?  建站之星五站合一营销型网站搭建攻略,流量入口全覆盖优化指南  广东专业制作网站有哪些,广东省能源集团有限公司官网?  深圳网站制作平台,深圳市做网站好的公司有哪些?  C++ static_cast和dynamic_cast区别_C++静态转换与动态类型安全转换  平台云上自助建站如何快速打造专业网站?  建站之星后台密码如何安全设置与找回?  Android自定义控件实现温度旋转按钮效果  建站主机与服务器功能差异如何区分?  导航网站建站方案与优化指南:一站式高效搭建技巧解析  重庆网站制作公司哪家好,重庆中考招生办官方网站? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。