Spring Boot Data JPA - 不将实体保存到数据库

时间:2016-05-08 13:37:23

标签: spring hibernate spring-data spring-data-jpa

我有一个使用JPA的Spring Boot应用程序,它有2个数据源,1个用于DB2,1个用于SQL Server。

当我尝试将实体保存到SQL Server时,不会抛出任何错误,但实体不会持久保存到数据库。我没有看到日志中生成了插入内容。

提前致谢

以下是我尝试并保存实体的代码。 @Component

public class TestSave {

    @Autowired
    private BeercupMessageLogRepository repository;


    @Scheduled(fixedRate = 500000)
    public void reportCurrentTime() {
        System.out.println("Testing Save ... ");

        // Save the message in the transaction log - TypeId = 1 for Quote
        BeercupMessageLog beercupMessage = new BeercupMessageLog(1,"THIS IS A TEST ...", false);
        beercupMessage = repository.save(beercupMessage);
        System.out.println("Testing save complete ....");

    }
}

这是sql Server配置。

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages="com.xxx.beverage.repository.sqlserver",entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager")
public class sqlserverConfiguration {

    @Bean(name="datasource")
    @Primary
    @ConfigurationProperties(prefix = "sqlserver.datasource")
    public DataSource sqlserverDataSource() {
        return DataSourceBuilder.create().build();
    }

    @PersistenceContext(unitName="primary")
    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean sqlserverEntityManagerFactory(EntityManagerFactoryBuilder builder) {
         return builder.dataSource(sqlserverDataSource()).persistenceUnit("sqlServer").properties(jpaProperties())
                   .packages("com.boelter.beverage.model.sqlserver").build();     }

    private Map<String, Object> jpaProperties() {
         Map<String, Object> props = new HashMap<>();
         props.put("spring.jpa.hibernate.naming-strategy","org.hibernate.cfg.DefaultNamingStrategy");
         props.put("hibernate.default_schema","dbo");
         return props;
     }
}

这是SQL Server存储库

公共接口BeercupMessageLogRepository扩展

CrudRepository<BeercupMessageLog, Long> {

    BeercupMessageLog findOne(Long id);
    List<BeercupMessageLog> findByMessageTypeId(Long messageTypeId);
    List<BeercupMessageLog> findAll();

这是DB2配置。

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages="com.boelter.beverage.repository.db2",entityManagerFactoryRef = "entityManagerFactory
2", transactionManagerRef = "transactionManager2")
public class db2Configuration {

    @Bean(name="db2DataSource")
    @ConfigurationProperties(prefix = "db2.datasource")
    public DataSource db2DataSource() {
        return DataSourceBuilder.create().build();
    }

    @PersistenceContext(unitName="secondary")
    @Bean(name = "entityManagerFactory2")
    public LocalContainerEntityManagerFactoryBean db2EntityManagerFactory(EntityManagerFactoryBuilder builder) {
         return builder.dataSource(db2DataSource()).persistenceUnit("db2").properties(jpaProperties())
                   .packages("com.boelter.beverage.model.db2").build();     }

    private Map<String, Object> jpaProperties() {
         Map<String, Object> props = new HashMap<>();
         props.put("spring.jpa.hibernate.naming-strategy","org.hibernate.cfg.DefaultNamingStrategy");
         //props.put("spring.jpa.hibernate.naming-strategy","org.hibernate.cfg.ImprovedNamingStrategy");
         //props.put("spring.jpa.properties.hibernate.default_schema","R3QASDATA");
         //props.put("spring.jpa.show-sql","true");
         return props;
     }
}

这是实体。

package com.boelter.beverage.model.sqlserver;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.springframework.transaction.annotation.Transactional;
@Table (name="[BeercupMessageLog]")
@Entity
@Transactional
public class BeercupMessageLog {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long    messageId;

    @Column(name="MessageTypeId", nullable = false)
    private long    messageTypeId;

    @Column(name="Processed", nullable = false)
    private boolean processed;

    // Set updatable and insertable to false so JPA does not try to pass a value.  The DB has a default
    // of the current date if no value is passed
    @Column(name="MessageDate", updatable=false, insertable=false)
    private Date    messageDate;

    @Column(name="MessageText", nullable = false)
    private String  messageText;

    protected BeercupMessageLog() {}

    public BeercupMessageLog(long messageTypeId, String messageText, boolean processed) {
        this.messageTypeId = messageTypeId;
        this.messageText = messageText;
        this.processed = processed;
    }

    /**
     * @return the messageId
     */
    public long getMessageId() {
        return messageId;
    }

    /**
     * @param messageId the messageId to set
     */
    public void setMessageId(long messageId) {
        this.messageId = messageId;
    }

    /**
     * @return the messageTypeId
     */
    public long getMessageTypeId() {
        return messageTypeId;
    }

    /**
     * @param messageTypeId the messageTypeId to set
     */
    public void setMessageTypeId(long messageTypeId) {
        this.messageTypeId = messageTypeId;
    }

    /**
     * @return the messageDate
     */
    public Date getMessageDate() {
        return messageDate;
    }

    /**
     * @param messageDate the messageDate to set
     */
    public void setMessageDate(Date messageDate) {
        this.messageDate = messageDate;
    }

    /**
     * @return the processed
     */
    public boolean isProcessed() {
        return processed;
    }

    /**
     * @param processed the processed to set
     */
    public void setProcessed(boolean processed) {
        this.processed = processed;
    }

    /**
     * @return the messageText
     */
    public String getMessageText() {
        return messageText;
    }

    /**
     * @param messageText the messageText to set
     */
    public void setMessageText(String messageText) {
        this.messageText = messageText;
    }

    @Override
    public String toString() {
        return String.format(
                "BeercupMessage[id=%d, typeId=%d, message='%s']",
                messageId, messageTypeId, messageText);
    }

}

3 个答案:

答案 0 :(得分:3)

我有同样的问题,对我来说是Spring Batch:

public class BatchConfiguration extends DefaultBatchConfigurer {

我扩展DefaultBatchConfigurer的事实是创建了第二个EntityManager,因此我的数据源没有将数据保存到数据库中。

答案 1 :(得分:3)

我想你的DB2数据库还没有保存,因为问题是您需要为数据库,entitymanager工厂和事务管理器未标记的数据库设置自定义transactionManagerRef @Primary。 在这里,您配置了transactionManagerRef = "transactionManager2",但未将其注入配置bean。

只需添加db2Configuration之类的内容:

@Bean(name = "transactionManager2")
public PlatformTransactionManager accountTransactionManager(EntityManagerFactoryBuilder builder) {
    JpaTransactionManager tm = new JpaTransactionManager();
    tm.setEntityManagerFactory(db2EntityManagerFactory(builder).getObject());
    tm.setDataSource(db2DataSource());
    return tm;
}

答案 2 :(得分:0)

使用org.springframework.batch.support.transaction.ResourcelessTransactionManager也将破坏事务数据库的提交功能。因此,请勿将ResourcelessTransactionManager创建为bean。