您的位置:首页 > 编程语言 > Java开发

spring-data-jpa初步开始的helloworld

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

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

Java代码


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该接口主要用来提供分页和排序查询

Java代码


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启动项目

Java代码


@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

Java代码


#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: