hibernate+junit测试实体类生成数据库表

今天在使用hibernate注解方式标明的实体类时产生数据库表示遇到了一些问题,经过搜集一些资料,最后总结了一下,如下所示:

先把我的整体的几个文件的代码贴出来吧

这是hibernate.cfg.xml文件






	
		com.mysql.jdbc.Driver
		jdbc:mysql://localhost:3306/phn_dsjava
		root
		123456
		org.hibernate.dialect.MySQLDialect
		true
		true
		update

		

	

这是实体类Announces.java

package com.phn.bean;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author phn
 * 
 */
@Entity
@Table(name = "t_announce")
public class Announces {

	private Integer id;
	private String announcement;
	private String title;
	private Date thetime;

	@Id
	@GeneratedValue
	@Column(nullable = false)
	public Integer getId() {
		return this.id;
	}

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

	@Column(length = 20000)
	public String getAnnouncement() {
		return this.announcement;
	}

	public void setAnnouncement(String announcement) {
		this.announcement = announcement;
	}

	@Column(length = 100)
	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Date getThetime() {
		return thetime;
	}

	public void setThetime(Date thetime) {
		this.thetime = thetime;
	}

}
这是测试类HibernateAnnotationTest.java
package com.phn.junitTest;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.junit.Test;

import junit.framework.TestCase;

public class HibernateAnnotationTest extends TestCase {
	@Test
	public void testSQL() {
		AnnotationConfiguration configuration = new AnnotationConfiguration();
		configuration.configure();
		SessionFactory sessionFactory = configuration.buildSessionFactory();
	}
}

下面是大致问题解释-------------------------------------------------------------------------------------------------------------------------------

Hibernate的配置文件hibernate.cfg.xml位于src目录下。在单元测试时,执行下面代码时,会产生异常。

Configuration cfg = new Configuration();
SessionFactory sf = cfg.configure().buildSessionFactory();

异常:
org.hibernate.MappingException: An AnnotationConfiguration instance is required to use
Hibernate配置文件中,若带有,则说明映射类时,采用了Annotation方式。在初始化Configuation时,应使用AnnoationConfiguration,代码如下:
AnnotationConfiguration configuration = new AnnotationConfiguration();
configuration.configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
注意:这里使用的hibernate版本是3.3
版本低一点可能会出现下面图片这个错误,这是因为低版本的hibernate的jar包org.hibernate.engine.query.sql.NativeSQLQueryReturn类缺少,因此将其版本更新一下就行了
hibernate+junit测试实体类生成数据库表_第1张图片

转载于:https://www.cnblogs.com/yannanying/p/4187350.html

你可能感兴趣的:(hibernate+junit测试实体类生成数据库表)