本文将介绍如何在Spring项目中链接、处理MySQL数据库。
该项目使用Spring Data JPA和Hibernate来链接、处理MySQL数据库,固然,这仅仅是其中一种方式,你也可使用Spring JDBC或者MyBatis.
Spring Data JPA是Spring Data的一个子项目,主要用于简化数据访问层的实现,使用Spring Data JPA能够轻松实现增删改查、分页、排序等。Spring Data拥有不少子项目,除了Spring Data JPA外,还有以下子项目:java
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了很是轻量级的对象封装,它将POJO与数据库表创建映射关系,是一个全自动的ORM框架,Hibernate能够自动生成SQL语句,自动执行,使得Java程序员能够为所欲为的使用对象编程思惟来操纵数据库。 Hibernate能够应用在任何使用JDBC的场合,既能够在Java的客户端程序使用,也能够在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate能够在应用EJB的J2EE架构中取代CMP,完成数据持久化的重任。
本文将介绍如何使用Spring Data JPA和Hibernate来链接、处理MySQL数据库。mysql
首先咱们须要对MySQL作一些准备处理。咱们将要在MySQL中建立db_example数据库,并建立springuser用户,拥有对db_example数据库的全部操做权限。打开MySQL , 输入如下命令:git
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数据库的全部操做权限
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
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 .github
新建src/main/resources/application.properties文件,配置相关属性,代码以下:web
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数据库,并设置用户名和密码。spring
建立src/main/java/hello文件夹(package),在该文件夹下新建User.java,Hibernate会将该entity类自动转化成数据库中的表格。User.java的完整代码以下:sql
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项目的主要程序入口。
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方面的内容,欢迎你们交流~~