SpringData-JPA操作数据库

来源:互联网 发布:js保存数据到本地文件 编辑:程序博客网 时间:2024/05/16 11:34

一、什么是springdata?

Spring Data的任务是为数据访问提供一个熟悉的、一致的、基于Spring的编程模型,同时仍然保留底层数据存储的特殊特征。它使使用数据访问技术,关系型数据库,非关系型数据库,map-reduce框架和基于云服务变得更加容易。这是来自springdata官网的解释,简单的说springdata可以操作关系型数据库以及非关系新数据库,使得操作更加简单快捷,还有更多的强大的功能。详情读者可自行去官网查看官方资料http://projects.spring.io/spring-data/。

二、搭建springdata框架

上面经过对springdata一番简单的介绍,下面我们直接上代码,通过代码来体验springdata的真正用途,在下面的代码中,我们将整个号jpa来实现对数据库的操作。

1.首先我们建立一个java项目,然后导入相关jar包(这里没有使用maven),由于导入的包太多,而且也比较杂乱,这里我已经将jar包上传,读者可前往下载
https://github.com/ljcan/SpringData
然后我们先在项目目录下创建一个db.properties文件来写数据源的信息。代码如下:

jdbc.user=rootjdbc.password=123456jdbc.driverClass=com.mysql.jdbc.Driverjdbc.jdbcUrl=jdbc:mysql:///jpa

建好数据源后我们开始来搭建spring框架,这个就不用详细讲解了,我们直接看代码吧。

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/context http://www.springframework.org/schema/context/spring-context-4.3.xsd        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.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="cn.shinelon.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 -->    <!-- 加入springdata的命名空间 -->    <!-- base-package这个属性自动扫描Repository Bean所在的package -->    <jpa:repositories base-package="cn.shinelon.springdata"     entity-manager-factory-ref="entityManagerFactory"/></beans>

在上面的配置文件中,除了配置数据源外,我们还配置了事务,然后整合了jpa,需要详细说明的我已经加了注释,这里就不多做解释了(需要额外注意的是cn.shinelon.springdata这个包下我放置着持久类以及Respository这个接口,这是什么接口,请看下面的讲解)。

接下来,我们来创建一个持久化类。

Person.java

package cn.shinelon.springdata;import java.util.Date;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;@Table(name="jpa_person")@Entitypublic class Person {    private Integer id;    private String lastName;    private Date birth;    private String email;    //主键    @GeneratedValue    @Id    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getLastName() {        return lastName;    }    public void setLastName(String lastName) {        this.lastName = lastName;    }    public Date getBirth() {        return birth;    }    public void setBirth(Date birth) {        this.birth = birth;    }    public String getEmail() {        return email;    }    public void setEmail(String email) {        this.email = email;    }    @Override    public String toString() {        return "Person [id=" + id + ", lastName=" + lastName + ", birth=" + birth + ", email=" + email + "]";    }}

然后创建Repository接口
PersonRepsotory.java

import org.springframework.data.repository.Repository;import org.springframework.data.repository.RepositoryDefinition;//这个两个泛型类型一个是实体类,一个是主键的类型public interface PersonRepsotory extends Repository<Person, Integer>{    //根据name查找数据    Person getByLastName(String lastName);}

在经过上面的一番操作后,我们可以对我们的代码进行一下测试(一般大型项目都需要进行单元测试,不然当你全部完成后再去启动的话,很可能会出现大量的错误,不便于我们调试),并且在数据库中生成相应的数据表。

package cn.shinelon.springdata.test;import java.sql.SQLException;import javax.sql.DataSource;import org.junit.jupiter.api.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.shinelon.springdata.Person;import cn.shinelon.springdata.PersonRepsotory;class SpringDataTest {    private ApplicationContext applicationContext=null;    {        applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");    }    @Test    void testDataSource() throws SQLException {        DataSource dataSource=applicationContext.getBean(DataSource.class);        System.out.println(dataSource.getConnection());    }    //因为在静态加载快中会自动加载spring容器,所以这里测试不需要任何的代码就能生成相应的数据表。    @Test    public void testJpa() {    }}

好了,经过我们上面的测试,已经验证了代码没有bug,并且也生成了相应的数据表。
在这里我们手动在数据表中插入一条数据。数据库中的数据如下图。
这里写图片描述
下面我们通过last_name这个字段来查询用户信息。
看代码如下:

@Test    public void TestPerson() {        PersonRepsotory personRepsotory=applicationContext.getBean(PersonRepsotory.class);        Person person=new Person();        person=personRepsotory.getByLastName("shinelon");        System.out.println(person.toString());    }

运行上面的代码,我们就可以轻松查到数据库中相应的信息,哈哈,是不是特别简单,现在,我们来对上面提到的Repository接口来解释一下。首先,这个接口是干嘛的呢?简单的说,只有当你继承这个接口后,Spring IOC容器扫描到包下的这个接口后会自动被识别为一个Repository bean,纳入到IOC容器中,进而可以在该接口中定义满足一定规范的方法,值得说的是,Repository是一个空接口,即一个标记接口,实际上,也可以通过注解@RepositoryDefinition来替代继承Repository接口将一个接口识别为一个Repository bean,只需要加上下面的这段代码即可:

@RepositoryDefinition(domainClass=Person.class,idClass=Integer.class)

接下来,我们再来说一个重要的问题,在Repository这个接口中,声明的方法是不是随意写的,它遵守一定的规范:

1.不是随便声明的,而需要符合一定的规范
2.查询方法以get |find |read开头
3.涉及查询条件的时候,条件属性用条件关键字连接
4.要注意的是,条件属性以大写字母开头

它的一些关键字可以看下面这张图:

这里写图片描述

通过这张图,我们可以清楚的看出来它对数据库的增删改查都有一定的规范,只要我们遵守它的规范来声明一个方法就绝对不会出错的。

最后,这是项目的完整目录图。
这里写图片描述