一、前言
PostgreSQL是一种广泛使用的开源关系型数据库,具有可靠性高、高性能、丰富的数据类型和易于扩展等特点,越来越多的企业和开发者开始使用它来存储和管理数据。SpringBoot可以很方便的集成PostgreSQL实现数据库的操作。
二、优势
PostgreSQL和MySQL都是免费、开源的关系型数据库,但它们肯定有区别,我们总结下PostgreSQL都有哪些优势。
1.支持存储一些特殊的数据类型,比如array,json、jsonb等。
2.对地理信息的存储与处理有更好的支持,所以它可以成为一个空间数据库。
3.支持树状结构,可以更方便的处理具备此类特性的数据存储。
4.外部数据源的支持,可以把MySQL、Oracle等当成自己数据库中的表来进行查询。
5.对索引的支持更强。
6.事务的隔离性更好。
7.时间精度更高,可以精确到秒以下。
8.字符支持更好,可以存储更大的数据量。
三、PostgreSQL工具操作
我们可以使用安装PostgreSQL后的工具pgAdmin连接PostgreSQL。
我们选择Databases,右键创建一个名为pg_test的数据库。
创建数据库后,我们打开pg_test->Schemas->public->Tables 然后右键创建数据表。
最后我们可以在Columns下面添加相关字段。
增加数据:右键表选择Scripts->INSERT Script
最后我们查询数据。
四、SpringBoot集成PostgreSQL
1.添加依赖
我们添加PostgreSQL和jpa的依赖。
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2.postgreSQL配置
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/pg_test
spring.datasource.username=postgres
spring.datasource.password=123456
3.创建实体类
由于我们使用了JPA的依赖,创建实体会自动在数据库中创建数据表。
package com.example.nettydemo.entity;
import lombok.Data;
import javax.persistence.*;
/**
* @author qx
* @date 2023/12/25
* @des
*/
@Entity
// 指定public下的pg_student表
@Table(name = "public.pg_student")
@Data
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
}
4.创建数据持久层
package com.example.nettydemo.repository;
import com.example.nettydemo.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author qx
* @date 2023/12/25
* @des
*/
public interface StudentRepository extends JpaRepository<Student, Long> {
}
5.测试
我们启动项目,刷新数据库表,会出现刚才我们自动创建的数据表。
数据新增:
@SpringBootTest
class NettyDemoApplicationTests {
@Autowired
private StudentRepository studentRepository;
@Test
void testAdd() {
Student student = new Student();
student.setName("张三");
student.setAge(20);
studentRepository.save(student);
}
}
执行成功后我们刷新数据表,发现成功新增了数据。
数据查询:
@SpringBootTest
class NettyDemoApplicationTests {
@Autowired
private StudentRepository studentRepository;
@Test
void testSelect() {
Student student = studentRepository.findById(1L).orElse(null);
System.out.println(student);
}
}
Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from public_t_student student0_ where student0_.id=?
Student(id=1, name=张三, age=20)
数据删除:
@SpringBootTest
class NettyDemoApplicationTests {
@Autowired
private StudentRepository studentRepository;
@Test
void testDelete() {
studentRepository.deleteById(1L);
}
}
执行成功之后我们刷新数据表,发现数据被成功删除了。