0

0

java通过JPA进行数据库操作的实例详解

Y2J

Y2J

发布时间:2017-05-06 13:19:15

|

3240人浏览过

|

来源于php中文网

原创

今天给大家介绍一下如何springboot中连接mysql数据库,并使用jpa进行数据库的相关操作。

今天给大家介绍一下如何springboot中连接mysql数据库,并使用jpa进行数据库的相关操作。

步骤一:在pom.xml文件中添加MYSQl和JPA的相关Jar包依赖,具体添加位置在dependencies中,具体添加的内容如下所示。

 
     
      org.springframework.boot 
      spring-boot-starter-web 
     
     
      org.springframework.boot 
      spring-boot-starter-data-jpa 
     
     
      mysql 
      mysql-connector-java 
     
     
      org.apache.poi 
      poi 
      3.11 
    

步骤二:在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是密码

立即学习Java免费学习笔记(深入)”;

步骤三:编写数据库操作的实体类,实体类具体信息如下所示:

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 { 
  public List findByName(String name); 
  public List findBySex(char sex); 
  public List findByBirthday(Date birthday); 
  public List findBySendtime(Date sendtime); 
  public List findByPrice(BigDecimal price); 
  public List findByFloatprice(float floatprice); 
  public List 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 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 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 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 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 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 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 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. 阿里巴巴Java开发手册

相关文章

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
go语言 注释编码
go语言 注释编码

本专题整合了go语言注释、注释规范等等内容,阅读专题下面的文章了解更多详细内容。

32

2026.01.31

go语言 math包
go语言 math包

本专题整合了go语言math包相关内容,阅读专题下面的文章了解更多详细内容。

23

2026.01.31

go语言输入函数
go语言输入函数

本专题整合了go语言输入相关教程内容,阅读专题下面的文章了解更多详细内容。

16

2026.01.31

golang 循环遍历
golang 循环遍历

本专题整合了golang循环遍历相关教程,阅读专题下面的文章了解更多详细内容。

5

2026.01.31

Golang人工智能合集
Golang人工智能合集

本专题整合了Golang人工智能相关内容,阅读专题下面的文章了解更多详细内容。

6

2026.01.31

2026赚钱平台入口大全
2026赚钱平台入口大全

2026年最新赚钱平台入口汇总,涵盖任务众包、内容创作、电商运营、技能变现等多类正规渠道,助你轻松开启副业增收之路。阅读专题下面的文章了解更多详细内容。

268

2026.01.31

高干文在线阅读网站大全
高干文在线阅读网站大全

汇集热门1v1高干文免费阅读资源,涵盖都市言情、京味大院、军旅高干等经典题材,情节紧凑、人物鲜明。阅读专题下面的文章了解更多详细内容。

195

2026.01.31

无需付费的漫画app大全
无需付费的漫画app大全

想找真正免费又无套路的漫画App?本合集精选多款永久免费、资源丰富、无广告干扰的优质漫画应用,涵盖国漫、日漫、韩漫及经典老番,满足各类阅读需求。阅读专题下面的文章了解更多详细内容。

170

2026.01.31

漫画免费在线观看地址大全
漫画免费在线观看地址大全

想找免费又资源丰富的漫画网站?本合集精选2025-2026年热门平台,涵盖国漫、日漫、韩漫等多类型作品,支持高清流畅阅读与离线缓存。阅读专题下面的文章了解更多详细内容。

85

2026.01.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Spring中文手册
Spring中文手册

共0课时 | 0人学习

马士兵spring视频教程
马士兵spring视频教程

共25课时 | 9.1万人学习

Kotlin 教程
Kotlin 教程

共23课时 | 3.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号