java - Spring MVC intègre l'erreur d'accès hibernate5 Impossible de localiser la ressource cfg.xml
为情所困
为情所困 2017-05-17 10:03:38
0
2
2065

Spring MVC intègre le framework Hibernate5 : la connexion à la base de données et d'autres informations ont été configurées dans le fichier dispatcher-servlet.xml. J'ai écrit une fonction simple pour créer une nouvelle table de données (juste quelques fichiers) aucune erreur n'a été signalée lors de l'exécution. , mais l'erreur HTTP Status 500 org a été signalée lors de l'accès à hibernate.internal.util.config.ConfigurationException : impossible de localiser la ressource cfg.xml [hibernate.cfg.xml], mais il est étrange que la table de données ait été créée avec succès mais non. les données ont été écrites.
Ce que je me demande, c'est que sessionFactoryBean sera utilisé à la place du fichier hibernate.cfg.xml après hibernate4. Je n'ai pas créé le fichier hibernate.cfg.xml. Certains fichiers spécifiques et captures d'écran d'erreur sont les suivants

fichier dispatcher-servlet.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"
       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">

    <!-- 扫描使用注解的类所在包 -->
    <context:component-scan base-package="com.hiber.*"/>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/hiber?useUnicode=yes&amp;characterEncoding=UTF-8" />
        <property name="username" value="root" />
        <property name="password" value="3443"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 找到实体包(pojo) -->
        <property name="packagesToScan" value="com.hiber.*" />
        <property name="hibernateProperties">
            <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL57Dialect</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
            <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 找到实体包(pojo) -->
        <property name="packagesToScan" value="com.hiber.*" />
        <!--指定jpa适配器-->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <!--<!&ndash;指定jpa属性&ndash;>-->
        <!--<property name="jpaProperties">-->
            <!--<props>-->
                <!--<prop key="hibernate.dialect">org.hibernate.dialect.MySQL57Dialect</prop>-->
                <!--<prop key="hibernate.hbm2ddl.auto">create</prop>-->
                <!--<prop key="hibernate.show_sql">true</prop>-->
            <!--</props>-->
        <!--</property>-->
    </bean>

    <!-- 配置hibernate事务管理器 -->
    <bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:annotation-driven />
</beans>

Fichier Message.java

package com.hiber.entity;

import javax.persistence.*;

@Entity
public class Message{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    int id;
    @Column(nullable = false)
    String text;

    public Message(String text) {
        setText(text);
    }
    public Message(){}

    public int getId() {
        return id;
    }

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

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

Fichier IndexController.java

package com.hiber.controllers;

import com.hiber.entity.Message;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class IndexController {
    @RequestMapping(value = "/persist")
    public String saveMessage(){
        Message message = new Message("Hello, world");
        StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure()
                .build();
        SessionFactory sessionFactory =  new MetadataSources(registry).buildMetadata().buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.persist(message);
        tx.commit();
        return "数据添加成功!";
    }
}

Capture d'écran d'erreur du navigateur

Capture d'écran de la création réussie d'une table de données

Structure du projet

S'il vous plaît, aidez-nous à découvrir quel est le problème. Merci d'avance !

为情所困
为情所困

répondre à tous(2)
黄舟

Hibernate version 5.2 ou supérieure est écrit comme ceci :

Message message = new Message("Hello,world!");
        Configuration configuration = new Configuration();
        StandardServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.persist(message);
        tx.commit();
        return "数据添加成功!";

org.hibernate.internal.util.config.ConfigurationException : impossible de localiser la ressource cfg.xml [hibernate.cfg.xml] Le problème a été résolu, mais org.hibernate.service.spi.ServiceException : impossible de créer le service demandé est réapparu [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment], aidez aussi !

PHPzhong

Voir la configuration web.xml, comme suit :

<!-- 加载Spring -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- spring默认的配置文件名称是:applicationContext.xml,如果是默认则不需要配置 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml,
        /WEB-INF/daoContext.xml</param-value>
</context-param>

La source de données, sessionFactory, le gestionnaire de transactions et la transaction sont configurés dans daoContext.xml
Les ajoutez-vous ? Voyez s'il y a une erreur

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!