Eclipse上使用Hibernate5.0及以上版本编写第一个HelloWorld程序
这个贴子是为了帮助初学者解决使用Eclipse并使用Hibernate5.0及以上版本(我用的是 hibernate-release-5.1.0-Final)创建第一个Hibernate HelloWorld程序时,junit4测试时出现各种问题。
未知实体类(- org.hibernate.MappingException: Unknown entity),
找不到cfg.xml包(org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource)
的解决办法。
我的环境:
Eclipse Java EE IDE for Web Developers.Version: Mars.2 Release (4.5.2)
jdk1.8.0_92
hibernate-release-5.1.0-Final
JBoss Tools 4.3.1 Final
1、当爆出:未知实体类(- org.hibernate.MappingException: Unknown entity)错误时,原因是:
Hibernate5.0及以上版本,与4.x以往版本不同的,最关键的代码——获得SessionFactory的方式不同
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
// 5.0及以上版本——不用通过ServiceRegistry
Configuration configuration = new Configuration().configure();
sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
// 4.x版本——需要通过ServiceRegistry
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = config.buildSessionFactory(serviceRegistry);
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
还有一个找不到类的原因: 在cfg.xml配置文件中<mapping class="" />映射没有配置正确
(1)、可以通过持久化类来配置



(2)、 可以通过.hbm.xml来配置


(3)、当然你也可以两个都加上去

------------------------------------------------------------------------------------------————----------------------------
2、当爆出:找不到cfg.xml包(org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource)错误时,原因是: cfg.xml文件放置的位置不对
你需要把.cfg.xml文件放在src中的一个Source Floder下如下图

原因在于,sessionFactory = new Configuration().configure().buildSessionFactory(); 这一段代码中获取cfg.xml文件的默认位置就是在src目录下。.
(configure()中是可以填写一个URL参数的,但是我不会写,还有,我把cfg.xml文件直接放在src目录下,有的时候可以正常运行,有的时候又说找不到cfg.xml文件。希望高手来解决这个问题,感谢!。)
贴出我的HelloWorld程序所有代码
Students
package config;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity(name="Students")
public class Students implements Serializable{
private static final long serialVersionUID = 1L;
@Id
private int sid; // 学号
private String sname; // 姓名
private String gender; // 性别
private Date brithday; // 出生日期
private String address; // 住址
public Students(){}
public Students(int sid, String sname, String gender, Date brithday, String address) {
super();
this.sid = sid;
this.sname = sname;
this.gender = gender;
this.brithday = brithday;
this.address = address;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBrithday() {
return brithday;
}
public void setBrithday(Date brithday) {
this.brithday = brithday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Students [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", brithday=" + brithday
+ ", address=" + address + "]";
};
}
TestStudents
public class TestStudents {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Before
public void init() {
// 获得 session工厂
sessionFactory = new Configuration().configure().buildSessionFactory();
// 获得 session
session = sessionFactory.getCurrentSession();
// 开启事务
transaction = session.beginTransaction();
}
@After
public void destory() {
transaction.commit(); // 提交事务
}
@Test
public void testSaveStudents() {
// 生成学生对象
Students students = new Students(2, "黄蓉", "女", new Date(), "桃花岛");
System.out.println(students.getSname() + students.getGender() + students.getAddress());
session.save(students); // 保存对象进入数据库
}
}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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">xxxxxx</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="config.Students"/>
<mapping resource="config/Students.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Students.hbm.xml
<?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 May 22, 2016 11:40:35 PM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="config.Students" table="STUDENTS">
<id name="sid" type="int">
<column name="SID" />
<generator class="assigned" />
</id>
<property name="sname" type="java.lang.String">
<column name="SNAME" />
</property>
<property name="gender" type="java.lang.String">
<column name="GENDER" />
</property>
<property name="brithday" type="java.util.Date">
<column name="BRITHDAY" />
</property>
<property name="address" type="java.lang.String">
<column name="ADDRESS" />
</property>
</class>
</hibernate-mapping>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
最后的最后,要特别感谢这几个网址中的朋友。正是看到了这些提问与回答,才解决了我这弄了整整两天的问题。
http://tieba.baidu.com/p/4350852805
http://stackoverflow.com/questions/32405031/hibernate-5-org-hibernate-mappingexception-unknown-entity
http://www.coderanch.com/t/215954/ORM/databases/hibernate-cfg-xml
...全文
相关推荐
eclipse搭建SSH框架详解
**Eclipse IDE**: 建议使用Java EE版本的Eclipse,该版本内置了对Web项目的支持,便于后续的开发工作。
配置flex+bleazeds+spring+hibernate框架
HelloWorld示例**- 使用Hibernate创建数据表,如上述的`food`表。- 创建Flex客户端,使用BlazeDS连接到Spring和Hibernate服务,展示数据。
Struts2学习笔记(一) 环境的搭建与HelloWorld程序
**Integrated Development Environment (IDE)**:虽然不是必需的,但使用IDE如Eclipse、IntelliJ IDEA或NetBeans可以提高开发效率。
MyEclipse_6_开发实战教程.doc
总结,本教程通过下载安装MyEclipse 6.0,创建并运行HelloWorld项目,以及配置和使用MySQL数据库,引导读者了解MyEclipse的基本使用和JDBC操作。
第一个struts2 程序
在开始编写第一个Struts2程序之前,确保你已经安装了Java Development Kit (JDK) 和 Apache Tomcat 服务器。


