SpringDataJPA的CrudRepository接口详解

在用SpringData(JPA是操作关系型的数据库)是个非常不错的框架,开发人员省去了创建数据库表格的时间,与此同时还简化了持久层的代码量.在SpringData中目前为止最核心的是Repository接口,但是里面没有任何的方法:

public interface Repository<T, ID extends Serializable>

Repository还有许多的额子接口,在项目开发中最常用的是三种(自己认为)
CrudRepository:继承Repoitory接口 ,实现了CRUD的相关方法
PagingAndSortingRepository:继承CrudRepository接口,实现了分页排序的相关方法
JpaRepository:继承PagingAndSortingRepository,实现Jpa规范的相关方法

第一个参数是操作时对应的实体类的类名,第二个参数是主键的类型:
当然除了继承外,还有一个方法是和继承Repository接口是一样的,那就是用@RepositoryDefinition注解效果都是一样的,
在这里插入图片描述
就可以在此接口编写对数据库操作的方法(在接口中是静态方法,没有方法体的,但是SpringData有个方法的命名规则,可以直接采用命名规则的方式来实现操作,因为SpringData的底层已经帮你写好sql语句,不需要再次写sql语句)
在这里插入图片描述
详细规则请参考官方文档:命名规则

第一步(引入依赖):

 <dependencies>
    <!--MySQL Driver-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>

    <!--junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
    </dependency>

    <!--spring-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.3.5.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.5.RELEASE</version>
    </dependency>

    <!--spring data jpa-->
    <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.6.Final</version>
    </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-to-slf4j</artifactId>
            <version>2.11.2</version>
        </dependency>

第二步(创建资源文件-db.properites):

jdbc.url = jdbc:mysql://localhost:3306/gz?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
jdbc.user = root
jdbc.password = 1234
jdbc.driverClass = com.mysql.jdbc.Driver

第三步(配置相关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">
    <!-- 加载properties文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!--1 配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.driverClass}"/>
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>

    </bean>

    <!--2 配置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.gaozhi"/>

        <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.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"/>
    </bean>

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

    <!--5 配置spring data-->
    <jpa:repositories base-package="com.gaozhi" entity-manager-factory-ref="entityManagerFactory"/>

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

</beans>

第四步(实现接口)

public interface EmployeeCrudRepository extends CrudRepository<Employee, Integer> {
}

第五步(服务层)

@Service
public class EmployeeService {
    @Autowired
    EmployeeCrudRepository employeeCrudRepository;
    public void save(Employee employee){
        employeeCrudRepository.save(employee);
    }
}

第六步(测试)

public class TestEmployeeCrud {
    private ApplicationContext applicationContext=null;
    private EmployeeCrudRepository employeeCrudRepository=null;
    @Before
    public void SetUp(){
        applicationContext=new ClassPathXmlApplicationContext("beans.xml");
        employeeCrudRepository=applicationContext.getBean(EmployeeCrudRepository.class);
    }
    @After
    public void After(){
        applicationContext=null;
    }
    @Test
    public void TestEmployeeSave(){
        Employee employee=new Employee();
        employee.setName("李四");
        employee.setAge(25);
        employeeCrudRepository.save(employee);
    }

结果:

D:\Develop\Java\jdk1.8.0_131\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:\SoftWare\IntelliJ IDEA 2018.1.8\lib\idea_rt.jar=60971:D:\SoftWare\IntelliJ IDEA 2018.1.8\bin" -Dfile.encoding=UTF-8 -classpath "D:\SoftWare\IntelliJ IDEA 2018.1.8\lib\idea_rt.jar;D:\SoftWare\IntelliJ IDEA 2018.1.8\plugins\junit\lib\junit-rt.jar;D:\SoftWare\IntelliJ IDEA 2018.1.8\plugins\junit\lib\junit5-rt.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\charsets.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\deploy.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\ext\access-bridge-64.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\ext\cldrdata.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\ext\dnsns.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\ext\jaccess.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\ext\jfxrt.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\ext\localedata.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\ext\nashorn.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\ext\sunec.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\ext\sunjce_provider.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\ext\sunmscapi.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\ext\sunpkcs11.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\ext\zipfs.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\javaws.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\jce.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\jfr.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\jfxswt.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\jsse.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\management-agent.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\plugin.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\resources.jar;D:\Develop\Java\jdk1.8.0_131\jre\lib\rt.jar;E:\IdeaProjects\SpringDataJPA\target\test-classes;E:\IdeaProjects\SpringDataJPA\target\classes;E:\MavenLib\mysql\mysql-connector-java\6.0.6\mysql-connector-java-6.0.6.jar;E:\MavenLib\junit\junit\4.10\junit-4.10.jar;E:\MavenLib\org\hamcrest\hamcrest-core\1.1\hamcrest-core-1.1.jar;E:\MavenLib\org\springframework\spring-jdbc\4.3.5.RELEASE\spring-jdbc-4.3.5.RELEASE.jar;E:\MavenLib\org\springframework\spring-beans\4.3.5.RELEASE\spring-beans-4.3.5.RELEASE.jar;E:\MavenLib\org\springframework\spring-core\4.3.5.RELEASE\spring-core-4.3.5.RELEASE.jar;E:\MavenLib\commons-logging\commons-logging\1.2\commons-logging-1.2.jar;E:\MavenLib\org\springframework\spring-tx\4.3.5.RELEASE\spring-tx-4.3.5.RELEASE.jar;E:\MavenLib\org\springframework\spring-context\4.3.5.RELEASE\spring-context-4.3.5.RELEASE.jar;E:\MavenLib\org\springframework\spring-aop\4.3.5.RELEASE\spring-aop-4.3.5.RELEASE.jar;E:\MavenLib\org\springframework\spring-expression\4.3.5.RELEASE\spring-expression-4.3.5.RELEASE.jar;E:\MavenLib\org\springframework\data\spring-data-jpa\1.8.0.RELEASE\spring-data-jpa-1.8.0.RELEASE.jar;E:\MavenLib\org\springframework\data\spring-data-commons\1.10.0.RELEASE\spring-data-commons-1.10.0.RELEASE.jar;E:\MavenLib\org\slf4j\slf4j-api\1.7.10\slf4j-api-1.7.10.jar;E:\MavenLib\org\slf4j\jcl-over-slf4j\1.7.10\jcl-over-slf4j-1.7.10.jar;E:\MavenLib\org\springframework\spring-orm\4.0.9.RELEASE\spring-orm-4.0.9.RELEASE.jar;E:\MavenLib\org\aspectj\aspectjrt\1.8.5\aspectjrt-1.8.5.jar;E:\MavenLib\org\hibernate\hibernate-entitymanager\4.3.6.Final\hibernate-entitymanager-4.3.6.Final.jar;E:\MavenLib\org\jboss\logging\jboss-logging\3.1.3.GA\jboss-logging-3.1.3.GA.jar;E:\MavenLib\org\jboss\logging\jboss-logging-annotations\1.2.0.Beta1\jboss-logging-annotations-1.2.0.Beta1.jar;E:\MavenLib\org\hibernate\hibernate-core\4.3.6.Final\hibernate-core-4.3.6.Final.jar;E:\MavenLib\org\jboss\spec\javax\transaction\jboss-transaction-api_1.2_spec\1.0.0.Final\jboss-transaction-api_1.2_spec-1.0.0.Final.jar;E:\MavenLib\dom4j\dom4j\1.6.1\dom4j-1.6.1.jar;E:\MavenLib\xml-apis\xml-apis\1.0.b2\xml-apis-1.0.b2.jar;E:\MavenLib\org\hibernate\common\hibernate-commons-annotations\4.0.5.Final\hibernate-commons-annotations-4.0.5.Final.jar;E:\MavenLib\org\hibernate\javax\persistence\hibernate-jpa-2.1-api\1.0.0.Final\hibernate-jpa-2.1-api-1.0.0.Final.jar;E:\MavenLib\org\javassist\javassist\3.18.1-GA\javassist-3.18.1-GA.jar;E:\MavenLib\antlr\antlr\2.7.7\antlr-2.7.7.jar;E:\MavenLib\org\jboss\jandex\1.1.0.Final\jandex-1.1.0.Final.jar;E:\MavenLib\org\apache\logging\log4j\log4j-to-slf4j\2.11.2\log4j-to-slf4j-2.11.2.jar;E:\MavenLib\org\apache\logging\log4j\log4j-api\2.11.2\log4j-api-2.11.2.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 TestEmployeeCrud,test
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
一月 11, 2020 8:47:21 下午 org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
	name: default
	...]
一月 11, 2020 8:47:21 下午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.6.Final}
一月 11, 2020 8:47:21 下午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
一月 11, 2020 8:47:21 下午 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
一月 11, 2020 8:47:21 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Sat Jan 11 20:47:21 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
一月 11, 2020 8:47:23 下午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
一月 11, 2020 8:47:23 下午 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
一月 11, 2020 8:47:23 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
一月 11, 2020 8:47:23 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Sat Jan 11 20:47:23 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
一月 11, 2020 8:47:23 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
一月 11, 2020 8:47:23 下午 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: gz.employee
一月 11, 2020 8:47:23 下午 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [name, id, age]
一月 11, 2020 8:47:23 下午 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
一月 11, 2020 8:47:23 下午 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
一月 11, 2020 8:47:23 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Sat Jan 11 20:47:23 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Hibernate: 
    insert 
    into
        employee
        (age, name) 
    values
        (?, ?)

SpringData-JPA:如果你的数据没有表格那就会自动帮你创建一个表格,这就是SpirngData-JPA的特性,当然也可以当实体类用注解来配置数据库表格中的一些参数,比如自增,列名,表名等.

实体类:


@Entity
public class Employee {

    private Integer id;

    private String name;

    private Integer age;

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(length = 20)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

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

格言:不驰于空想,不骛于虚声

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值