当前位置: 首页 > 知识库问答 >
问题:

Spring数据jpa-save()不持久化任何enities

隆安然
2023-03-14
package com.howtodoinjava.entity;

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.data.neo4j.annotation.Indexed;

@Entity
@Table(name = "EMPLOYEE")
@SuppressWarnings("SerializableClass")
public class EmployeeEntity {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column(name = "FIRSTNAME")
    private String firstname;

    @Column(name = "LASTNAME")
    private String lastname;

    @Indexed
    @Column(name = "EMAIL")
    private String email;

    @Column(name = "TELEPHONE")
    private String telephone;

    public String getEmail() {
        return email;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getFirstname() {
        return firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}
package com.howtodoinjava.service;

import com.howtodoinjava.entity.EmployeeEntity;
import com.howtodoinjava.repository.jpa.EmployeeJpaRepository;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.neo4j.helpers.collection.IteratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class EmployeeManagerJpa implements EmployeeManager {

    @Autowired
    private EmployeeJpaRepository employeeRepository;

    @Transactional
    public void addEmployee(EmployeeEntity employee) {
        employeeRepository.save(employee);
    }

    @Transactional
    public List<EmployeeEntity> getAllEmployees() {
        return (List<EmployeeEntity>) makeCollection(employeeRepository.findAll());
    }

    @Transactional
    public void deleteEmployee(Long employeeId) {
        employeeRepository.delete(getEmployee(employeeId));
    }

    @Transactional
    public EmployeeEntity getEmployee(Long employeeId) {
        return employeeRepository.findOne(employeeId);
    }

    public static <E> Collection<E> makeCollection(Iterable<E> iter) {
        Collection<E> list = new ArrayList<E>();
        for (E item : iter) {
            list.add(item);
        }
        return list;
    }
}
package com.howtodoinjava.repository.jpa;

import com.howtodoinjava.entity.EmployeeEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;

public interface EmployeeJpaRepository extends JpaRepository<EmployeeEntity, Long> {}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
       xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
       xmlns:tx="http://www.springframework.org/schema/tx" 
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd            
            http://www.springframework.org/schema/data/jpa
            http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
            http://www.springframework.org/schema/data/neo4j
            http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

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

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

    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean> 
</beans>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
       xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
       xmlns:tx="http://www.springframework.org/schema/tx" 
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd            
            http://www.springframework.org/schema/data/jpa
            http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <jpa:repositories base-package="com.howtodoinjava.repository.jpa" />

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" > 
        <property name="packagesToScan" value="com.howtodoinjava.entity" />
        <property name="persistenceUnitName" value="SpringDataJPA" />
        <!--property name="dataSource" ref="dataSource" /-->
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <property name="persistenceProvider">
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
        </property>
    </bean>

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

</beans>
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">

    <persistence-unit name="SpringDataJPA" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>      
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/atom" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="123456" />

            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="update" />

        </properties>
    </persistence-unit>
</persistence>
Aug 27, 2014 3:06:48 AM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: SpringDataJPA
    ...]
Aug 27, 2014 3:06:48 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.6.Final}
Aug 27, 2014 3:06:48 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Aug 27, 2014 3:06:48 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Aug 27, 2014 3:06:48 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Aug 27, 2014 3:06:48 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Aug 27, 2014 3:06:48 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/atom]
Aug 27, 2014 3:06:48 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
Aug 27, 2014 3:06:48 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Aug 27, 2014 3:06:48 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Aug 27, 2014 3:06:48 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 27, 2014 3:06:48 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Aug 27, 2014 3:06:49 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Aug 27, 2014 3:06:49 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Aug 27, 2014 3:06:49 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Aug 27, 2014 3:06:49 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Aug 27, 2014 3:06:49 AM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: atom.employee
Aug 27, 2014 3:06:49 AM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [firstname, telephone, id, email, lastname]
Aug 27, 2014 3:06:49 AM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
Aug 27, 2014 3:06:49 AM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
Aug 27, 2014 3:06:49 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: select employeeen0_.ID as ID1_0_, employeeen0_.EMAIL as EMAIL2_0_, employeeen0_.FIRSTNAME as FIRSTNAM3_0_, employeeen0_.LASTNAME as LASTNAME4_0_, employeeen0_.TELEPHONE as TELEPHON5_0_ from EMPLOYEE employeeen0_
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.519 sec

/**若要更改此许可证标头,请在项目属性中选择许可证标头。*要更改此模板文件,请选择工具模板*并在编辑器中打开模板。*/

package com.howtodoinjava;

import com.howtodoinjava.entity.EmployeeEntity;
import com.howtodoinjava.service.EmployeeManager;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:employee-servlet*.xml")
@Transactional
public class EmployeeManagerTest {

    @Test
    public void emptyTest() {
    }

    @Autowired
    @Qualifier("employeeManagerJpa")
    EmployeeManager employeeManager;

    @Test
    public void test() {
        EmployeeEntity employee = new EmployeeEntity();
        employee.setFirstname("Tom");
        employee.setLastname("One");
        employee.setTelephone("12-154-789");
        employee.setEmail("tom_one@mail.com");

        EmployeeEntity employee1 = new EmployeeEntity();
        employee1.setFirstname("Kat");
        employee1.setLastname("Two");
        employee1.setTelephone("12-154-789");
        employee1.setEmail("kat_two@mail.com");

        employeeManager.addEmployee(employee);
        employeeManager.addEmployee(employee1);

        Assert.assertEquals("Two",employee1.getLastname()); // True

        Assert.assertEquals(0, employeeManager.getAllEmployees().size()); // Always true
    }
}

Edit:如果我使用saveAndFlush()强制写入,我将得到no transaction的错误:org.springframework.dao.invalidDataAccessapiusageException:no transaction正在进行;嵌套异常是javax.persistence.TransactionRequiredException:没有事务在进行中

我检查了web上找到的大多数修复(包括 参数、@transactional参数、删除@service注释并在employee-servlet-app.xml上下文文件中显式创建bean)。

任何其他建议都非常感谢。请随时询问任何其他可能有帮助的信息。

共有1个答案

单勇
2023-03-14

persistence.xml中,您有

<persistence-unit name="SpringDataJPA" transaction-type="RESOURCE_LOCAL">

事务类型不应该是JTA吗?

默认行为afaik是,事务总是自动创建,不管发生什么,但它是只读的。因此,如果配置(或代码)有问题,那么将不会持久化任何内容。

 类似资料:
  • 我正在创建一个新项目,并使用Spring Data JPA创建一些RESTendpoint。 只要json文件没有任何oneToMany数据,我就可以将其放到并持久化到我的主类(customer)中。然而,当张贴给客户,如果有任何数据,我会得到错误。 那些电子邮件 postman json测试 顺便说一句,我已经确认在客户控制器中,电子邮件包括在客户的请求体中。 客户控制器 因此,对于post或p

  • 如何在一对多的关系中保持子实体? 创建注册时,如果付款表中的注册列不可为空: 通用域名格式。mysql。jdbc。例外情况。jdbc4.MySQLIntegrityConstraintViolationException:列“registration”不能为null 但如果注册可为null,则会创建付款,但注册列为null: 直到发生异常并执行“HH000010:在批处理发布时,它仍然包含JDBC

  • 我有连接到我的数据库运行。我可以执行以下没有问题: 然而,在设置了JPA和持久类之后,我总是得到一个“未选择数据库”错误。看起来我不需要调整我的数据库配置(MySQL连接到Glassfish 3.1),否则上面的代码将无法工作。 正在拨打的电话: 我尝试过这个调用直接在MySQL工作台和它不工作。 这一个确实有效: 我一直在玩游戏,似乎无法在任何地方添加数据库名称(“人”)。以下是我目前掌握的情况

  • 我有一个简单的JPA存储库,看起来如下所示: 和两个有一个单子映射的类,如下所示: . 现在,我知道我可以很容易地编辑和持久化一个像这样的用户实例: 但是,在没有指向实例的指针的上下文中,如何持久化实例,f.I.: 我可以只调用吗? 我是否需要自动连接另一个存储库()并在其上调用.save()?

  • 我想创建一个作业,但我想在没有任何数据库持久性的情况下运行它。不幸的是spring-batch要求以某种方式将作业循环写入数据库的,从而使我至少提供某种带有transactionmanager和EntityManager的db。 是否可以阻止元数据并独立于TXManager和数据库运行? 更新: