Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JpaRepository won't save data

I use JpaRepository to save data, but the hibernate.show_sql shows "select" and won't save data. Following is my service:

@Autowired
private UserRepository userRepository;

@PostConstruct
public void init() {
    User admin = new User();
    admin.setDisplayName("admin");
    admin.setEmailAddress("admin@admin");
    admin.setPassword("admin___");
    admin.setRegisteredAt(new Date());
    admin.setLastAccessAt(new Date());
    admin.setUuid(UUID.randomUUID().toString());

    try {
        System.out.println("before save");
        userRepository.save(admin);
        System.out.println("after save");
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

The output looks like this:

========before save======

Hibernate: select user0_.uuid as uuid1_0_0_, user0_.display_name as display_2_0_0_, user0_.email_address as email_ad3_0_0_, user0_.last_access_at as last_acc4_0_0_, user0_.password as password5_0_0_, user0_.registered_at as register6_0_0_ from User user0_ where user0_.uuid=?

========after save=======

Following is my applicationContext.xml:

<context:component-scan base-package="test">
    <context:exclude-filter type="annotation"
        expression="org.springframework.stereotype.Controller" />
</context:component-scan>

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/helloworld" />
    <property name="username" value="root" />
    <property name="password" value="password" />
</bean>

<bean id="myEmf"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="packagesToScan" value="test.entity"></property>
    <property name="dataSource" ref="myDataSource" />
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
    <property name="persistenceProvider">
        <bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
    </property>
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="myDataSource" />
</bean>

<jpa:repositories base-package="test.repository"
    entity-manager-factory-ref="myEmf" transaction-manager-ref="transactionManager"></jpa:repositories>

Attached is my class generated by JPA Tools:

@Entity
@NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
  private static final long serialVersionUID = 1L;

  @Id
  private String uuid;

  @Column(name="display_name")
  private String displayName;

  @Column(name="email_address")
  private String emailAddress;

  @Temporal(TemporalType.TIMESTAMP)
  @Column(name="last_access_at")
  private Date lastAccessAt;

  private String password;

  @Temporal(TemporalType.TIMESTAMP)
  @Column(name="registered_at")
  private Date registeredAt;

  public   User() {
  }

  public String getUuid() {
      return this.uuid;
  }

  public void setUuid(String uuid) {
      this.uuid = uuid;
  }

  public String getDisplayName() {
      return this.displayName;
  }

  public void setDisplayName(String displayName) {
      this.displayName = displayName;
  }

  public String getEmailAddress() {
      return this.emailAddress;
  }

  public void setEmailAddress(String emailAddress) {
      this.emailAddress = emailAddress;
  }

  public Date getLastAccessAt() {
      return this.lastAccessAt;
  }

  public void setLastAccessAt(Date lastAccessAt) {
      this.lastAccessAt = lastAccessAt;
  }

  public String getPassword() {
      return this.password;
  }

  public void setPassword(String password) {
      this.password = password;
  }

  public Date getRegisteredAt() {
      return this.registeredAt;
  }

  public void setRegisteredAt(Date registeredAt) {
      this.registeredAt = registeredAt;
  }

}
like image 426
Study Hard Avatar asked Sep 06 '15 12:09

Study Hard


People also ask

How does JpaRepository save work?

The save operation performs a merge on the underlying EntityManager . This on its own doesn't perform any SQL but just returns a managed version of the entity. If that isn't already loaded into the EntityManager it might do this or it might identify the entity as a new one and make it a managed entity.

Should I use JpaRepository or CrudRepository?

Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.

What is difference between save and Saveflush?

On saveAndFlush , changes will be flushed to DB immediately in this command. With save , this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.


1 Answers

Since you're using JPA, the transaction manager should be a JpaTransactionManager, not a DataSourceTransactionManager.

like image 59
JB Nizet Avatar answered Oct 05 '22 22:10

JB Nizet