版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24894159/article/details/79946113
主要内容
- 概念简介
- 配置
- 代码实现
- 常见问题
-
概念简介
JPA
Java Persistence API,Java持久层API,所谓持久层,个人浅显的理解就是和数据持久化存储相关的一层。
Hibernate
详细的解释可以看下百度百科,个人理解就是在JDBC上封装的一层,能够便利的进行数据库的操作,提供了很多的接口。参照这个博主文章。https://blog.csdn.net/xiao_xuwen/article/details/53420824
配置
application.properties配置
spring.datasource.url=jdbc:mysql://localhost:3306/databasename
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update #该属性有不同选项
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true
create: 每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
create-drop :每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等 应用第一次运行起来后才会。
validate :每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。
(ps:上面四个属性摘自https://zhuanlan.zhihu.com/p/24965387?refer=dreawer)
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
代码
1、实体
@Entity
@Table(name = "user")
public class User implements Serializable {//序列化在Jpa需要
private static final long serialVersionUID = 1L;
@Id //主键
@GeneratedValue(strategy = GenerationType.IDENTITY) //自增长
private Long id;
@Column(name = "uid",nullable = false,unique = true)
private String uid;
@Column(name = "nickname",nullable = false)
private String nickname;
@Column(name = "avatar",nullable = true)
private String avatar;
...
}
2、Jpa数据操作
//JpaRepository<Entity,Primary Key Type>
public interface UserRepository extends JpaRepository<User,Long> {
public User findByNickname(String nickname);
}
3、单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class ThereApplicationTests {
@Autowired
private UserRepository userRepository;
@Test
public void test() throws Exception {
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
String formattedDate = dateFormat.format(date);
userRepository.save(new User("abc11","scrovor1","https://sdfdsfsd1",UserType.DEFAULT,formattedDate));
userRepository.save(new User("abc12","scrovor2","https://sdfdsfsd2",UserType.DEFAULT,formattedDate));
userRepository.save(new User("abc13","scrovor3","https://sdfdsfsd3",UserType.DEFAULT,formattedDate));
}
}
直接Run As、Junit Test就OK,关于单元测试可以学习下这篇博文。
可能出现的问题
- 确保mysql-connector驱动下载下来了。
- 实体类Id类型与JpaRepository第二个泛型一定要对应。
- application.properties配置参数名称不要写错。