標籤:
註:在閱讀本文前,請先閱讀:
使用IntelliJ IDEA開發SpringMVC網站(一)開發環境
使用IntelliJ IDEA開發SpringMVC網站(二)架構配置
六、資料庫配置
下面,就要通過一個簡單的例子,來介紹,SpringMVC如何整合Spring Data JPA(有Hibernate JPA提供),來進行強大的資料庫訪問,並通過本章節的講解,更加深刻地認識Controller是如何進行請求處理的,相信看完這一章節,你就可以開始你的開發工作了。
準備工作:
在src\main\java中建立兩個包:com.gaussic.model、com.gaussic.repository,將在後面用上。
1、建立Mysql資料庫
本文的講解使用Mysql資料庫,如果使用其它資料庫的讀者,可以去網上參考其他的配置教程,在此不做太多的敘述。資料庫是一個底層的東西,底層的細節對上層的抽象並沒有太大的影響,因此,只要配置好資料庫,本章的內容仍然是適用於所有資料庫的(貌似如此)。
假設我們現在要建立一個小小的部落格系統,其資料庫ER圖如下所示(當然這隻是一個小小的例子,真實的部落格系統遠遠比這要複雜的多):
在資料庫中,有兩張表:
(1)使用者表user:儲存使用者的登入資訊,主鍵id設為自增;
(2)博文表blog:儲存使用者發表的博文,主鍵id設為自增,其中有一個外鍵userid連結到user表。
詳細表結構如所示:
2、IntelliJ IDEA匯入資料庫
對於此前所接觸的一些常用的架構中,一張資料表往往對應一個Java Bean。在SpringMVC中,這個Java Bean相當於model。那麼,這個類是否需要自己來寫呢?不需要,利用IntelliJ IDEA可以幫我們自動的產生這些JavaBean。
首先,右鍵項目,選擇Add Framework Support:
下拉選擇JavaEE Persistence,右邊provider選擇Hibernate,Libraries選擇Set up Later(Maven已經將所需jar包都匯入了):
在這一步結束後,我們可以發現,在resources裡面產生了persistence.xml設定檔,左側邊欄出現了一個Persistence標題(若沒有請點擊左下角那個灰框):
persistemce.xml具體如下:
<?xml version="1.0" encoding="UTF-8"?><persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"> <persistence-unit name="NewPersistenceUnit"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.connection.url" value=""/> <property name="hibernate.connection.driver_class" value=""/> <property name="hibernate.connection.username" value=""/> <property name="hibernate.connection.password" value=""/> <property name="hibernate.archive.autodetection" value="class"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> <property name="hbm2ddl.auto" value="update"/> </properties> </persistence-unit></persistence>
我們先不著急填寫這個設定檔。點開左側邊欄的Persistence,顯示如所示:
右鍵項目名,選擇Generate Persistence Mapping,再選擇By Database Schema:
出現如下介面,其主要需要配置的地方如紅框所示:
點擊Choose Data Source右邊的三個點選擇資料來源,在彈出的介面左上方選擇“+”,選擇Mysql:
在如下介面填寫主機、連接埠號碼、資料庫名、使用者名稱、密碼,如果驅動丟失點擊下面的Download可以下載驅動,點擊 Test Connection可以測試資料庫是否串連成功:
在以上介面配置完成後,點OK,回到如下頁面,package填寫model包(1),勾選Show default relationships以顯示所有資料庫關係(2),再點擊重新整理按鈕(3),將會找到資料庫中的兩個表,展開兩個表並全選(4,除了外鍵),再勾選Generate Column Defination以產生每一列的描述資訊(5),點擊OK,選擇Yes。
稍後,開啟model包,可以看到產生了兩個Java Bean,在SpringMVC中稱為兩個實體,它們對應了資料庫的兩張表:
BlogEntity如下所示:
package com.gaussic.model;import javax.persistence.*;/** * Created by dzkan on 2015/10/4. */@Entity@Table(name = "blog", schema = "", catalog = "springdemo")public class BlogEntity { private int id; private String title; private String content; private UserEntity userByUserid; @Id @Column(name = "id", nullable = false, insertable = true, updatable = true) public int getId() { return id; } public void setId(int id) { this.id = id; } @Basic @Column(name = "title", nullable = true, insertable = true, updatable = true, length = 100) public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Basic @Column(name = "content", nullable = true, insertable = true, updatable = true, length = 255) public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BlogEntity that = (BlogEntity) o; if (id != that.id) return false; if (title != null ? !title.equals(that.title) : that.title != null) return false; if (content != null ? !content.equals(that.content) : that.content != null) return false; return true; } @Override public int hashCode() { int result = id; result = 31 * result + (title != null ? title.hashCode() : 0); result = 31 * result + (content != null ? content.hashCode() : 0); return result; } @ManyToOne @JoinColumn(name = "userid", referencedColumnName = "id", nullable = false) public UserEntity getUserByUserid() { return userByUserid; } public void setUserByUserid(UserEntity userByUserid) { this.userByUserid = userByUserid; }}
我們可以看到,在BlogEntity中,不僅包含了其所有的列,還多產生了一個:
private UserEntity userByUserid;
在SpringMVC中,可以通過這個類作為外鍵,進行外鍵的相關操作,具體如何使用將在後面講解。
再看UserEntity:
package com.gaussic.model;import javax.persistence.*;import java.util.Collection;/** * Created by dzkan on 2015/10/4. */@Entity@Table(name = "user", schema = "", catalog = "springdemo")public class UserEntity { private int id; private String firstName; private String lastName; private String password; private Collection<BlogEntity> blogsById; @Id @Column(name = "id", nullable = false, insertable = true, updatable = true) public int getId() { return id; } public void setId(int id) { this.id = id; } @Basic @Column(name = "firstName", nullable = true, insertable = true, updatable = true, length = 45) public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Basic @Column(name = "lastName", nullable = true, insertable = true, updatable = true, length = 45) public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Basic @Column(name = "password", nullable = true, insertable = true, updatable = true, length = 45) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserEntity that = (UserEntity) o; if (id != that.id) return false; if (firstName != null ? !firstName.equals(that.firstName) : that.firstName != null) return false; if (lastName != null ? !lastName.equals(that.lastName) : that.lastName != null) return false; if (password != null ? !password.equals(that.password) : that.password != null) return false; return true; } @Override public int hashCode() { int result = id; result = 31 * result + (firstName != null ? firstName.hashCode() : 0); result = 31 * result + (lastName != null ? lastName.hashCode() : 0); result = 31 * result + (password != null ? password.hashCode() : 0); return result; } @OneToMany(mappedBy = "userByUserid") public Collection<BlogEntity> getBlogsById() { return blogsById; } public void setBlogsById(Collection<BlogEntity> blogsById) { this.blogsById = blogsById; }}
同樣產生了:
private Collection<BlogEntity> blogsById;
同樣是為了滿足外鍵的需求。
3、設定資料庫
既然資料庫已經匯入了,那麼前期準備工作基本完成,還需要進行最終的配置。
首先,開啟mvc-dispatcher-servlet.xml,添加下列配置(如果某些地方報錯,請選中並按Alt + Insert補全配置):
<!-- 表示JPA Repository所在的包 --><jpa:repositories base-package="com.gaussic.repository"/><bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="defaultPersistenceUnit"/></bean><!-- 交易管理 --><bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/></bean><tx:annotation-driven transaction-manager="transactionManager"/>
講解:
(1) jpa:repositories:這一部分涉及到資料庫的介面,將在後面詳解;
(2)entityManagerFactory:實體管理器工廠,讀取persistence.xml配置;
(3)transactionManager:交易管理員,利用entityManager進行交易管理;
(4)tx:annotation-driven:開啟交易管理員的註解驅動,可以使用註解的方法操縱資料庫。
整體如下所示:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--指明 controller 所在包,並掃描其中的註解--> <context:component-scan base-package="com.gaussic.controller"/> <!-- 靜態資源(js、image等)的訪問 --> <mvc:default-servlet-handler/> <!-- 開啟註解 --> <mvc:annotation-driven/> <!--ViewResolver 視圖解析器--> <!--用於支援Servlet、JSP視圖解析--> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 表示JPA Repository所在的包 --> <jpa:repositories base-package="com.gaussic.repository"/> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="defaultPersistenceUnit"/> </bean> <!-- 交易管理 --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/></beans>
下面,填充persistence.xml,將persistence-unit的name改為 defaultPersistenceUnit。在下面的檔案中,我添加了一些更為詳細的配置:
<?xml version="1.0" encoding="UTF-8"?><persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"> <persistence-unit name="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <!-- 使用MySQL方言 --> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/> <!-- 資料庫連接的URL地址 --> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/springdemo"/> <!-- 資料庫連接的驅動 --> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/> <!-- 資料庫連接的使用者名稱 --> <property name="hibernate.connection.username" value="root"/> <!-- 資料庫連接的密碼 --> <property name="hibernate.connection.password" value="root"/> <!-- 顯示SQL語句 --> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.connection.useUnicode" value="true"/> <property name="hibernate.connection.characterEncoding" value="UTF-8"/> <!-- 在顯示SQL語句時格式化語句 --> <property name="hibernate.format_sql" value="true"/> <property name="hibernate.use_sql_comments" value="false"/> <!-- 自動輸出schema建立DDL語句 --> <property name="hibernate.hbm2ddl.auto" value="update"/> <!-- 資料庫連接逾時後自動重連 --> <property name="hibernate.connection.autoReconnect" value="true"/> <property name="connection.autoReconnectForPools" value="true"/> <property name="connection.is-connection-validation-required" value="true"/> </properties> </persistence-unit></persistence>
現在,重新啟動tomcat,如果沒有報錯,說明資料庫已經配置完成了,接下來就要講解資料庫的相關開發工作。
使用IntelliJ IDEA開發SpringMVC網站(三)資料庫配置