PostgreSQL
Last updated
Last updated
다운로드 https://www.enterprisedb.com/downloads/postgres-postgresql-downloads
pom.xml 작성
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
application.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/test
spring.datasource.username=postgres
spring.datasource.password=123456
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.hbm2ddl.auto=create
application.yml
spring:
datasource:
driver-class-name: org.postgresql.Driver
password: 123456
url: jdbc:postgresql://localhost:5432/test
username: postgres
jpa:
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
hbm2ddl:
auto: create
UserInfo 객체 생성 (user_info 테이블과 매핑)
@Entity
@Data
@NoArgsConstructor
public class UserInfo {
@Id
@GeneratedValue
private Long id;
private String name;
private Integer age;
public UserInfo(String name, Integer age) {
this.name = name;
this.age = age;
}
}
interface 작성
public interface UserInfoRepository extends JpaRepository<UserInfo, Long> {
UserInfo findByName(String name);
UserInfo findByNameAndAge(String name, Integer age);
@Query("from UserInfo u where u.name=:name")
UserInfo findUser(@Param("name") String name);
}
@Slf4j
@SpringBootTest
public class ApplicationTests {
@Autowired
private UserInfoRepository userRepository;
@Test
public void test() throws Exception {
userRepository.save(new UserInfo("AAA", 10));
userRepository.save(new UserInfo("BBB", 20));
userRepository.save(new UserInfo("CCC", 30));
userRepository.save(new UserInfo("DDD", 40));
userRepository.save(new UserInfo("EEE", 50));
userRepository.save(new UserInfo("FFF", 60));
userRepository.save(new UserInfo("GGG", 70));
userRepository.save(new UserInfo("HHH", 80));
userRepository.save(new UserInfo("III", 90));
userRepository.save(new UserInfo("JJJ", 100));
Assertions.assertEquals(10, userRepository.findAll().size());
Assertions.assertEquals(60, userRepository.findByName("FFF").getAge().longValue());
Assertions.assertEquals(60, userRepository.findUser("FFF").getAge().longValue());
Assertions.assertEquals("FFF", userRepository.findByNameAndAge("FFF", 60).getName());
userRepository.delete(userRepository.findByName("AAA"));
Assertions.assertEquals(9, userRepository.findAll().size());
}
}
결과
pgadmin
다 만들고 생각해보니 mysql 설정할때랑 별로 다른게 없어보인다. pom 수정 , application.yml 파일 수정 하는 부분만 다를뿐. 이것이 바로 JPA 매력이다. 추상화로 되어 있어 db를 어떤 제품으로 변경하든지 java code 는 변경되는 부분으 매우 적거나 없다.
끝!