Andreas_G 2021-11-12 17:38 采纳率: 100%
浏览 55
已结题

SSH报错找不到实体类

刚接触Hibernate,公司带我的人说需要做一个登录注册给他。
具体情况,执行到Dao里的save时候会报错,然后不会写入数据库。
报错提示
org.hibernate.MappingException: Unknown entity: com.andreas.entity.User

img

save位置

img

数据库
数据库用的MySQL8.0.11
数据库账号密码是对的,root和123
库名

img

表结构

img

已经在sessionFactory里引了实体类包

img


以下是代码

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"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:applicationContext.xml
        </param-value>
    </context-param>

    <!-- spring MVC config -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- hibernateFilter -->
    <filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>hibernateFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!-- Spring监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--  字符集过滤  -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

applicationContext


<?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:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:jee="http://www.springframework.org/schema/jee" 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-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
       default-lazy-init="true">

    <description>Spring公共配置</description>

    <!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
    <context:component-scan base-package="com.andreas">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    <context:component-scan base-package="com.andreas">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="namingStrategy">
            <bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.cache.provider_class">
                    org.hibernate.cache.EhCacheProvider
                </prop>
                <prop key="net.sf.ehcache.configurationResourceName">ehcache/ehcache-hibernate-local.xml</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
            </props>
        </property>
<!--            <property name="packagesToScan" value="com.andreas.entity" />-->

        <property name="packagesToScan">
            <list>
                <value>com.andreas.entity</value>
            </list>
        </property>
    </bean>

    <!-- Hibernate 事务配置 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!-- 使用annotation定义事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

    <context:property-placeholder ignore-unresolvable="true"/>

    <!-- 数据源配置, 使用DBCP数据库连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <!-- Connection Info -->
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/logindemo?useUnicode=true&amp;characterEncoding=utf-8" />
        <property name="username" value="root" />
        <property name="password" value="123" />

        <!-- Connection Pooling Info -->
        <property name="maxActive" value="500" />
        <property name="maxIdle" value="30" />
        <property name="maxWait" value="10000" />
        <property name="removeAbandoned" value="true" />
        <property name="removeAbandonedTimeout" value="60" />
        <property name="logAbandoned" value="true" />
        <property name="validationQuery" value="select 1 from dual  " />
        <property name="testOnBorrow" value="true" />
        <property name="defaultAutoCommit" value="false" />
        <!-- 连接Idle一个小时后超时 -->
        <property name="timeBetweenEvictionRunsMillis" value="3600000" />
        <property name="minEvictableIdleTimeMillis" value="3600000" />
    </bean>
</beans>

hibernate.cof


<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration
        PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory >
        <!--JDBC驱动程序-->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <!-- 连接数据库的URL-->
        <property name="connection.url">
            jdbc:mysql://127.0.0.1:3306/logindemo?useUnicode=true&amp;characterEncoding=utf-8
        </property>
        <property name="connection.useUnicode">true</property>
        <property name="connection.characterEncoding">UTF-8</property>
        <!--连接的登录名-->
        <property name="connection.username">root</property>
        <!--登录密码-->
        <property name="connection.password">123</property>

        <!-- C3P0连接池设定-->
        <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider
        </property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.timeout">120</property>
        <property name="hibernate.c3p0.max_statements">100</property>
        <property name="hibernate.c3p0.idle_test_period">120</property>
        <property name="hibernate.c3p0.acquire_increment">2</property>
        <!--是否将运行期生成的SQL输出到日志以供调试-->
        <property name="show_sql">false</property>
        <!--指定连接的语言-->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.autocommit">true</property>

    </session-factory>
</hibernate-configuration>

spring-mvc


<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/aop
 http://www.springframework.org/schema/aop/spring-aop.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!--开启SpringMVC注解的支持-->
    <mvc:annotation-driven/>

    <!--定义Controller扫描包-->
    <context:component-scan base-package="com.andreas"/>
    <!--打开静态资源设置规则-->
    <mvc:default-servlet-handler/>
    <!--配置视图解析器-->
    <bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

UserDaoImpl


package com.andreas.dao.impl;

import com.andreas.dao.UserDao;
import com.andreas.entity.User;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.stereotype.Repository;


@Repository
public class UserDaoImpl implements UserDao {
//----------------------------------------------------------------------------------
//    //通过sessionfactoryUtil创建session
//    org.hibernate.Session session = SessionUtil.getSession();
//----------------------------------------------------------------------------------
    public boolean useRegist(User user) {

//----------------------------------------------------------------------------------
        //创建Configuration文件,以拿到hibernate配置
        Configuration configure = new Configuration().configure();
        System.out.println("This is configure-----"+configure);
        //获取SessionFactory
        SessionFactory sessionFactory = configure.buildSessionFactory();
        System.out.println("This is sessionFactory-----"+sessionFactory);
        //获取session
        Session session = sessionFactory.openSession();
        System.out.println("This is session-----"+session);
//------------------------------------------------------------------------------------

        //写入user数据
        try {
            session.save(user);
            session.beginTransaction().commit();
            session.close();
            return true;
        } catch (HibernateException e) {
            System.out.println(e);
            session.close();
            return false;
        }
    }

    public User userLongin(User user) {
//        String hql = "from User where username = ? and password= ?";
//        Query query = session.createQuery(hql);
//                User searchUser = new User();
//        query.setString(0, user.getUsername());
//        query.setString(1, user.getPassword());
//        List<Object[]> links = query.list();
//        for(Object[] link : links){
//            String userid = link[0];
//            String username = link[1];
//            String password = link[2];
//        }
//        searchUser.setUserid(query.);
//        searchUser.setUsername();
//        searchUser.setPassword();
        return null;
    }
}

Entity


package com.andreas.entity;

import javax.persistence.*;

@Entity
//@JsonAutoDetect
@Table(name = "user")
public class User implements java.io.Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "user_id", unique = true, nullable = false)
    private Integer userid;
    @Column(name = "user_name")
    private String username;
    @Column(name = "password")
    private String password;

    /**
     * 用户映射类
     * @param userid 用户id
     * @param username 用户名,作为唯一登录凭证
     * @param password 明文密码
     * @param email 邮箱
     */
    public User(int userid, String username, String password, String email) {
        this.userid = userid;
        this.username = username;
        this.password = password;
    }

    public User() {
    }

    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


    @Override
    public String toString() {
        return "User{" +
                "userid=" + userid +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

结构图

img

实在没办法了,我看了网上很多解决办法要么是entity包没有引入sessionFictory或者就是Hibernate4需要注册一个ServiceRegistryBuilder 但是好像都没有用,怎么办啊。

  • 写回答

2条回答 默认 最新

  • _Onelone丶 2021-11-12 17:56
    关注

    你的User实体导错包了吧,你User包应该是你的实体那个,你看一下你class头部import那个User是不是你想要的

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 12月9日
  • 已采纳回答 12月1日
  • 创建了问题 11月12日

悬赏问题

  • ¥15 加氢站氢负荷数据集来源
  • ¥15 umi接入sentry遇到问题
  • ¥15 HBuilderX打包H5网页,扫码模块无法使用
  • ¥15 Javascript跳转页面后,无法执行后面代码,如何解决?
  • ¥15 echarts绘制图表
  • ¥15 请教两个关于高德地图定位不准的技术问题
  • ¥15 根据企业名称 对照两个文件 样本筛选/匹配
  • ¥15 Linux环境下CA证书更新问题
  • ¥15 sqlserver语句提取结果以外数据
  • ¥60 微信小程序如何上传QQ聊天文件