大家有没有遇到使用spring data jpa hibernate无法自动写入时间戳的问题?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了大家有没有遇到使用spring data jpa hibernate无法自动写入时间戳的问题?相关的知识,希望对你有一定的参考价值。

数据库是 mysql,字段类型是datatime
代码如下:
//对象创建时间
@Temporal(TemporalType.TIMESTAMP)//不用set,hibernate会自动把当前时间写入
@Column(updatable = false, length = 20,name="create_time")
private Date createTime;

参考技术A 表建立时这个列是指定的默认值的吧?
再加 insertable=false, @Basic(optiona=false) 看看。

没有 Spring Boot 的 Spring Data JPA

【中文标题】没有 Spring Boot 的 Spring Data JPA【英文标题】:Spring Data JPA without Spring Boot 【发布时间】:2014-07-21 08:57:58 【问题描述】:

Spring Boot 不适用于 Google App Engine(至少不适合我)。

无论 GitHub 或其他存储库中编写或提供的许多示例都使用 Spring Boot,是否有任何不使用 Spring Boot 并使用纯上下文 XML 的 Spring-Data-JPA 示例和以前一样?

这会显示

- spring/context.xml(或servlet-context.xml)

【问题讨论】:

非常接近您的要求(不同之处在于大多数情况下使用 Java Config 而不是 XML)是本系列中的教程petrikainulainen.net/programming/spring-framework/… http://www.springbyexample.org/examples/spring-data-jpa.html 如果您有兴趣,这里有一个带有 Spring Boot 的 GAE 示例:github.com/scratches/spring-boot-sample-gae。为什么要使用 XML 并不是很清楚,但请注意,也没有什么能阻止您将 Spring Boot 与 XML 结合使用。 确实工作了。如果您想修复它并发送拉取请求,请成为我的客人。 我没有看到这个问题,并且应用程序运行良好(昨天从 master 部署)。 【参考方案1】:

刚刚为您创建了这个示例:

src/main/webapp/WEB-INF/spring/context.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: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:property-placeholder location="/WEB-INF/spring/jdbc.properties" />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        p:driverClassName="$jdbc.driverClassName" p:url="$jdbc.url"
        p:username="$jdbc.username" p:password="$jdbc.password" />

    <bean id="hibernateJpaVendorAdapter"
        class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />

    <!-- Configure the entity manager factory bean -->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
        <!-- Set JPA properties -->
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">$hibernate.dialect</prop>
            </props>
        </property>
        <property name="packagesToScan" value="com.demo.data" />
    </bean>

    <!-- Configure the transaction manager bean -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <tx:annotation-driven />

    <jpa:repositories base-package="com.demo.data" />
    <context:component-scan base-package="com.demo.svc" />
</beans>

/src/main/webapp/WEB-INF/spring/jdbc.properties

# JDBC Connection
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://host:3306/db
jdbc.username=user
jdbc.password=password
hibernate.dialect=org.hibernate.dialect.MySQLDialect

/src/main/webapp/WEB-INF/spring/servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        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">

    <context:component-scan base-package="com.demo.web" />
</beans:beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/context.xml</param-value>
    </context-param>
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>demo_jpa</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

pom.xml

<properties>
    <org.springframework-version>4.1.7.RELEASE</org.springframework-version>
    <org.hibernate-em-version>4.3.8.Final</org.hibernate-em-version>
    <org.springframework.data-version>1.9.0.RELEASE</org.springframework.data-version>
    <dbcp-version>1.4</dbcp-version>
    <mysql-connector-version>5.1.28</mysql-connector-version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>$org.springframework-version</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>$org.springframework-version</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>$org.springframework.data-version</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>$org.hibernate-em-version</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>$mysql-connector-version</version>
    </dependency>

    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>$dbcp-version</version>
    </dependency>
</dependencies>

数据实体:com.demo.data.User

package com.demo.data;

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

@Entity
@Table(name = "SYS_USERS")
public class User 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "USER_ID")
    private int id;

    @Column(name = "USER_NAME")
    private String name;

    public int getId() 
        return id;
    

    public void setId(int id) 
        this.id = id;
    

    public String getName() 
        return name;
    

    public void setName(String name) 
        this.name = name;
    

Spring Data JPA 存储库:com.demo.data.UserRepository

package com.demo.data;

import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, Integer> 

服务

界面:

package com.demo.svc;

import com.demo.data.User;

public interface UserService 
    User findUserById(Integer id);

实施:

package com.demo.svc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo.data.User;
import com.demo.data.UserRepository;

@Service
public class UserServiceImpl implements UserService 
    @Autowired
    UserRepository userRepository;

    public User findUserById(Integer id) 
        return userRepository.findOne(id);
    

网页控制器:com.demo.web.UserController

package com.demo.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo.svc.UserService;

@Controller
public class UserController 
    @Autowired
    UserService svc;

    @RequestMapping("/")
    @ResponseBody
    public String test() 
        return svc.findUserById(1).getName();
    

【讨论】:

嗨@JM Yang,请按照您的示例进行操作,但是当我启动应用程序时,出现以下错误:org.springframework.beans.factory.BeanCreationException:创建名为“userRepository”的bean时出错:注入持久性依赖失败;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] ​​你对这个错误有什么想法吗?问候!【参考方案2】:

这是因为您没有在上下文中创建 UserRepository 的 bean。有很多方法可以做到这一点,因为您没有使用 Spring Boot 项目,因此它不会在启动时在容器中创建对象,因为 @Autowired 没有在 UserRepository 类中注入对象。对于此项目,您可以在项目中更新以下内容:

 package com.demo.svc;

 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;

 import com.demo.data.User;
 import com.demo.data.UserRepository;

 @Service
 public class UserServiceImpl implements UserService 

 UserRepository userRepository;

 public User findUserById(Integer id) 
     return userRepository.findOne(id);
 

  public UserRepository setRepo(UserRepository repo)
  
    userRepository=repo;
  


此外,您还需要从容器中注入对象。 在 src/main/webapp/WEB-INF/spring/context.xml

<bean id="repo" class="com.demo.data.UserRepository"></bean>

<!--Setting the object ref in com.demo.svc.UserServiceImpl-->

<bean id="userserviceImpl" class="com.demo.svc.UserServiceImpl">
 <property name="userRepository" ref="repo"></property>
 </bean>

希望对你有帮助

【讨论】:

他不必指定 bean - 它被组件扫描检测到:&lt;jpa:repositories base-package="com.demo.data" /&gt;

以上是关于大家有没有遇到使用spring data jpa hibernate无法自动写入时间戳的问题?的主要内容,如果未能解决你的问题,请参考以下文章

使用 spring data jpa 更新单个字段

在 Spring 3.1.0 中使用 Spring Data JPA

TransactionRequiredException:Spring Data JPA 没有正在进行的事务

Spring Boot + Spring Data JPA + PostgreSQL

spring-data-jpa 存储库在 Query 中使用 Collection 作为 @Param

Spring Data Jpa Repository 未将实体保存到数据库