SpringData快速入门

本文涉及的产品
云数据库 RDS MySQL,集群版 2核4GB 100GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: SpringData快速入门

好久没有写框架文章了,最近一直都在忙活数据结构,趁着今天有空赶紧写一篇SpringData框架入门。

框架简介

按照惯例,在学习框架之前,当然要先了解框架的作用,看官方定义:
SpringData是Spring的一个子项目,用于简化数据库访问,支持NoSQL和关系数据存储,其主要目的是使数据库的访问变得方便快捷。
SpringData致力于减少数据访问层的开发量,开发者唯一要做的,就只是声明持久层的接口,其它都交给SpringData来帮你完成。

HelloWorld

下面同样是通过一个HelloWorld级的案例来入门SpringData。
创建Java项目,导入Spring、JPA、SpringData、C3P0的jar包和mysql的驱动,因为SpringData是建立在Spring和JPA框架的基础之上的。
在src目录下创建db.properties文件,将数据源信息抽离出来:

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

接着创建spring的配置文件,进行如下配置:

<?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:property-placeholder location="classpath:db.properties"/>

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

此时可以测试一下数据源是否配置成功。

    public static void main(String[] args){
   
   
        try {
   
   
            ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
            DataSource dataSource = ctx.getBean(DataSource.class);
            System.out.println(dataSource.getConnection());
        } catch (SQLException e) {
   
   
            e.printStackTrace();
        }
    }

运行结果:

com.mchange.v2.c3p0.impl.NewProxyConnection@1efee8e7

此时证明代码编写无误,我们继续。
接着对JPA进行配置,如果没有了解过JPA的话,可以看我前面的文章。

<?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:property-placeholder location="classpath:db.properties"/>

    <bean id="dataSource"
          class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
    </bean>
    <!--配置JPA的EntityManagerFactory-->
    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <property name="packagesToScan" value="com.wwj.springdata"/>
        <property name="jpaProperties">
            <props>
                <!-- 生成的数据表的列的映射策略 -->
                <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>
</beans>

配置完后,我们同样测试一下JPA是否配置成功。
先创建一个持久化类:

package com.wwj.springdata;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "JPA_PERSON")
@Entity
public class Person {
   
   

    private Integer id;
    private String name;

    @GeneratedValue
    @Id
    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;
    }

    @Override
    public String toString() {
   
   
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

只需重新运行刚才的程序即可,框架会自动为我们创建持久化类对应的数据表,运行结果如下:

mysql> show tables;
+---------------+
| Tables_in_jpa |
+---------------+
| jpa_person    |
+---------------+
1 row in set (0.00 sec)

接下来配置事务管理器、配置事务和SpringData即可:

<?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:property-placeholder location="classpath:db.properties"/>

    <bean id="dataSource"
          class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
    </bean>
    <!--配置JPA的EntityManagerFactory-->
    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <property name="packagesToScan" value="com.wwj.springdata"/>
        <property name="jpaProperties">
            <props>
                <!-- 生成的数据表的列的映射策略 -->
                <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>

    <!--配置事务管理器-->
    <bean id="transactionManager"
          class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    <!--配置支持注解的事务-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--配置SpringData-->
    <jpa:repositories base-package="com.wwj.springdata"
                      entity-manager-factory-ref="entityManagerFactory"/>
</beans>

项目结构如下:
在这里插入图片描述
配置完成后,我们创建一个接口:

package com.wwj.springdata;

import org.springframework.data.repository.Repository;

public interface PersonRepository extends Repository<Person, Integer> {
   
   

    //根据名字获取信息
    Person getByName(String name);
}

通过该方法获取数据表的数据。
我们测试一下:

    public static void main(String[] args) {
   
   
        try {
   
   
            ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
            PersonRepository personRepository = ctx.getBean(PersonRepository.class);
            Person person = personRepository.getByName("aaa");
            System.out.println(person);
        } catch (Exception e) {
   
   
            e.printStackTrace();
        }
    }

运行结果:

Person{
   
   id=1, name='aaa'}

测试成功。

总结

到这里入门案例就编写完成了,可以看到,通过一个接口的抽象方法就可以实现数据表的操作,是不是很神奇呢?想了解SpringData的细节,请看下篇文章。

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
3月前
|
安全 算法 Java
SpringSecurity 快速入门
SpringSecurity 快速入门
54 3
|
9月前
|
Java 应用服务中间件 API
Webflux快速入门
Webflux快速入门
|
10月前
|
Java
30SpringBoot整合SpringData JPA
30SpringBoot整合SpringData JPA
38 0
|
2月前
|
Java 数据安全/隐私保护 Spring
SpringSecurity6从入门到实战之SpringSecurity快速入门
这篇文章是关于使用SpringSecurity 6进行快速入门的教程。首先介绍了所需的环境配置,包括SpringSecurity 6.0.8、SpringBoot 3.0.12和JDK 17。接着,通过步骤展示了如何创建一个新的SpringBoot工程,并添加Web支持。然后,运行工程并测试了Hello接口,确保其正常工作。之后,引入SpringSecurity依赖后,无需额外配置,系统即实现了基础的认证功能,自动重定向到登录页面。文章通过截图详细说明了这个过程,包括控制台日志、登录页面以及登录后的资源访问。
|
3月前
|
XML Java 数据库
springboot集成flowable
springboot集成flowable
|
3月前
|
Java 关系型数据库 数据库连接
Hibernate学习笔记(一)快速入门
Hibernate学习笔记(一)快速入门
|
3月前
|
SQL Java 关系型数据库
SpringBoot整合SpringData与JPA
SpringBoot整合SpringData与JPA
52 0
|
SQL 存储 XML
SpringData进阶篇-下
SpringData进阶篇-下
116 0
|
XML SQL Java
SpringData 进阶篇-上
SpringData 进阶篇-上
59 0
|
SQL XML NoSQL
SpringData 基础篇
SpringData 基础篇
90 0