Entity Mapping
package com.example.domain;
import jakarta.persistence.*;
@Entity
@Table(name = "t_account")
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long accountId;
@Column(nullable = false, unique = true)
private String login;
@Column(nullable = false)
private String mail;
protected Account() {}
public Account(String login, String mail) {
this.login = login;
this.mail = mail;
}
public Long getAccountId() { return accountId; }
public String getLogin() { return login; }
public String getMail() { return mail; }
}
Rpeository Delcaration
package com.example.persistence;
import com.example.domain.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface AccountRepository extends JpaRepository<Account, Long> {
Optional<Account> findByLogin(String login);
@Query("select a from Account a where a.mail = :email")
Optional<Account> locateByEmail(@Param("email") String email);
}
Service Layer
package com.example.application;
import com.example.domain.Account;
import com.example.persistence.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class AccountManager {
private final AccountRepository repo;
public AccountManager(AccountRepository repo) {
this.repo = repo;
}
public List<Account> fetchAll() {
return repo.findAll();
}
public Account fetchByLogin(String login) {
return repo.findByLogin(login)
.orElseThrow(() -> new IllegalArgumentException("Account not found"));
}
public Account register(Account account) {
return repo.save(account);
}
public void remove(Long id) {
repo.deleteById(id);
}
}
Application Configuration
spring:
datasource:
url: jdbc:postgresql://localhost:5432/sampledb
username: app
password: secret
jpa:
hibernate:
ddl-auto: validate
properties:
hibernate:
format_sql: true