您的位置:首页 > 其它

学习hibernate遇到的问题及解决方案

2017-11-02 19:39 375 查看
使用工具版本:Eclipse Java EE IDE for Web Developers.Version: Neon.3 Release (4.6.3),

hibernate版本:hibernate-release-5.2.12.Final

JUnit4测试单元版本:junit-4.12(由于自4.8版本以后,JUbit4.jar包中并不包含hamcrest-core-1.3.jar和hamcrest-core-1.3-sources.jar这两个包,所以需要单独下载)

MySQL版本:mysql-5.7.17-winx64

问题描述1:org.hibernate.MappingException: Unknown entity: com.wch.fhibernatemodel.vo.Employee

at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:620)

at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1636)
重点是 Unknown entity问题,找不到实体
解决方法:
因为版本问题:Hibernate4版本的SessionFactory实例构建的步骤是这样的(也是很多学习资料的通用范本):
  V4版:
//Configuration就是代表着hibernate的那个xml配置文件对象,如果configure方法中没有参数的话,默认是就是hibernate.cfg.xml。
Configuration conf = new Configuration().configure();
 
//服务注册,这是使用创建者模式,根据配置文件中的配置字段来构建注册服务(这应该是hibernate架构中注册服务的通用流程)。
 
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().
applySettings(conf.getProperties()).build();

//使用实例化好了的注册服务,使用Configuration中的工厂模式实例化了SessionFactory
SessionFactory sf = conf.buildSessionFactory(serviceRegistry);
 
如果你用的是Hibernate4的版本,这样做完全OK的,运行的时候不会报MappingException。
但是如果你使用Hibernate5的版本,就会报错。那么Hibernate5应该怎样构建SessionFactory呢,如下:
 
V5版
 //V5版本直接使用创建者模式构建出了标准服务注册对象
 
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure().build();
 
//这个对象metadata对象应该扮演了一个万金油的角色,使用以上的注册对象作为入参构建这个对象
Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder()
.
applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();
 
//最后由这个metadata使用构建出sessionFactory
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
问题描述2:hibernate不能自动创建数据表,总是报错。
EROOR:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
Table 'portal.hibernate_sequence' doesn't exist
解决方法:首先检查配置文件是否配置如下
自动创建数据表配置为:
<!-- 指定ddl的生成方式 ,根据需要自动创建数据表-->

<property name="hibernate.hbm2ddl.auto">update</property>

如果配置如上描述,则查看自己安装的MySQL数据库的版本,如果是5.0以下,在hibernate.cfg.xml配置的文件中,方言配置应为
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
如果是5.0以上版本的则方言应配置为:
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

希望对初学hibernate的朋友有所帮助。。。
第一个hibernate项目配置文件如下:
hibernate.cfg.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

<!-- 配置数据库连接的URL -->

<property name="hibernate.connection.url">

jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=utf8

</property>

<!-- 配置驱动 -->

<property name="connection.driver_class">com.mysql.jdbc.Driver</property>

<!-- 配置用户名 -->

<property name="connection.username">root</property>

<!-- 用户密码 -->

<property name="connection.password"></property>

<!-- 指定hibernate方言 -->

<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

<property name="show_sql">true</property>

<property name="format_sql">true</property>

<!-- 指定ddl的生成方式 ,根据需要自动创建数据表-->

<property name="hibernate.hbm2ddl.auto">update</property>

<!-- 配置关系映射文件 -->

<mapping resource="com/wch/fhibernatemodel/vo/Employee.hbm.xml"/>

</session-factory>

</hibernate-configuration>

Employee.hbm.xml配置文件:(利用安装的hibernate插件自动生成)
<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!-- Generated 2017-11-1 21:54:30 by Hibernate Tools 3.5.0.Final -->

<hibernate-mapping>

    <class name=
a617
"com.wch.fhibernatemodel.vo.Employee" table="employee">

        <id name="id" type="int">

            <column name="ID" />

            <generator class="assigned" />

        </id>

        <property name="name" type="java.lang.String">

            <column name="NAME" />

        </property>

        <property name="password" type="java.lang.String">

            <column name="PASSWORD" />

        </property>

    </class>

</hibernate-mapping>

Employee实体类:
package com.wch.fhibernatemodel.vo;

public class Employee {
private int id;
private String name;
private String password;

public Employee(){}//无参构造方法

public Employee(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", password=" + password + "]";
}

}

测试类:
package test;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.boot.Metadata;

import org.hibernate.boot.MetadataSources;

import org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl;

import org.hibernate.boot.registry.StandardServiceRegistry;

import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import org.hibernate.cfg.Configuration;

import org.hibernate.service.*;

import org.junit.After;

import org.junit.Before;

import org.junit.Test;

import com.wch.fhibernatemodel.vo.Employee;

/**

 * 

 * @ClassName: UserTest 

 * @类描述: 对User对象的测试

 * @author A18ccms a18ccms_gmail_com 

 * @date 2017年11月1日 下午3:52:43 

 *

 */

public class UserTest {

private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Before
public void init(){
//直接使用创建者模式构建出了标准服务注册对象
StandardServiceRegistry standarServiceRegister=new StandardServiceRegistryBuilder().configure().build();
//这个对象metadata对象应该扮演了一个万金油的角色,使用以上的注册对象作为入参构建这个对象
Metadata metadata = new MetadataSources(standarServiceRegister).getMetadataBuilder().applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();
//由meatadata创建出sessionFactory
sessionFactory = metadata.getSessionFactoryBuilder().build();
//创建会话对象
session = sessionFactory.openSession();
//开启事务
transaction = session.beginTransaction();
}

@Test
public void testUserSave(){

Employee user=new Employee(13,"李立群","123456");
session.save(user);//将user对象存入数据库中

}

@After
public void destory(){
transaction.commit();//提交事务
session.close();//关闭会话
sessionFactory.close();//关闭工厂
}

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: