gpt4 book ai didi

java - 数据在数据库 jpa/hibernate 中插入两次

转载 作者:行者123 更新时间:2023-11-30 08:47:38 25 4
gpt4 key购买 nike

无法找到使用 Spring 数据、JPA、hibernate 和 mySQL 向 mySQL 数据库中插入数据的错误。它在数据库中插入数据两次。

root-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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

<!-- Root Context: defines shared resources visible to all other web components -->
<context:component-scan base-package="com.project.db">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>

<jdbc:embedded-database type="HSQL" id="dataSource"/>

<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/jpa"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean> -->

<!-- <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean> -->

<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="packagesToScan" value="com.project.db.entity"></property>
<property name="dataSource" ref="dataSource"></property>
<!-- <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/> -->
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
</property>
</bean>

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

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

<jpa:repositories base-package="com.project.db.repository"/>
</beans>

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">

<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>

<context:component-scan base-package="com.project.db" />

</beans:beans>

我的@Entity 类是:

@Entity
public class User {

@Id
@GeneratedValue
private Integer id ;

private String name ;

public Integer getId() {
return id;
}

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

public String getName() {
return name;
}

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

}

JPA 存储库是:

import org.springframework.data.jpa.repository.JpaRepository;

import com.project.entity.User;

public interface UserRepository extends JpaRepository<User, Integer> {

}

最后,@Service 类是:

import javax.annotation.PostConstruct;
import javax.transaction.Transactional;

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

import com.project.entity.User;
import com.project.repository.UserRepository;

@Transactional
@Service
public class InitDbService {

@Autowired
private UserRepository userRepository;

@PostConstruct
public void init() {
User user = new User();
user.setName("Ali");
userRepository.save(user);
}
}

上面的代码没有错误/异常;还创建了数据库/表,但是当我在 mySQL 数据库中看到数据时,数据被插入到实体/表中两次。项目在 github .

控制台输出为:

INFO: Spring WebApplicationInitializers detected on classpath: [com.project.db.WebAppInitializer@1867584]
Sep 2, 2015 12:50:17 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Wed Sep 02 12:50:17 PKT 2015]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/root-context.xml]
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Hibernate: drop table if exists users
Hibernate: create table users (id integer not null auto_increment, name varchar(255), primary key (id))
Hibernate: insert into users (name) values (?) // first time inserting here and
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 5633 ms
Sep 2, 2015 12:50:23 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'springDispatcher'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'springDispatcher': initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'springDispatcher-servlet': startup date [Wed Sep 02 12:50:23 PKT 2015]; parent: Root WebApplicationContext
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.project.db.HomeController.home(java.util.Locale,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: WebApplicationContext for namespace 'springDispatcher-servlet': startup date [Wed Sep 02 12:50:23 PKT 2015]; parent: Root WebApplicationContext
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: WebApplicationContext for namespace 'springDispatcher-servlet': startup date [Wed Sep 02 12:50:23 PKT 2015]; parent: Root WebApplicationContext
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
Hibernate: insert into users (name) values (?) // Second time inserting here
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'springDispatcher': initialization completed in 1483 ms
Sep 2, 2015 12:50:25 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/db] is completed

最佳答案

在这里碰碰运气,因为我看到您正在使用 Spring MVC。

使用 Spring MVC,您有一个定义 Controller 的 servlet 上下文,以及一个用于其他 bean 的 applicationContext。可能是您正在扫描 servlet 上下文中除 Controller 之外的 bean,这反过来会给您两个 InitDbService bean,它们都运行它们的 @PostConstruct-method,插入到数据库中。

这可以通过像这样定义组件扫描来解决:

servlet-context(将controller和controller only放在单独的包中之后):

<context:component-scan base-package="com.my.project.controller" />

应用上下文:

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

关于java - 数据在数据库 jpa/hibernate 中插入两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32356344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com