歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Spring Data學習筆記-Hello World

Spring Data學習筆記-Hello World

日期:2017/3/1 9:21:14   编辑:Linux編程

工作已簽,瞬間感覺沒目標了。頹廢了幾天之後決定還是繼續踏上Java編程之路,接下來幾篇記錄Spring Data的學習過程。

Spring Data : Spring 的一個子項目。用於簡化數據庫訪問,支持NoSQL和關系數據存儲。其主要目標是使數據庫的訪問變得方便快捷。

SpringData項目所支持 NoSQL存儲:

  • –MongoDB(文檔數據庫)
  • –Neo4j(圖形數據庫)
  • –Redis(鍵/值存儲)
  • –Hbase(列族數據庫)

SpringData項目所支持的關系數據存儲技術:–JDBC–JPA

JPA Spring Data : 致力於減少數據訪問層 (DAO) 的開發量. 開發者唯一要做的,就只是聲明持久層的接口,其他都交給 Spring Data JPA 來幫你完成!

框架怎麼可能代替開發者實現業務邏輯呢?

比如:當有一個 UserDao.findUserById() 這樣一個方法聲明,大致應該能判斷出這是根據給定條件的 ID 查詢出滿足條件的 User 對象。SpringData JPA 做的便是規范方法的名字,根據符合規范的名字來確定方法需要實現什麼樣的邏輯。

使用 Spring Data JPA 進行持久層開發需要的四個步驟:

–配置Spring 整合JPA

–在 Spring 配置文件中配置 Spring Data,讓 Spring 為聲明的接口創建代理對象。配置了<jpa:repositories> 後,Spring 初始化容器時將會掃描 base-package 指定的包目錄及其子目錄,為繼承Repository 或其子接口的接口創建代理對象,並將代理對象注冊為Spring Bean,業務層便可以通過 Spring 自動封裝的特性來直接使用該對象。

–聲明持久層的接口,該接口繼承 Repository,Repository 是一個標記型接口,它不包含任何方法,如必要,SpringData 可實現 Repository其他子接口,其中定義了一些常用的增刪改查,以及分頁相關的方法。

–在接口中聲明需要的方法。SpringData 將根據給定的策略(具體策略稍後講解)來為其生成實現代碼。

首先從萬能的Hello world開始~~

項目的目錄結構如下圖

wKioL1YsRDrARvLUAAD8DAsPm6o372.jpg

applicationContext.xml配置如下

<?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:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<!-- 配置自動掃描的包 -->
<context:component-scan base-package="com.springdata"></context:component-scan>

<!-- 1. 配置數據源 -->
<context:property-placeholder location="classpath:db.properties" />

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>

<!-- 配置其他屬性 -->
</bean>

<!-- 2. 配置 JPA 的 EntityManagerFactory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
</property>
<property name="packagesToScan" value="com.springdata"></property>
<property name="jpaProperties">
<props>
<!-- 二級緩存相關 -->
<!-- <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="net.sf.ehcache.configurationResourceName">ehcache-hibernate.xml</prop> -->
<!-- 生成的數據表的列的映射策略 -->
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<!-- hibernate 基本屬性 -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>

<!-- 3. 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>

<!-- 4. 配置支持注解的事務 -->
<tx:annotation-driven transaction-manager="transactionManager" />

<!-- 5. 配置 SpringData -->
<!-- 加入 jpa 的命名空間 -->
<!-- base-package: 掃描 Repository Bean 所在的 package -->
<jpa:repositories base-package="com.springdata"
entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>

</beans>

db.properties配置如下

jdbc.user=root
jdbc.password=
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///test

實體類User

@Table(name="user")
@Entity
public class User {
@GeneratedValue
@Id
private Integer id;
private String username;
private String password;

//省略getter setter

@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password="
+ password + "]";
}

}

UserRepository接口

public interface UserRepository extends Repository<User, Integer>{

public User getByUsername(String username);

public User getById(Integer id);
}

測試類

public class Test {

private ApplicationContext applicationContext = null;

{
applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
}

@org.junit.Test
public void testDataSource() {
DataSource dataSource = applicationContext.getBean(DataSource.class);
System.out.println(dataSource);
}

@org.junit.Test
public void testJPA() {
//測試自動生產數據庫表

}

@org.junit.Test
public void testHelloWorld() {
UserRepository userRepository = applicationContext.getBean(UserRepository.class);
User user = null;
// user = userRepository.getByUsername("admin");
user = userRepository.getById(1);
System.out.println(user);
}
}

你沒看錯,就這麼點代碼。數據庫中的表是根據實體類自動生成的,測試類中的testHelloWorld方法可以從數據庫中取出user對象。

本文源碼下載

------------------------------------------分割線------------------------------------------

免費下載地址在 http://linux.linuxidc.com/

用戶名與密碼都是www.linuxidc.com

具體下載目錄在 /2015年資料/10月/25日/Spring Data學習筆記-Hello World/

下載方法見 http://www.linuxidc.com/Linux/2013-07/87684.htm

------------------------------------------分割線------------------------------------------

Spring Data 的詳細介紹:請點這裡
Spring Data 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved