Spring Boot + JPA

Spring Boot + JPA

2021, Aug 30    

Hướng dẫn sử dụng jpa giao tiếp database trong Spring Boot

  • Thư viện sử dụng
  • Định nghĩa dependency trong pom.xml
<dependencies>
    <!--spring mvc, rest-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--spring data jpa-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!--mysql connector java-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>
  • Cấu hình datasource & jpa trong application.yml
spring:
    datasource:
        url: "jdbc:mysql://localhost:3306/spring_boot_jpa_example"
        username: user
        password: password
        driver-class-name: com.mysql.cj.jdbc.Driver
    jpa:
        database-platform: org.hibernate.dialect.MySQL5Dialect
        show-sql: true
        hibernate:
          ddl-auto: none
  • Tạo class entity tương ứng với table trong database
@Entity
@Table(name = "user")
public class UserDto {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "user_id")
  private int userId;

  @Column(name = "user_name")
  private String userName;
}
  • Tạo Repository thao tác với table
public interface UserRepository extends JpaRepository<UserDto, Integer> {

  Optional<UserDto> findUserByUserName(String username);
}
  • Query database thông qua repository
  @Autowired
  private final UserRepository userRepository;
  
  @Override
  public UserDto getUserByName(String username) {
      return userRepository.findUserByUserName(username)
          .orElseThrow(() -> new UserNotFoundException(String.format("Not found user by name %s", username)));
  }

Source code ở đây