spring-data-jpa

其实我一直对spring-data-jpa与hibernate比较迷糊。spring提供的解决方案太多。总感觉自己用的时候思维比较混乱。不知道各种之间的联系与利弊。下面是stackoverflow上的一段解释:


down vote accepte

Hibernate is a JPA implementation, while Spring Data JPA is a JPA Data Access Abstraction. Spring Data offers a solution to GenericDao custom implementations. It can also generate JPA queries on your behalf through method name conventions.

With Spring Data, you may use Hibernate, Eclipse Link or any other JPA provider. A very interesting benefit is that you can control transaction boundaries declaratively using the @Transactional annotation.

Spring JDBC is much more lightweight, and it's intended for native querying, and if you only intend to use JDBC alone, then you are better off using Spring JDBC and overcome JDBC verbosity.

So, Hibernate,and Spring Data are complementary rather than competitors.也只搜到了这一个解释。姑且理解为;jpa是一种规范,hibernate是这种规范的实现之一,spring-data-jpa是对jpa的进一步抽象,要使用它,也必须选用一种实现方案,例如hibernate

今天的文章介绍一下springboot里使用spring-data-jpa

maven依赖:

 <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-data-jpa</artifactId>

        </dependency>

plus:一开始我添加的是spring-data-jpa.然后后面的很多地方,注解之类的就报错。应该是缺少了相关jar包,用这个才可以

官方文档里给出了使用jpa的四个步骤:

1.配置spring以支持repository

@Configuration
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@EnableJpaRepositories(basePackages = "com.example.pg",entityManagerFactoryRef = "pgEntityManagerFactory",
        transactionManagerRef = "pgTransactionManager")
public class jpaConfig {
	
	
	@Bean
    @Primary
    @Qualifier("pgDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.pg")
    public DataSource pgDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Qualifier("pgTransactionManager")
    PlatformTransactionManager pgTransactionManager() {
        return new JpaTransactionManager(pgEntityManagerFactory().getObject());
    }

    @Bean
    @Primary
    LocalContainerEntityManagerFactoryBean pgEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(true);
        jpaVendorAdapter.setDatabase(Database.POSTGRESQL);
        jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.PostgreSQLDialect");

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        factoryBean.setDataSource(pgDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan("com.example.pg");
        factoryBean.setPersistenceUnitName("pgPersistUnit");
        Map<String, Object> props = new HashMap<>();
        props.put("hibernate.physical_naming_strategy",new SpringPhysicalNamingStrategy());
        props.put("hibernate.ejb.entitymanager_factory_name", "pgEntityManagerFactory");
        props.put("hibernate.hbm2ddl.auto","update");
        factoryBean.setJpaPropertyMap(props);
//        factoryBean.afterPropertiesSet();

        return factoryBean;
    }

@EnableMongoRepositories(basePackages='com.exampple.mongo') 如果使用的是mongo
2.定义实体类(如果使用的是postgressql或oracle等,实体类以entity标记。mongo则是document。系统会根据注解识别具体的数据库。还有一种方法是,不同数据库是实体类分不同的package存放,在上面的config那里添加注解

@EntityScan("com.example.pg"))因为例子里只有到了pg。没有添加此项。

@Entity
public class userInfo {
	
	 @javax.persistence.Id
	 @GeneratedValue(strategy = GenerationType.AUTO)
	 private Long id;

	 public String name;
	 public int age;

	 public String getName(){
		 return name;
	 }
	 
	 
	 public int getAge(){
		 return age;
	 }
	 
	 public void setName(String name)
	 {
		 this.name=name;
	 }
	 
	 public void setAge(int age){
		 this.age=age;
	 }

}

一个简单的实体类,注:实体类必须有一个主键。

3.定义接口集成repository 。这里可以是(crudRepository,只提供简单的crud操作。还可以是PagingAndSortingRepository,如果用的是mongo,则可以为:MongoRepository

public interface userInferface extends CrudRepository<UserInfo, Long> {
	
	public UserInfo findByName(String name);

}
因为简单的 CrudRepository<UserInfo, Long>只包含:save findone findAll delete count等几个简单方法。所以在接口里增加自己的方法,并按照约定的格式命名


4.使用

在其他类里可以直接注入userInferface,并实现对数据库的操作

@RequestMapping(value="/user/{name}",method = RequestMethod.GET)

public UserInfo getUser(@PathVariable Stringname){

return u.findByName("xx");

}

@RequestMapping(value="/user",method = RequestMethod.POST)

public UserInfo saveUser(@RequestBody UserInfouser){

return u.save(user);

}



plus:在3处:还可以使用非规范命名的方法,但是增加注解:
@Query ( "select u from UserInfo u where u.name = ?1" )

public UserInfo findUser(String name);


更多具体的用法,可以参考官方文档:

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值