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

Spring Data JPA审计功能在我的项目中不起作用

夹谷浩博
2023-03-14

我正在阅读“ProSpring3”一书,并尝试在我的项目中使用Spring Data JPA功能。我在这里发布相关文件。

src/main/java/foo/bar/domain/ContactAudit。java语言:

package foo.bar.domain;

import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import org.springframework.data.domain.Auditable;

import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import static javax.persistence.GenerationType.IDENTITY;


@Table(name = "CONTACT_AUDIT")
@Entity
public class ContactAudit implements Auditable<String, Long>{
    private Long id;
    private String firstName;
    private String lastName;
    private Date birthDate;
    private int version;

    private Set<Hobby> hobbies = new HashSet<Hobby>();
    private Set<ContactTelDetail> contactTelDetails = new HashSet<ContactTelDetail>();

    //Audit fields
    private String createdBy;
    private DateTime createdDate;
    private String lastModifiedBy;
    private DateTime lastModifiedDate;

    //constructors
    public ContactAudit() {
    }

    public ContactAudit(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public ContactAudit(String firstName, String lastName, Date birthDate, Set<Hobby> hobbies, Set<ContactTelDetail> contactTelDetails) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.birthDate = birthDate;
        this.hobbies = hobbies;
        this.contactTelDetails = contactTelDetails;
    }

    @Column(name = "ID")
    @Id
    @GeneratedValue(strategy = IDENTITY)
    public Long getId() {
        return id;
    }

    @Override
    @Transient
    public boolean isNew() {
        if (id == null)
            return true;
        else
            return false;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "FIRST_NAME")
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Column(name = "LAST_NAME")
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Column(name = "BIRTH_DATE")
    @Temporal(TemporalType.DATE)
    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    @Column(name = "VERSION")
    @Version
    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

    @ManyToMany
    @JoinTable(name = "contact_hobby_detail",
            joinColumns = @JoinColumn(name = "CONTACT_ID"),
            inverseJoinColumns = @JoinColumn(name = "HOBBY_ID"))
    public Set<Hobby> getHobbies() {
        return hobbies;
    }

    public void setHobbies(Set<Hobby> hobbies) {
        this.hobbies = hobbies;
    }

    @OneToMany(mappedBy = "contact", cascade = CascadeType.ALL, orphanRemoval = true)
    public Set<ContactTelDetail> getContactTelDetails() {
        return contactTelDetails;
    }

    public void setContactTelDetails(Set<ContactTelDetail> contactTelDetails) {
        this.contactTelDetails = contactTelDetails;
    }

    @Column(name = "CREATED_BY")
    public String getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    @Column(name = "CREATED_DATE")
    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    public DateTime getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(DateTime createdDate) {
        this.createdDate = createdDate;
    }

    @Column(name = "LAST_MODIFIED_BY")
    public String getLastModifiedBy() {
        return lastModifiedBy;
    }

    public void setLastModifiedBy(String lastModifiedBy) {
        this.lastModifiedBy = lastModifiedBy;
    }

    @Column(name = "LAST_MODIFIED_DATE")
    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    public DateTime getLastModifiedDate() {
        return lastModifiedDate;
    }

    public void setLastModifiedDate(DateTime lastModifiedDate) {
        this.lastModifiedDate = lastModifiedDate;
    }

    //other methods
    public String toString()
    {
        return "Contact - Id: " + id + ", First name: " + firstName + ", Last name: " + lastName + ", Birthday: " + birthDate
                + ", Create by: " + createdBy + ", Create date: " + createdDate + ", Modified by: " + lastModifiedBy + ", Modifed date: " + lastModifiedDate;

    }

}

src/main/java/foo/bar/repository/ContactAuditRepository.java :

package foo.bar.repository;

import foo.bar.domain.ContactAudit;
import org.springframework.data.repository.CrudRepository;


public interface ContactAuditRepository extends CrudRepository<ContactAudit, Long>{
}

src/main/java/foo/bar/service/ContactAuditService.java :

package foo.bar.service;

import foo.bar.domain.ContactAudit;

import java.util.List;


public interface ContactAuditService {

    public List<ContactAudit> findAll();

    public ContactAudit findById(Long id);

    public ContactAudit save(ContactAudit contact);
}

src/main/java/foo/bar/service/spingjpa/ContactAuditServiceImpl.java

package foo.bar.service.springjpa;

import com.google.common.collect.Lists;
import foo.bar.domain.ContactAudit;
import foo.bar.repository.ContactAuditRepository;
import foo.bar.service.ContactAuditService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service("contactAuditService")
@Repository
@Transactional
public class ContactAuditServiceImpl implements ContactAuditService{

    @Autowired
    private ContactAuditRepository contactAuditRepository;

    @Override
    @Transactional(readOnly = true)
    public List<ContactAudit> findAll() {
        return Lists.newArrayList(contactAuditRepository.findAll());
    }

    @Override
    @Transactional(readOnly = true)
    public ContactAudit findById(Long id) {
        return contactAuditRepository.findOne(id);
    }

    @Override
    public ContactAudit save(ContactAudit contact) {
        return contactAuditRepository.save(contact);
    }
}

src/main/java/foo/bar/spingjpa/Auditor/AuditorAwareBean.java:

package foo.bar.springjpa.auditor;

import org.springframework.data.domain.AuditorAware;


public class AuditorAwareBean implements AuditorAware<String>{
    @Override
    public String getCurrentAuditor() {
        return "prospring3";
    }
}

