Spring Data学习笔记-Hello World


工作已签,瞬间感觉没目标了。颓废了几天之后决定还是继续踏上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.bkjia.com/

用户名与密码都是www.bkjia.com

具体下载目录在 /2015年资料/10月/25日/Spring Data学习笔记-Hello World/

下载方法见

------------------------------------------分割线------------------------------------------

Spring Data 的详细介绍:请点这里
Spring Data 的下载地址:请点这里

本文永久更新链接地址

相关内容