简体   繁体   中英

Spring JPA Repositories @PostConstruct

I am new to Spring (4.2.5) and JPA and I am facing issue related to @PostConstruct . In My project I wrote repositories and I am inserting data to them by using @PostConstruct and inside init method.

  @PostConstruct
  public void init(){
    Role roleUser = new Role();
    roleUser.setName("ROLE_USER");
    roleRepository.save(roleUser);

    Role roleAdmin = new Role();
    roleAdmin.setName("ROLE_ADMIN");
    roleRepository.save(roleAdmin);
}

I am initializing all repositories by calling in applicationContext.xml

<context:component-scan base-package="com.shiva.controller">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<context:annotation-config/>
 <jpa:repositories base-package="com.shiva.repository"  entity-manager-factory-ref="emf"  />

But in logs Tables are getting created but the problem is insert statement is not getting called and I might doubt that this init method is nit getting called.

These are the logs for table creation but I am not getting insert statements what I called from applicationContext.xml:

Hibernate: drop table if exists Blog
Hibernate: drop table if exists Item
Hibernate: drop table if exists Role
Hibernate: drop table if exists Role_User
Hibernate: drop table if exists User
Hibernate: drop table if exists User_Role
Hibernate: create table Blog (id integer not null auto_increment, name varchar(255), url varchar(255), user_id integer, primary key (id))
Hibernate: create table Item (id integer not null auto_increment, description varchar(255), link varchar(255), published_date datetime, title varchar(255), blog_id integer, primary key (id))
Hibernate: create table Role (id integer not null auto_increment, name varchar(255), primary key (id))
Hibernate: create table Role_User (Role_id integer not null, users_id integer not null)
Hibernate: create table User (id integer not null auto_increment, email varchar(255), name varchar(255), password varchar(255), primary key (id))
Hibernate: create table User_Role (User_id integer not null, roles_id integer not null)

How can I look into this issue?

Thanks All for your response .... problem was in my applicationServlet.xml file ... I modified the code to scan the jpaRepositories like this ..

<jpa:repositories base-package="com.shiva.repository"   entity-manager-factory-ref="emf" transaction-manager-ref="txManager" />

I gave the reference of entity-manager-factory and transaction-manager and it's working perfect for me :)

Enable @PostConstruct handling with:

<context:annotation-config/>

Or

<context:component-scan/>

You can find here a similar post:

@PostConstruct method is not called in Spring

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM