summaryrefslogtreecommitdiff
path: root/spring-boot/04-bank-jpa-rest/src/main/java/com/example/spring/bank/customer/CustomerManagerImpl.java
blob: 05b3fdc97fad27c76aa9e3353466de01d76a6390 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.example.spring.bank.customer;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.spring.bank.account.Account;

import jakarta.transaction.Transactional;

@Service
public class CustomerManagerImpl implements CustomerManager {

	@Autowired
	private CustomerRepository customerRepository;
	
	@Override
	@Transactional
	public Customer create(Customer customer) {
		return customerRepository.save(customer);
	}

	@Override
	public Optional<Customer> findById(Long customerId) {
		return customerRepository.findById(customerId);
	}
	
	@Override
	public Iterable<Customer> findAll() {
		return customerRepository.findAll();
	}

	@Transactional
	@Override
	public void addAccount(Customer customer, Account account) {
		// May not work is the customer is detached.
		//	customer.getAccounts().add(account);
		
		// Access the Customer again - so that it would not be a detached entity.
		customerRepository.findById(customer.getId()).get().getAccounts().add(account);
	}
	
	// Other methods
}