先上代碼,後面再仔細分析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層開啓事務,纔可以修改成功。