0

当我使用 Spring Data Jpa 模块在 MySQL 数据库中插入数据时出现问题。

问题如下:当我启动我的 Springapplication 时,我创建了数据库并使用 SpringdataJPA 初始化了数据,我看到了插入到表中的数据。之后我想插入一些与插入数据相关的数据,并且只找到之前插入的 3 条记录中的 1 条。当我重新启动服务器并且我不重新创建数据并使用相同的方法搜索它时,每条记录都会被找到。我搜索了 2 周的解决方案,但没有找到任何东西。我希望你能帮助我。

消息

我觉得只有文字很难理解,所以我在后面插入代码。jpa.xml 与所有 spring jpa 配置。2 个实体和 init 方法。希望你能找到我的错误。

jpa.xml:

<?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:property-placeholder location="classpath:properties/database/database.properties" />
<!-- Declare a datasource that has pooling capabilities--> 
<!-- BoneCP configuration -->   
<bean id="SoopDataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close" >
   <property name="driverClass" value="${database.driver}" />
   <property name="jdbcUrl" value="${database.url}" />
   <property name="username" value="${database.user}"/>
   <property name="password" value="${database.password}"/>
   <property name="idleConnectionTestPeriod" value="60"/>
   <property name="idleMaxAge" value="240"/>
   <property name="maxConnectionsPerPartition" value="30"/>
   <property name="minConnectionsPerPartition" value="5"/>
   <property name="partitionCount" value="2"/>
   <property name="acquireIncrement" value="5"/>
   <!-- <property name="statementsCacheSize" value="100"/> -->
   <!-- <property name="releaseHelperThreads" value="2"/> -->
</bean>

<!-- Declare a JPA entityManagerFactory-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >

    <property name="persistenceUnitName" value="SoopDbProvider" />
    <property name="dataSource" ref="SoopDataSource"/>
    <property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence"/>    

    <property name="jpaProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>              
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
        </props>
    </property>

    <property name="packagesToScan">
    <list>
        <value>com.soopproject.main.db</value>
    </list>
    </property>
</bean>

<!-- Db initialization bean -->
<bean id="databaseinit" class="com.soopproject.main.db.init.DatabaseInitialization" init-method="init"/>

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

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

实体:

BaseEntityWithPrimary

@MappedSuperclass
@Data
@EqualsAndHashCode(callSuper = false)
public class SoopBaseEntityWithPrimary implements
        Serializable {

    @Id
    @GeneratedValue
    private long id;

}

语:

@Entity
@Data
@EqualsAndHashCode(callSuper = true)
public class Language extends BaseEntityWithPrimary {

    @Column(nullable = false, unique = true)
    private String shortname;

    @Column(nullable = false)
    private String longname;

    @ManyToMany(cascade = CascadeType.ALL)
    private List<TranslationsShort> languageTranslationsShorts;

}

初始化方法

@Autowired
    private UserRepository userrep;

    @Autowired
    private LanguageRepository langrep;

    @Autowired
    private ErrorCodesRepository errorrep;


private void initLanguage() {
    User systemuser = null;
    try {
        systemuser = userrep.findUserByUsername("system");
    } catch (Exception ex) {
        DatabaseException exception = new DatabaseReadException(ex);
        exception.writeLog();
    }

    List<Language> languages = new LinkedList<>();

    Language deutsch = new Language();
    deutsch.setCreateUser(systemuser);
    deutsch.setShortname("DE");
    deutsch.setLongname("Deutsch");

    Language english = new Language();
    english.setCreateUser(systemuser);
    english.setShortname("EN");
    english.setLongname("English");

    Language italiano = new Language();
    italiano.setCreateUser(systemuser);
    italiano.setShortname("IT");
    italiano.setLongname("Italiano");

    languages.add(deutsch);
    languages.add(italiano);
    languages.add(english);

    for (Language lang : languages) {
        Language l_help = null;
        try {
            l_help = langrep.findLanguageByShortname(lang.getShortname());
        } catch (Exception ex) {
            DatabaseException exception = new DatabaseReadException(ex);
            exception.writeLog();
        }
        if (l_help == null)
            try {
                langrep.saveAndFlush(lang);
            } catch (Exception e) {
                DatabaseException exception = new DatabaseWriteException(e);
                exception.writeLog();
            }
    }
}



private void initErrorCodes() {
    User systemuser = null;
    Language de = null;
    Language it = null;
    Language en = null;

    try {
        systemuser = userrep.findUserByUsername("system");
    } catch (Exception ex) {
        DatabaseException exception = new DatabaseReadException(ex);
        exception.writeLog();
    }

    try {
        de = langrep.findLanguageByShortname("DE");
    } catch (Exception ex) {
        DatabaseException exception = new DatabaseReadException(ex);
        exception.writeLog();
    }

    try {
        it = langrep.findLanguageByShortname("IT");
    } catch (Exception ex) {
        DatabaseException exception = new DatabaseReadException(ex);
        exception.writeLog();
    }

    try {
        en = langrep.findLanguageByShortname("EN");
    } catch (Exception ex) {
        DatabaseException exception = new DatabaseReadException(ex);
        exception.writeLog();
    }

问题是在启动 springapplication 并<prop key="hibernate.hbm2ddl.auto">create</prop>在方法 initErrorCodes 中设置只有它的行 = langrep.findLanguageByShortname("IT"); 在数据库中查找数据。其他 2 个调用返回 null(de = langrep.findLanguageByShortname("DE"); 和 en = langrep.findLanguageByShortname("EN");)。然后我停止应用程序并查看数据库,所有数据都插入到表语言中。当我重新启动服务器时,<prop key="hibernate.hbm2ddl.auto">none</prop>所有 3 个方法调用都返回数据???!?!?!我不明白。所以肯定不是方法调用的问题。但我找不到错误。

4

1 回答 1

0

找到 3 个中的 1 个是什么意思?您是在查询数据还是访问关系?

听起来某种缓存正在发生。一些 JPA 提供程序默认启用缓存,检查您的缓存设置,并确保您正确维护双向关系。

https://en.wikibooks.org/wiki/Java_Persistence/Caching

https://en.wikibooks.org/wiki/Java_Persistence/Relationships#Object_corruption.2C_one_side_of_the_relationship_is_not_updated_after_updating_the_other_side

于 2013-09-04T14:41:02.923 回答