Hibernate是一个全自动的ORM框架(Object Relational Mapping ,对象关系映射)。
Spring Data JPA:
是Spring Data的子模块,JPA默认使用hibernate作为ORM实现。
第1步:引入pom文件:
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql-connector}version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
第2步:定义配置文件:
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories(basePackages = "org.feidao.chapter42.repository")
@EntityScan(basePackages = "org.feidao.chapter42.entity")
public class JpaConfiguration {
@Bean
PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
第3步:定义entity实体bean;
@Getter@Setter
@Entity
@Table(name="tb_heroic")
public class Heroic{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
@Column(name="name")
public String name = "";
@Column(name="remarks")
public String remarks = "";
}
第4步:定义dao的interface;
@Repository
public interface HeroicRepository extends JpaRepository <Heroic, Long>{
}
然后就可以直接调用HeroicRepository 的接口了。
可以数据库中多了一条记录:
可以数据库记录已经修改
可见数据库中的记录已经清空了。
报错1:org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’
解决: import org.springframework.data.annotation.Id; 改为improt javax.persistence.Id;
报错2::Caused by: java.lang.NullPointerException
at com.mysql.jdbc.ConnectionImpl.getServerCharset(ConnectionImpl.java:2997)
解决:
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.39version>
dependency>
修改为:
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.30version>
dependency>
报错3:
com.mysql.cj.exceptions.ConnectionIsClosedException: No operations allowed after connection closed.
at sun.reflect.GeneratedConstructorAccessor50.newInstance(Unknown Source) ~[na:na]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_25]
at java.lang.reflect.Constructor.newInstance(Constructor.java:408) ~[na:1.8.0_25]
解决:
配置文件增加:
spring.datasource.hikari.max-lifetime=30000
代码详见:
https://gitee.com/linghufeixia/springboot-simple
chapter4-2
教程列表:
springboot simple(0) springboot简介
springboot simple(1) springboot Helloworld
springboot simple(2) springboot Starter
springboot simple(3 )springboot Web开发
springboot simple(4)springboot 数据持久化
springboot simple (5) springboot Nosql
springboot simple (6) springboot mqtt
springboot simple (7) springboot thrift
springboot simple (8) springboot kafka
springboot simple (9) springboot jpa(Hibernate)