返回目录
1 JPA Hibernate
Hibernate是一个全自动的ORM框架(Object Relational Mapping ,对象关系映射)。
Spring Data JPA:
是Spring Data的子模块,JPA默认使用hibernate作为ORM实现。
2 springboot继承Hibernate
第1步:引入pom文件:
<!-- MySQL 连接驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector}</version>
</dependency>
<!--jpa相关依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</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 的接口了。
3 测试验证
3.1 新增英雄(heroic)验证
可以数据库中多了一条记录:
3.2 查询英雄(heroic)验证
3.3 修改英雄(heroic)验证
可以数据库记录已经修改
3.4 删除英雄(heroic)验证
可见数据库中的记录已经清空了。
4 问题汇总
报错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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
修改为:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</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