Spring Data JPA搭建及测试

Spring Data JPA学习记录

概览

  • Spring Data 是spring全家桶中的一个项目,为了统一对数据的访问,并且支持对很多种关系型与非关系性的数据库进行处理,包括JDBC、JPA、MongoDB、Redis、REST等等,其中JDBC、MongoDB等数据库的访问,提供了统一的访问模版,如JdbcTemplate、RedisTemplate等。
  • Spring Data JPA,是基于JPA的规范,目前实现了JPA规范的ORM框架有Hibernate、easyJPA等,其中最著名的当然是Hibernate。
  • Spring Data JPA,最方便的地方,还是通过整合ORM框架,并且通过动态代理的方式将数据访问层的接口中的方法动态生成了数据库访问实现,使程序员在进行DAO数据访问层开发的时候,非常方便,只需要进行接口定义,并继承了相关的CRUDRepository等接口,就可以实现对数据的增删改查等处理,并且支持相关分页、排序等处理。

搭建

  • 引入依赖,按照官网的说明

    Spring Data JPA搭建及测试_第1张图片
<dependency>
    <groupId>org.springframework.datagroupId>
    <artifactId>spring-data-jpaartifactId>
dependency>
<dependency>
    <groupId>junitgroupId>
    <artifactId>junitartifactId>
    <version>4.12version>
    <scope>testscope>
dependency>
<dependency>
    <groupId>org.hibernategroupId>
    <artifactId>hibernate-entitymanagerartifactId>
    <version>5.4.32.Finalversion>
dependency>
<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>5.1.48version>
dependency>
<dependency>
    <groupId>log4jgroupId>
    <artifactId>log4jartifactId>
    <version>1.2.17version>
dependency>
<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.2.3version>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-testartifactId>
    <version>5.1.12.RELEASEversion>
dependency>
  • Spring配置类
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.huwc.dao")
public class AppConfig {
    //数据源
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///test?useSSL=false&allowPublicKeyRetrieval=true");
        dataSource.setUsername("root");
        dataSource.setPassword("password");
        return dataSource;
    }
    //entityManager管理器
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);//ddl处理规则,没有表的话,则进行自动创建
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("com.huwc.pojo");//扫描的pojo的包
        factory.setDataSource(dataSource());
        return factory;
    }
    //事务管理器,使用JpaTransactionManager
    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory);
        return txManager;
    }
}
  • POJO类定义
@Entity//表明是一个实体类
@Table(name = "t_customer")//表明
public class Customer {

    @Id//主键
    @Column(name = "id")//列名
    @GeneratedValue(strategy = GenerationType.IDENTITY)//主键生成策略
    private Integer id ;

    @Column(name = "name")
    private String name ;

    @Column(name = "address")
    private String address ;

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

    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;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
  • Dao层声名
public interface CustomerDao extends CrudRepository<Customer, Integer> {
}
  • 测试代码
@ContextConfiguration(classes = AppConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringDataTest {
    @Autowired
    private CustomerDao customerDao ;

    @Test
    public void test_Save(){
        Customer customer = new Customer();
        customer.setName("huwenchao");
        customer.setAddress("wuhu");
        System.out.println(customerDao.save(customer));
    }
}
  • 测试结果
    Spring Data JPA搭建及测试_第2张图片

以上可以看出,Spring Data JPA,使得程序员对DAO层的处理非常简单,只要简单声明一个接口,并继承CrudRepository,就可以完全获得对数据库表的增删改查的处理,CrudRepository的源码如下:

@NoRepositoryBean
public interface CrudRepository<T, ID> extends Repository<T, ID> {

	/**
	 * Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
	 * entity instance completely.
	 *
	 * @param entity must not be {@literal null}.
	 * @return the saved entity; will never be {@literal null}.
	 * @throws IllegalArgumentException in case the given {@literal entity} is {@literal null}.
	 * @throws OptimisticLockingFailureException when the entity uses optimistic locking and has a version attribute with
	 *           a different value from that found in the persistence store. Also thrown if the entity is assumed to be
	 *           present but does not exist in the database.
	 */
	<S extends T> S save(S entity);

	/**
	 * Saves all given entities.
	 *
	 * @param entities must not be {@literal null} nor must it contain {@literal null}.
	 * @return the saved entities; will never be {@literal null}. The returned {@literal Iterable} will have the same size
	 *         as the {@literal Iterable} passed as an argument.
	 * @throws IllegalArgumentException in case the given {@link Iterable entities} or one of its entities is
	 *           {@literal null}.
	 * @throws OptimisticLockingFailureException when at least one entity uses optimistic locking and has a version
	 *           attribute with a different value from that found in the persistence store. Also thrown if at least one
	 *           entity is assumed to be present but does not exist in the database.
	 */
	<S extends T> Iterable<S> saveAll(Iterable<S> entities);

	/**
	 * Retrieves an entity by its id.
	 *
	 * @param id must not be {@literal null}.
	 * @return the entity with the given id or {@literal Optional#empty()} if none found.
	 * @throws IllegalArgumentException if {@literal id} is {@literal null}.
	 */
	Optional<T> findById(ID id);

	/**
	 * Returns whether an entity with the given id exists.
	 *
	 * @param id must not be {@literal null}.
	 * @return {@literal true} if an entity with the given id exists, {@literal false} otherwise.
	 * @throws IllegalArgumentException if {@literal id} is {@literal null}.
	 */
	boolean existsById(ID id);

	/**
	 * Returns all instances of the type.
	 *
	 * @return all entities
	 */
	Iterable<T> findAll();

	/**
	 * Returns all instances of the type {@code T} with the given IDs.
	 * 

* If some or all ids are not found, no entities are returned for these IDs. *

* Note that the order of elements in the result is not guaranteed. * * @param ids must not be {@literal null} nor contain any {@literal null} values. * @return guaranteed to be not {@literal null}. The size can be equal or less than the number of given * {@literal ids}. * @throws IllegalArgumentException in case the given {@link Iterable ids} or one of its items is {@literal null}. */ Iterable<T> findAllById(Iterable<ID> ids); /** * Returns the number of entities available. * * @return the number of entities. */ long count(); /** * Deletes the entity with the given id. *

* If the entity is not found in the persistence store it is silently ignored. * * @param id must not be {@literal null}. * @throws IllegalArgumentException in case the given {@literal id} is {@literal null} */ void deleteById(ID id); /** * Deletes a given entity. * * @param entity must not be {@literal null}. * @throws IllegalArgumentException in case the given entity is {@literal null}. * @throws OptimisticLockingFailureException when the entity uses optimistic locking and has a version attribute with * a different value from that found in the persistence store. Also thrown if the entity is assumed to be * present but does not exist in the database. */ void delete(T entity); /** * Deletes all instances of the type {@code T} with the given IDs. *

* Entities that aren't found in the persistence store are silently ignored. * * @param ids must not be {@literal null}. Must not contain {@literal null} elements. * @throws IllegalArgumentException in case the given {@literal ids} or one of its elements is {@literal null}. * @since 2.5 */ void deleteAllById(Iterable<? extends ID> ids); /** * Deletes the given entities. * * @param entities must not be {@literal null}. Must not contain {@literal null} elements. * @throws IllegalArgumentException in case the given {@literal entities} or one of its entities is {@literal null}. * @throws OptimisticLockingFailureException when at least one entity uses optimistic locking and has a version * attribute with a different value from that found in the persistence store. Also thrown if at least one * entity is assumed to be present but does not exist in the database. */ void deleteAll(Iterable<? extends T> entities); /** * Deletes all entities managed by the repository. */ void deleteAll(); }

  • 继承了Repostory接口的子接口如下:
    Spring Data JPA搭建及测试_第3张图片
    其中PagingAndSortingRepository,继承这个接口,可以方便实现查询分页和排序。
  • 也可以通过自定义的hql来实现查询等操作
public interface CustomerDao extends CrudRepository<Customer, Integer> {

    @Query(" from Customer where name = :name and address = :address")
    public List<Customer> getByNameAndAddress(@Param("name") String name, @Param("address") String address);
}

测试代码:

@Test
public void test_Hql(){
    List<Customer> customers = customerDao.getByNameAndAddress("huwenchao", "wuhu");
    for (Customer customer : customers) {
        System.out.println("customer = " + customer);
    }
}

结果:
Spring Data JPA搭建及测试_第4张图片

你可能感兴趣的:(java学习笔记,spring学习笔记,java,spring,开发语言)