Last active
August 29, 2015 14:03
-
-
Save donovanmuller/ebff90215d7953439d6b to your computer and use it in GitHub Desktop.
Original classes for SO question: http://stackoverflow.com/questions/24469690/persisting-jpa-entity-using-crudrepository
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.jpa.base.repository; | |
import org.springframework.data.repository.CrudRepository; | |
import org.springframework.data.repository.query.Param; | |
import com.jpa.base.entity.Account; | |
public interface AccountRepository extends CrudRepository<Account, Long>{ | |
public Account findByEmailAddress(@Param(value="emailAddress") String emailAddress); | |
public Account findByAccountId(@Param(value="accountId") Long accountId); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.jpa.base.service.impl; | |
import com.jpa.base.entity.Account; | |
import com.jpa.base.repository.AccountRepository; | |
import com.jpa.base.service.AccountService; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.stereotype.Repository; | |
import org.springframework.stereotype.Service; | |
import org.springframework.transaction.annotation.Transactional; | |
import javax.persistence.EntityManager; | |
import javax.persistence.EntityManagerFactory; | |
@Service("accountService") | |
@Repository | |
@Transactional | |
public class AccountServiceImpl implements AccountService { | |
@Autowired | |
private AccountRepository accountRepository; | |
@Autowired | |
EntityManagerFactory emf; | |
@Override | |
@Transactional(readOnly = true) | |
public Account findByAccountId(Long accountId) { | |
Account account = accountRepository.findByAccountId(accountId); | |
return account; | |
} | |
@Override | |
@Transactional(readOnly = true) | |
public Account findByEmailAddress(String emailAddress) { | |
Account account = accountRepository.findByEmailAddress(emailAddress); | |
return account; | |
} | |
@Override | |
@Transactional(readOnly = false) | |
public Account save(Account account) { | |
EntityManager em = emf.createEntityManager(); | |
em.persist(account); | |
em.flush(); | |
Account saved = em.merge(account); | |
return saved; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment