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等接口,就可以实现对数据的增删改查等处理,并且支持相关分页、排序等处理。

搭建

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

org.springframework.data

spring-data-jpa

junit

junit

4.12

test

org.hibernate

hibernate-entitymanager

5.4.32.Final

mysql

mysql-connector-java

5.1.48

log4j

log4j

1.2.17

com.alibaba

druid

1.2.3

org.springframework

spring-test

5.1.12.RELEASE

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 {

}

测试代码

@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,使得程序员对DAO层的处理非常简单,只要简单声明一个接口,并继承CrudRepository,就可以完全获得对数据库表的增删改查的处理,CrudRepository的源码如下:

@NoRepositoryBean

public interface CrudRepository extends Repository {

/**

* 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 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.

*/

Iterable saveAll(Iterable 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 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 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 findAllById(Iterable 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 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 entities);

/**

* Deletes all entities managed by the repository.

*/

void deleteAll();

}

继承了Repostory接口的子接口如下: 其中PagingAndSortingRepository,继承这个接口,可以方便实现查询分页和排序。也可以通过自定义的hql来实现查询等操作

public interface CustomerDao extends CrudRepository {

@Query(" from Customer where name = :name and address = :address")

public List getByNameAndAddress(@Param("name") String name, @Param("address") String address);

}

测试代码:

@Test

public void test_Hql(){

List customers = customerDao.getByNameAndAddress("huwenchao", "wuhu");

for (Customer customer : customers) {

System.out.println("customer = " + customer);

}

}

结果:

精彩链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: