首页 > Java程序员从笨鸟到菜鸟之(七十四)细谈Spring(六)spring之AOP基本概念和配置详解


相关标签: spring 程序员 aop 配置 java



up vote 4 down vote favorite 3

I was using Google guice in my project and now I tried to convert the framework to SpringBoot totally.

I configured the Bean for persistence.xml like below in

@Bean(name = "transactionManager")
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
    LocalContainerEntityManagerFactoryBean lEMF =  new LocalContainerEntityManagerFactoryBean();
    return lEMF;

Now I need to configure(Inject) EntityManager em, to do JPA operations like em.persist(), em.find etc... How do I configure, also someone try to explain this with sample code

spring-boot share | improve this question edited Oct 12 '15 at 8:35 M. Deinum 45.4k 7 84 110 asked Oct 12 '15 at 6:30 Aravind E 107 1 3 9 add a comment  | 

2 Answers 2

active oldest votes up vote 9 down vote accepted

With Spring Boot its not necessary to have any config file like persistence.xml. You can configure with annotations Just configure your DB config for JPA in the



Then you can use CrudRepository provided by Spring where you have standard CRUD transaction methods. There you can also implement your own SQL's like JPQL.

public interface ObjectRepository extends CrudRepository<Object, Long> {

And if you still need to use the Entity Manager you can create another class.

public class ObjectRepositoryImpl implements ObjectCustomMethods{

    private EntityManager em;


This should be in your pom.xml




share | improve this answer edited Oct 12 '15 at 8:33 answered Oct 12 '15 at 7:09 Patrick 2,580 1 15 45      Thanks, Is it possible to use JPARepository instead of CRUD repository. whats the diff –  Aravind E Oct 12 '15 at 10:56      I think this should not be a problem. Here is a good documentation. –  Patrick Oct 12 '15 at 11:32 1   @Patrick what if there are custom datasources connecting to different database. In that case wouldn't you need to use separate entitymanagers ? How would one pass in hibernate properties in such a case ? –  user3869813 Jan 23 at 4:18 add a comment  |  up vote 7 down vote

Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample

@ComponentScan(basePackageClasses = { 
    RepositoryMarker.class }
public class AppConfig {



@PropertySource(value = { "classpath:database/" })
public class PersistenceConfig {

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};

    private Environment env;

     @Bean(destroyMethod = "close")
     public DataSource dataSource() {
         BasicDataSource dataSource = new BasicDataSource();
         return dataSource;

     public JpaTransactionManager jpaTransactionManager() {
         JpaTransactionManager transactionManager = new JpaTransactionManager();
         return transactionManager;

    private HibernateJpaVendorAdapter vendorAdaptor() {
         HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
         return vendorAdapter;

    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {

         LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();

         return entityManagerFactoryBean;

     private Properties jpaHibernateProperties() {

         Properties properties = new Properties();


         properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
         properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");      
         return properties;       



public static void main(String[] args) { 
    try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
        MyService myService = springContext.getBean(MyServiceImpl.class);
        try {
            myService.handleProcess(fromDate, toDate);
        } catch (Exception e) {
            logger.error("Exception occurs", e);
            myService.handleException(fromDate, toDate, e);
    } catch (Exception e) {
        logger.error("Exception occurs in loading Spring context: ", e);


public class MyServiceImpl implements MyService {

    private MyDao myDao;

    public void handleProcess(String fromDate, String toDate) {
        List<Student> myList =, toDate);


public class MyDaoImpl implements MyDao {

    private EntityManager entityManager;

    public Student select(String fromDate, String toDate){

        TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
        query.setParameter("fromDate", fromDate);
        query.setParameter("toDate", toDate);
        List<Student> list = query.getResultList();
        return CollectionUtils.isEmpty(list) ? null : list;


Assuming maven project: Properties file should be in src/main/recourses/database folder file

jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password

hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true

ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.

Let say you have package name a.b.c.service.impl. MyServiceImpl is in this package and also ServiceMarker.

public interface ServiceMarker {


Same for repory marker. Let say you have a.b.c.repository.impl or a.b.c.dao.impl package name. Then MyDaoImpl is in this this package and also Repositorymarker

public interface RepositoryMarker {



//dummy class and dummy query
@NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
public class Student implements Serializable {

    private LocalDateTime fromDate;
    private LocalDateTime toDate;

    //getters setters



@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

    public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {

        if (dateTime == null) {
            return null;
        return Timestamp.valueOf(dateTime);

    public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {

        if (timestamp == null) {
            return null;
        return timestamp.toLocalDateTime();




    <!-- Spring -->









Hope it helps. Thanks

share | improve this answer edited Oct 12 '15 at 7:40 answered Oct 12 '15 at 7:11 Basit 3,187 31 80 144      Thanks Basti it helped me a lot –  Aravind E Oct 12 '15 at 10:11      My pleasure :) You can also use Spring Data JPA in your project. In this way you don't have to write simple queries on your domain classes. Also it will simplify your application even more . Follow this link… –  Basit Oct 12 '15 at 10:30      That's great - finally some documentation on how to do this! Just one question, which I will tackle now that it's clear how to get this far: how do you code it without any hard-coded dependency on the JDBC driver classes and the connection pool classes? –  Adam Nov 4 '16 at 17:18      In POM there is a dependency of MySQL mysql-connector-java. This could be SQLServer or oracle. But in case of SQLServer or Oracle or any proprietary JDBC driver you need to download jar and using maven import it in your maven local repository. You can google. It's very easy. Also for connection pooling In POM there is commons-dbcp2. In PersistenceConfig see dataSource(). I used defaults. But you can configure it according to your needs. Like I said in my answer lot of tutorials on the net ;) :) –  Basit Nov 22 '16 at 15:28      Also From hibernate onwards 5.2.0. hibernate-entitymanager is no longer needed. Just include hibernate-core. But 5.2.0 have problem with Spring Data JPA while process collection.` hibernate-core 5.2.1` and above is ok with Spring Data JPA if you are using Spring Data JPA. –  Basit Nov 22 '16 at 15:32 add a comment  | 

Your Answer

  draft saved draft discarded

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name Email

Post as a guest

Name Email discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged spring-boot or ask your own question.


up vote 4 down vote favorite 3 I was using Google guice in my project and now I tried to convert the framework to SpringBoot totally. I configured the Bean for persistence.xml like