先上代码,后面再仔细分析spring-data

pom.xml

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>4.3.0.Release</version>
</dependency>

<!-- spring data -->
  <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>1.8.0.RELEASE</version>
  </dependency>

  <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>4.3.1.Final</version>
  </dependency>

  <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.36</version>
  </dependency>

spring.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">

    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <property name="url" value="jdbc:mysql:///spring_data"/>

    </bean>
    <bean id="entityManager" 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.demo"/>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.show_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="entityManager"/>
    </bean>

    <!-- 事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!-- jpa -->
    <jpa:repositories base-package="com.demo" entity-manager-factory-ref="entityManager"/>

    <context:component-scan base-package="com.demo"/>

</beans>

编写完配置文件后就可以开发spring-data程序了。

首先需要创建一个实体,根据业务来定义。

实体创建完不需要创建数据库表,spring-data会自动创建表的。

这儿以学生类Student为例。

@Entity
public class Student{
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    private Integer age;
    
    //get set 这儿省略...
}

创建好实体后就可以编写spring-data程序了。

包名类名根据自己需求创建。

这儿建一个com.demo.dao和StudentDao接口,需要继承SpringData的Repository接口

package com.demo.dao;


import com.demo.entity.Student;
import org.springframework.data.repository.Repository;

import java.util.List;

public interface StudentDao extends Repository<Student,Integer> {

    public Student findByName(String name);

    public List<Student> findByAge(Integer age);

}

这儿的命名是有一定的规范的,如果查询某一个字段,需要前面加findBy+字段名,如果些错是查不到数据的。

如果不想继承Repository接口还可以用注解RepositoryDefinition也可以达到同样的效果。

package com.demo.dao;

import com.demo.Student;
import org.springframework.data.repository.RepositoryDefinition;

@RepositoryDefinition(domainClass = Student.class,idClass = Integer.class)
public interface StudentDao {

    public Student findByName(String name);

}

前面两种都是可以直接查询到数据的,但是前面两种方式的函数名必须要规范写入,要不然是查找不到数据的,这个一定要注意。

SpringData还有个子接口CrudRepository,里面包含了增删改查的函数,大家可以去看下源码。

直接在接口集成CrudRepository就可以了。例如

package com.demo.dao;

import com.demo.entity.Student;
import org.springframework.data.repository.CrudRepository;

public interface StudentDao extends CrudRepository<Student,Integer> {
}

继承这个接口后就可以直接调用该函数的增删改查。

以上几种方式的函数名是有一定的规范的,这样导致的可能性是函数名有肯能过长、复杂业务逻辑实现比较麻烦等等。以下有一种更灵活的方式,需要继承JpaRepository接口

直接使用注解@Query

package com.demo.dao;

import com.demo.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface StudentDao extends JpaRepository<Student,Integer> {

    @Query("select o from Student o where o.name=?1")
    public Employee getStudent(String name);

    @Query("select o from Student o where o.name=:name")
    public Employee getStudent1(@Param("name")String name);
}

上面的函数名是可以随便写的,@query里面直接写入对应的sql语句,注意:@Query里面的表名其实是类名,并不是数据库表名,如果想用本地话查询,需要在@Query修改里面的nativeQuery为true,默认为false。

例如

package com.demo.dao;

import com.demo.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface StudentDao extends JpaRepository<Student,Integer> {

    @Query(value="select o from student o where o.name=?1",nativeQuery=true)
    public Employee getStudent(String name);

}

这样就可以本地化查询了。

@Query做的不仅仅只有查询,增删改查都可以

只要在@Query里面写入对应的sql语句就可以了。

但是增删改的时候需要配合另一个注解@Modifying来使用,service层开启事务,才可以修改成功。