介紹
本文將介紹如何在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中查看數據是否插入成功,結果如下圖所示:
