Spring Boot入门(2)使用MySQL数据库
介绍
本文将介绍如何在Spring项目中连接、处理MySQL数据库。
该项目使用Spring Data JPA和Hibernate来连接、处理MySQL数据库,当然,这仅仅是其中一种方式,你也可以使用Spring JDBC或者MyBatis.
Spring Data JPA是Spring Data的一个子项目,主要用于简化数据访问层的实现,使用Spring Data JPA可以轻松实现增删改查、分页、排序等。Spring Data拥有很多子项目,除了Spring Data Jpa外,还有如下子项目。
- Spring Data Commons
- Spring Data MongoDB
- Spring Data Redis
- Spring Data Solr
- Spring Data Gemfire
- Spring Data REST
- Spring Data Neo4j
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的ORM框架,Hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的J2EE架构中取代CMP,完成数据持久化的重任。
本文将介绍如何使用Spring Data JPA和Hibernate来连接、处理MySQL数据库。
准备
首先我们需要对MySQL做一些准备处理。我们将要在MySQL中创建db_example数据库,并创建springuser用户,拥有对db_example数据库的所有操作权限。打开MySQL , 输入以下命令:
mysql> create database db_example; -- 创建新数据库db_example mysql> create user 'springuser'@'localhost' identified by 'pwd123'; -- 创建新用户springuser,密码为pwd123 mysql> grant all on db_example.* to 'springuser'@'localhost'; -- 给予springuser用户对db_example数据库的所有操作权限
Spring Boot程序
Step1. 创建项目spring_mysql, 以及项目布局:
mkdir spring_mysql cd ./spring_mysql touch build.gradle mkdir -p src/main/java mkdir -p src/main/resources mkdir -p src/test/java mkdir -p src/test/resources
Step2 编写build.gradle
build.gradle代码如下:
buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.0.RELEASE") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' bootJar { baseName = 'gs-accessing-data-mysql' version = '0.1.0' } repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { compile("org.springframework.boot:spring-boot-starter-web") // JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) compile 'org.springframework.boot:spring-boot-starter-data-jpa' // Use MySQL Connector-J compile 'mysql:mysql-connector-java' testCompile('org.springframework.boot:spring-boot-starter-test') }
在上述Spring Boot项目中,主要使用spring-boot-starter-web ,spring-boot-starter-data-jpa和mysql:mysql-connector-java来实现在Web端操作MySQL .
Step3 配置属性文件
新建src/main/resources/application.properties文件,配置相关属性,代码如下:
spring.jpa.hibernate.ddl-auto=create spring.datasource.url=jdbc:mysql://localhost:3306/db_example spring.datasource.username=springuser spring.datasource.password=pwd123
在上述代码中,主要的数据库操作为新建(create),因为数据库中实现不存在相应的表格。使用MySQL的localhost服务器的3306端口的db_example数据库,并设置用户名和密码。
Step4 编写Java文件
创建src/main/java/hello文件夹(package),在该文件夹下新建User.java,Hibernate会将该entity类自动转化成数据库中的表格。User.java的完整代码如下:
package hello; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity // This tells Hibernate to make a table out of this class public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private String name; private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
在上述文件夹中新建UserRepository.java,其代码如下:
package hello; import org.springframework.data.repository.CrudRepository; import hello.User; // This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository // CRUD refers Create, Read, Update, Delete public interface UserRepository extends CrudRepository<User, Long> { }
这是repository接口, 它将会被Spring中的bean中自动执行。
在上述文件夹中新建MainController.java,代码如下:
package hello; 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.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import hello.User; import hello.UserRepository; @Controller // This means that this class is a Controller @RequestMapping(path="/demo") // This means URL's start with /demo (after Application path) public class MainController { @Autowired // This means to get the bean called userRepository // Which is auto-generated by Spring, we will use it to handle the data private UserRepository userRepository; @GetMapping(path="/add") // Map ONLY GET Requests public @ResponseBody String addNewUser (@RequestParam String name , @RequestParam String email) { // @ResponseBody means the returned String is the response, not a view name // @RequestParam means it is a parameter from the GET or POST request User n = new User(); n.setName(name); n.setEmail(email); userRepository.save(n); return "Saved"; } @GetMapping(path="/all") public @ResponseBody Iterable<User> getAllUsers() { // This returns a JSON or XML with the users return userRepository.findAll(); } }
这是Spring应用的新控制器(Controller)。
在上述文件夹中新建Application.java,代码如下:
package hello; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
这是该Spring Boot项目的主要程序入口。
Step5 创建可执行jar包
cd spring_mysql gradle build
执行完毕后,会在build/libs文件夹下生成gs-accessing-data-mysql-0.1.0.jar .
运行及测试
使用以下命令启动该Spring Boot项目
java -jar build/libs/gs-accessing-data-mysql-0.1.0.jar
在浏览器端测试,输入以下网址:
localhost:8080/demo/add?name=Alex&email=alex@baidu.com localhost:8080/demo/add?name=Jclian&email=github@sina.com localhost:8080/demo/add?name=Bob&email=bob@google.com localhost:8080/demo/add?name=Cook&email=cook@apple.com localhost:8080/demo/add?name=Mark&email=mark@west.com
上述程序将会name和email参数的值解析成数据库中user表中的记录并储存,浏览器界面如下图:
在浏览器中输入网址localhost:8080/demo/all,即可刚看我们我们插入到MySQL中的记录(JSON格式):
最后我们去MySQL中查看数据是否插入成功,结果如下图所示:
结束语
本文将介绍如何使用Spring Data JPA和Hibernate来连接、处理MySQL数据库。
本次分享到此结束,接下来还会继续更新Spring Boot方面的内容,欢迎大家交流~~

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
【转】宽字节注入详解
前言 在mysql中,用于转义的函数有addslashes,mysql_real_escape_string,mysql_escape_string等,还有一种情况是magic_quote_gpc,不过高版本的PHP将去除这个特性。 首先,宽字节注入与HTML页面编码是无关的,笔者曾经看到 <meta charset=utf8> 就放弃了尝试,这是一个误区,SQL注入不是XSS。虽然他们中编码的成因相似,不过发生的地点不同。 很多网上的材料都说程序使用了宽字节来处理程序,却又不指出具体是指什么程序。本文就介绍一下具体漏洞发生的原理与简单的利用。在这里我们限定使用的语言是PHP5.4,数据库MYSQL5.6。 涉及到的一些概念 字符、字符集与字符序 字符(character)是组成字符集(characterset)的基本单位。对字符赋予一个数值(encoding)来确定这个字符在该字符集中的位置。 字符序(collation)指同一字符集内字符间的比较规则。 UTF8 由于ASCII表示的字符只有128个,因此网络世界的规范是使用UNICODE编码,但是用A...
- 下一篇
以太坊智能合约编程入门(一)
原文地址:https://medium.com/@ConsenSys/a-101-noob-intro-to-programming-smart-contracts-on-ethereum-695d15c1dab4 1-ABBewYWJfdIFhgwBt8mfGQ.png 有些人说以太坊太难用了,现在就写一篇入门教程,讲一下怎么使用以太坊构建智能合约和应用。 第一部分 总览关键的术语以及以太坊客户端和智能合约语言 第二部分 讨论工作流以及dapp框架和工具 第三部分 编程,快速编写测试,以及使用truffle开发一个智能合约dapp 第一部分 介绍 如果你还是加密货币行业的新手,不太了解比特币,更不知道它是怎么工作的,那么你应该先去看看Andreas Antonopoulos写的关于比特币的书,熟悉一下这个行业。然后再看看以太坊的白皮书。 如果你已经熟悉了加密货币,那么可以继续读下去了。在开始之前,你不需要知道加密经济学的所有计算机科学知识,也不必知道以太坊是如何改进比特币的那些论文。 起始示例 以太坊官方网站ethereum.org 上有一些示例。以及官方的文档。还有一个学习智能合约...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- CentOS关闭SELinux安全模块
- Linux系统CentOS6、CentOS7手动修改IP地址
- Windows10,CentOS7,CentOS8安装Nodejs环境
- CentOS7,8上快速安装Gitea,搭建Git服务器
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果
- Jdk安装(Linux,MacOS,Windows),包含三大操作系统的最全安装
- Red5直播服务器,属于Java语言的直播服务器
- CentOS8,CentOS7,CentOS6编译安装Redis5.0.7
- Docker使用Oracle官方镜像安装(12C,18C,19C)
- CentOS7编译安装Cmake3.16.3,解决mysql等软件编译问题