spring-data-jpa初步开始的helloworld

1.在Spring Data的核心接口里面Repository是最基本的接口了, spring提供了很多实现了该接口的基本接口,如: CrudRepository, PagingAndSortingRepository,SimpleJpaRepository,QueryDslJpaRepository等大量查询接口

2.其中CrudRepository实现基本的增删查改

public interface CrudRepository<T, ID extends Serializable>
    extends Repository<T, ID> {
                                                                                                                       
    <S extends T> S save(S entity);
                                                                                                                       
    T findOne(ID primaryKey);
                                                                                                                       
    Iterable<T> findAll();

    Long count();
                                                                                                                       
    void delete(T entity);
                                                                                                                       
    boolean exists(ID primaryKey);
    .....                                                                                                                 
}

1.保存该对象
2.根据该对象的id查询该对象
3.返回该对象的一个集合
4.返回该对象的数量
5.删除该对象
6.根据id验证该对象是否存在

详见该接口CrudRepository方法


3.PagingAndSortingRepository该接口主要用来提供分页和排序查询

public interface PagingAndSortingRepository<T, ID extends Serializable> 
  extends CrudRepository<T, ID> {

  Iterable<T> findAll(Sort sort);

  Page<T> findAll(Pageable pageable);
}

如:
Page<StudentEntity> users = repository.findAll(new PageRequest(1, 20));


4.配置spring-boot启动项目
@EnableAutoConfiguration
@ComponentScan("com.lance")
@EntityScan("com.lance.entity")
@EnableJpaRepositories("com.lance.repository")
public class WebAppConfig {
    
    public static void main(String[] args) {
		SpringApplication.run(WebAppConfig.class, args);
	}
}


5.配置数据库连接以及其他配置项application.properties
#DB properties:
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driverClassName=com.mysql.jdbc.Driver

#JPA Configuration:
spring.jpa.show-sql=true
#spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
#spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
#spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
#spring.jpa.database=org.hibernate.dialect.MySQL5InnoDBDialect

#view Configuration:
spring.view.prefix=/WEB-INF/views/

#Server Configuration:
server.port=8080


6.demo详见附件

猜你喜欢

转载自lihao312.iteye.com/blog/2075659