src/main/resources/spring-config . 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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
    <context:annotation-config />
    <context:component-scan base-package="foo.bar.service.springjpa"/>


    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName">
            <value>${jdbc.driverClassName}</value>
        </property>
        <property name="url">
            <value>${jdbc.url}</value>
        </property>
        <property name="username">
            <value>${jdbc.username}</value>
        </property>
        <property name="password">
            <value>${jdbc.password}</value>
        </property>
    </bean>

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

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

    <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <property name="packagesToScan" value="foo.bar.domain"/>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.max_fetch_depth">3</prop>
                <prop key="hibernate.jdbc.fetch_size">50</prop>
                <prop key="hibernate.jdbc.batch_size">10</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <context:property-placeholder location="jdbc.properties"/>

    <jpa:repositories base-package="foo.bar.repository"
                      entity-manager-factory-ref="emf"
                      transaction-manager-ref="transactionManager"/>

    <jpa:auditing auditor-aware-ref="auditorAwareBean"/>

    <bean id="auditorAwareBean" class="foo.bar.springjpa.auditor.AuditorAwareBean"/>
</beans>

src/main/java/META-INF/persistence.xml :

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">

    <persistence-unit name="NewPersistenceUnit"/>

</persistence>

src/main/java/META-INF/orm.xml:

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

    <description>JPA</description>

    <persistence-unit-metadata>
        <persistence-unit-defaults>
            <entity-listeners>
                <entity-listener class="org.springframework.data.jpa.domain.support.AuditingEntityListener"/>
            </entity-listeners>
        </persistence-unit-defaults>
    </persistence-unit-metadata>

</entity-mappings>

--

src/main/Java/foo/bar/springjpaauditsample . Java:

package foo.bar;

import foo.bar.domain.ContactAudit;
import foo.bar.service.ContactAuditService;
import org.springframework.context.support.GenericXmlApplicationContext;

import java.util.Date;
import java.util.List;


public class SpringJpaAuditSample {

    public static void main(String[] args) {
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("spring-config.xml");

        ContactAuditService contactService = ctx.getBean("contactAuditService", ContactAuditService.class);

        List<ContactAudit> contacts = contactService.findAll();
        listContacts(contacts);

        //Add new contact
        System.out.println("Add new contact");
        ContactAudit contact = new ContactAudit();
        contact.setFirstName("Michael");
        contact.setLastName("Jackson");
        contact.setBirthDate(new Date());
        contactService.save(contact);

        contacts = contactService.findAll();
        listContacts(contacts);
    }

    private static void listContacts(List<ContactAudit> contacts)
    {
        System.out.println("");
        System.out.println("Listing contacts without details:");
        for(ContactAudit contact: contacts)
        {
            System.out.println(contact);
            System.out.println();
        }
    }
}

findAll返回这个:

Listing contacts without details:
Contact - Id: 4, First name: Michael, Last name: Jackson, Birthday: 2013-05-27, Create by: null, Create date: 2013-05-27T04:02:36.000+03:00, Modified by: null, Modifed date: 2013-05-27T04:02:36.000+03:00

这意味着我得到 null 而不是字符串 'prospring3'。

有什么想法吗?谢谢你。

共有1个答案

步兴为
2023-03-14

我用IntelliJ idea创建的这个项目的“错误”是,我让IDE在它选择的任何地方创建META-INF目录,我没有注意到作者已经将其放在资源目录中。修复的动机来自这篇文章(“未找到持久性单元”错误)。

 类似资料:
  • 问题内容: 我正在学习Vue并在计算属性中使用箭头功能时遇到问题。 我的原始代码工作正常(请参见下面的代码段)。 但是,更改计算属性中的方法后,颜色不会更改(尽管turnRed值仍成功在true和false之间切换)。 这是我的代码: 我使用错误的语法吗? 问题答案: 您遇到此错误是因为箭头函数不会绑定到您要为其定义计算属性的vue实例。如果要使用箭头功能进行定义,也会发生同样的情况。 不要在实例

  • 我试图在我的Angular2应用程序中使用RouteConfig。现在,我似乎找不到我做错了什么。 我的应用程序组件正在使用路由器插座,但它不工作。 我已经创建了一个主。引导我的应用程序的ts文件: 主要的ts 应用程序组件 当一个用户输入地址:localhost:3000或localhost:3000/amendment,它应该加载AmendmentComponent组件,但什么都没发生,我可以

  • 您可以从Burp 仪表板(dashboard)中打开任务详细信息窗口(task details)来访问扫描任务中含有审计的具体项目。 该栏显示了每个项目的以下详细信息: 项目的编号。 目标主机的协议,Host和URL。 该项的当前状态。 针对被动,主动或是JS分析的各个审计阶段已完成进度。 该项按严重性分类后已确定的问题问题数量。 审计时发出的请求数。请注意,这不是针对插入点数量的线性函数 - 观

  • 我正在用spring做一个rest API来做crud操作。在我的angular应用程序中,删除HTTP客户端不起作用,当我单击删除按钮时,选定的id不会被删除。我知道我的服务器正在运行,并且控制器代码是正确的。 这是员工列表.组件. ts 这是服务页面- employee.service.ts 下面是按钮如何绑定到employee-list.component.html中的deleteClae(

  • 问题内容: 我正在使用这种技术来加载数据。因此,我创建了以下解析函数: 存在的问题是,是在瞬间函数执行。它是正确的/错误吗?我该如何解决? 问题答案: 您需要改用。该只更新 后 的路线被改变。因此,您的代码应遵循以下原则:

  • 我正在构建一个Spring启动应用程序。我对这项技术还很陌生。我已经看到了许多关于如何启用审计的示例。我似乎已经遵循了所需的配置和设置。但是在标记lastModifiedBy的“更新”操作期间,审计不起作用 以下是我在项目中的代码。 实体-我ssue.java 一个uditable.java 审核配置。JAVA AuditAwareImpl。JAVA IssueController。JAVA 发行