我們都知道Spring是一個非常優秀的JavaEE整合框架它盡可能的減少我們開發的工作量和難度
在持久層的業務邏輯方面Spring開源組織又給我們帶來了同樣優秀的Spring Data JPA
通常我們寫持久層都是先寫一個接口再寫接口對應的實現類在實現類中進行持久層的業務邏輯處理
而現在Spring Data JPA幫助我們自動完成了持久層的業務邏輯處理我們要做的僅僅是聲明一個持久層接口
下載開發所需要的發布包
)springframeworkRELEASEwithdocszip
下載地址framework
)hibernatereleaseFinalzip
下載地址
)Spring Data JPA
Spring Data JPA
下載地址data/jpa
Spring Data Commons
下載地址data/commons
)其他一些依賴包可以從 上查找下載
新建一個Web項目 springdatajpa把相應的jar包放到/WebRoot/WEBINF/lib目錄下
我也沒有挑選哪些是不需要的最後用到的jar如下
antlrjarsfcglibjaraopalliancejarmonsloggingjaraspectjweaverRELEASEjarcommonslangjardomjjarhibernatecommonsannotationsFinaljarhibernatecoreFinaljarhibernateentitymanagerFinaljarhibernatejpaapiFinaljarjavassistGAjarjbossloggingGAjarjbosstransactionapi__specFinaljarlogjjarmysqlconnectorjavabinjarorgspringframeworkaopRELEASEjarorgspringframeworkasmRELEASEjarorgspringframeworkaspectsRELEASEjarorgspringframeworkbeansRELEASEjarorgntextRELEASEjarorgntextsupportRELEASEjarorgreRELEASEjarorgspringframeworkexpressionRELEASEjarorgspringframeworkinstrumentRELEASEjarorgspringframeworkinstrumenttomcatRELEASEjarorgspringframeworkjdbcRELEASEjarorgspringframeworkjmsRELEASEjarorgspringframeworkjsresourcesRELEASEjarorgspringframeworkormRELEASEjarorgspringframeworkoxmRELEASEjarorgspringframeworktestRELEASEjarorgspringframeworktransactionRELEASEjarorgspringframeworkwebRELEASEjarorgspringframeworkwebportletRELEASEjarorgspringframeworkwebservletRELEASEjarslfjapijarslfjlogjjarspringdatacommonscoreMjarspringdatajpaRELEASEjar
在MySql數據庫中建立一個叫spring_data_jpa的數據庫
create database spring_data_jpa default character set utf;
JPA配置文件persistence
xml
)在src目錄下建立一個叫META
INF的文件夾
)在META
INF文件夾下建立persistence
xml文件
persistence
xml內容如下
xml version=
encoding=
UTF
?><persistence version=
xmlns=
xmlns:xsi=
instance
xsi:schemaLocation=
_
_
xsd
>
<persistence
unit name=
myJPA
transaction
type=
RESOURCE_LOCAL
>
<provider>org
hibernate
ejb
HibernatePersistenceprovider>
<properties>
<property name=
hibernate
dialect
value=
org
hibernate
dialect
MySQL
Dialect
/>
<property name=
nnection
driver_class
value=
com
mysql
jdbc
Driver
/>
<property name=
nnection
username
value=
root
/>
<property name=
nnection
password
value=
root
/>
<property name=
nnection
url
value=
jdbc:mysql://localhost:
/spring_data_jpa?useUnicode=true&characterEncoding=UTF
/>
<property name=
hibernate
max_fetch_depth
value=
/>
<property name=
hibernate
hbm
ddl
auto
value=
update
/>
<property name=
hibernate
show_sql
value=
true
/>
<property name=
hibernate
format_sql
value=
true
/>
<property name=
javax
persistence
validation
mode
value=
none
/>
properties>
persistence
unit>
persistence>
Spring配置文件applicationContext
xml
在src目錄下建立applicationContext
xml
applicationContext
xml內容如下
xml version=
encoding=
UTF
?> <beans xmlns=
xmlns:xsi=
instance
xmlns:context=
xmlns:aop=
xmlns:tx=
xmlns:p=
xmlns:cache=
xmlns:jpa=
xsi:schemaLocation=
beans
xsd
context
xsd
aop
xsd
tx
xsd
cache
xsd
jpa
xsd
>
<context:annotation
config />
<context:component
scan base
package=
cn
luxh
app
/>
<bean id=
entityManagerFactory
class=
org
springframework
orm
jpa
LocalContainerEntityManagerFactoryBean
>
<property name=
persistenceUnitName
value=
myJPA
/>
bean>
<bean id=
transactionManager
class=
org
springframework
orm
jpa
JpaTransactionManager
>
<property name=
entityManagerFactory
ref=
entityManagerFactory
/>
bean>
<tx:annotation
driven transaction
manager=
transactionManager
/>
<jpa:repositories base
package=
cn
luxh
app
repository
/>
beans>
web
xml
web
xml內容如下
xml version=
encoding=
UTF
?><web
app version=
xmlns=
xmlns:xsi=
instance
xsi:schemaLocation=
app_
_
xsd
> <display
name>display
name>
<context
param>
<param
name>webAppRootKeyparam
name>
<param
value>springdatajpa
rootparam
value> context
param> <context
param>
<param
name>log
jConfigLocationparam
name>
<param
value>classpath:log
j
propertiesparam
value> context
param> <listener>
<listener
class>org
springframework
web
util
Log
jConfigListenerlistener
class> listener>
<filter>
<filter
name>characterEncodingFilterfilter
name>
<filter
class>org
springframework
web
filter
CharacterEncodingFilterfilter
class>
<init
param>
<param
name>encodingparam
name>
<param
value>UTF
param
value>
init
param>
filter> <filter
mapping>
<filter
name>characterEncodingFilterfilter
name>
<url
pattern>/*url
pattern> filter
mapping>
<context
param>
<param
name>contextConfigLocationparam
name>
<param
value>classpath:applicationContext
xmlparam
value> context
param> <listener>
<listener
class>org
sprntext
ContextLoaderListenerlistener
class> listener>
<listener>
<listener
class>org
springframework
web
util
IntrospectorCleanupListenerlistener
class>
listener>
<welcome
file
list>
<welcome
file>index
jspwelcome
file> welcome
file
list>web
app>
日志配置
在src目錄下建立log
j
properties文件
log
j
properties內容如下
log
j
rootLogger=INFO
CONSOLE
FI
apache=true # 應用於控制台 log
j
appender
CONSOLE=org
apache
log
j
ConsoleAppender log
j
appender
Threshold=INFO log
j
appender
CONSOLE
Target=System
out log
j
appender
CONSOLE
layout=org
apache
log
j
PatternLayout log
j
appender
CONSOLE
layout
ConversionPattern=[framework] %d
%c
%
r [%t] %
p %c %x
%m%n #log
j
appender
CONSOLE
layout
ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD] n%c[CATEGORY]%n%m[MESSAGE]%n%n #應用於文件 log
j
appender
FILE=org
apache
log
j
DailyRollingFileAppenderlog
j
appender
FILE
File=${springdatajpa
root}/springdatajpa
log log
j
appender
FILE
Append=true log
j
appender
FILE
layout=org
apache
log
j
PatternLayout log
j
appender
FILE
layout
ConversionPattern=[framework] %d
%c
%
r [%t] %
p %c %x
%m%n
所有環境配完畢
開始寫一個Spring Data JPA 的增刪改查
)建立相應的包
)領域模型實體類User
package cn
luxh
app
domain;import javax
persistence
Entity;import javax
persistence
GeneratedValue;import javax
persistence
Id;import javax
persistence
Table;/** * 用戶信息 * @author Luxh *
*/@Entity@Table(name=
t_user
)public class User {
@Id
@GeneratedValue
private Integer id;
//賬號
private String account;
//姓名
private String name;
//密碼
private String password;
//省略 getter和setter方法}
)聲明持久層接口UserRepository
讓UserRepository接口繼承CrudRepository
T是領域實體
ID是領域實體的主鍵類型
CrudRepository實現了相應的增刪改查方法
package cn
luxh
app
repository;import org
springframework
data
repository
CrudRepository;import cn
luxh
app
domain
User;/** * 用戶持久層接口 * @author Luxh *
*/public interface UserRepository extends CrudRepository{
}
不再需要持久層接口實現類
)業務層
一般多層架構是控制層調用業務層
業務層再調用持久層
所以這裡寫個業務層
a
業務層接口
package cn
luxh
app
service;import cn
luxh
app
domain
User;/** * 用戶業務接口 * @author Luxh *
*/public interface UserService {
/**
* 保存用戶
* @param user
*/
void saveUser(User user)
/**
* 根據id查找用戶
* @param id
* @return
*/
User findUserById(Integer id)
/**
* 更新用戶
* @param user
*/
void updateUser(User user)
/**
* 根據ID刪除用戶
* @param id
*/
void deleteUserById(Integer id)
}
b
業務層接口實現類
package cn
luxh
app
service;import org
springframework
beans
factory
annotation
Autowired;import org
springframework
stereotype
Service;import org
springframework
transaction
annotation
Transactional;import cn
luxh
app
domain
User;import cn
luxh
app
repository
UserRepository;/** * 用戶業務服務實現類 * @author Luxh *
*/@Service(
userService
)public class UserServiceImpl implements UserService{
@Autowired
private UserRepository userRepository;//注入UserRepository
@Override
@Transactional
public void saveUser(User user) {
userRepository
save(user)
}
@Override
@Transactional(readOnly=true)
public User findUserById(Integer id) {
return userRepository
findOne(id)
}
@Override
@Transactional
public void updateUser(User user) {
userRepository
save(user)
}
@Override
@Transactional
public void deleteUserById(Integer id) {
userRepository
delete(id)
}}
)編寫測試用例
在執行測試的時候
發現如下錯誤
Caused by: java
lang
NoSuchMethodError: javax
persistence
spi
PersistenceUnitInfo
getValidationMode()Ljavax/persistence/ValidationMode;
at org
hibernate
ejb
Enfigure(Ejb
Configuration
java:
)
at org
hibernate
ejb
HibernatePersistence
createContainerEntityManagerFactory(HibernatePersistence
java:
)
at org
springframework
orm
jpa
LocalContainerEntityManagerFactoryBean
createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean
java:
)
at org
springframework
orm
jpa
AbstractEntityManagerFactoryBean
afterPropertiesSet(AbstractEntityManagerFactoryBean
java:
)
at org
springframework
beans
factory
support
AbstractAutowireCapableBeanFactory
invokeInitMethods(AbstractAutowireCapableBeanFactory
java:
)
at org
springframework
beans
factory
support
AbstractAutowireCapableBeanFactory
initializeBean(AbstractAutowireCapableBeanFactory
java:
)
…
more
網上說是新版本的Hibernate跟javaee
jar裡面的JPA接口沖突了
解決方法
移除MyEclipse自帶的Java EE
Libraries
自己新建一個user libraries
加入Java EE中的jsf
api
jar
jsf
impl
jar和jstl
jar
再加入Tomcat中自帶的
servlet
api
jar
用servletapijar替換掉javaeejar就沒問題了
測試代碼
package cn
luxh
app
test;import org
junit
Assert;import org
junit
Test;import org
junit
runner
RunWith;import org
springframework
beans
factory
annotation
Autowired;import org
sprintext
ContextConfiguration;import org
sprintext
junit
SpringJUnit
ClassRunner;import cn
luxh
app
domain
User;import cn
luxh
app
service
UserService;@RunWith(SpringJUnit
ClassRunner
class)@ContextConfiguration({
/applicationContext
xml
}) public class UserTest {
@Autowired
private UserService userService;
//保存用戶
@Test
public void testSaveUser() {
User user = new User()
user
setAccount(
LiHuai
)
user
setName(
李壞
)
user
setPassword(
)
userService
saveUser(user)
}
//根據id查找用戶
@Test
public void testFindUserById() {
Integer id =
;
User user = userService
findUserById(id)
Assert
assertEquals(
李壞
user
getName())
}
//更新用戶
@Test
public void testUpdateUser() {
Integer id =
;
User user = userService
findUserById(id)
user
setName(
李尋歡
)
userService
updateUser(user)
}
//根據id刪除用戶
@Test
public void testDeleteUserById() {
Integer id =
;
userService
deleteUserById(id)
}}
使用Spring Data JPA相當的簡單
我們只需要定義持久層的接口
不需要編寫實現代碼
步驟和注意點
)在spring配置文件中添加倉庫接口的掃描路徑
)編寫領域實體
需要按照JPA規范
)編寫倉庫Repository接口
依靠Spring Data規范定義接口方法
比如按照規范定義一個數據訪問接口方法 List findByName(String name)
Spring Data JPA 就會自動轉化為 select u from User u where u
name = ?
可以使用的倉庫接口有
Repository:
是 Spring Data的一個核心接口
它不提供任何方法
開發者需要在自己定義的接口中聲明需要的方法
CrudRepository:
繼承Repository
提供增刪改查方法
可以直接調用
PagingAndSortingRepository:
繼承CrudRepository
具有分頁查詢和排序功能
JpaRepository:
繼承PagingAndSortingRepository
針對JPA技術提供的接口
JpaSpecificationExecutor:
可以執行原生SQL查詢
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26344.html