java.lang.NoSuchMethodError;Unable to perform unmarshalling at line n;java.lang.AbstractMethodError

 

public void init(){
        //加载hibernate.cfg.xml
        final StandardServiceRegistry registry=new StandardServiceRegistryBuilder().configure().build();
        try {
            // 根据hibernate.cfg.xml配置,初始化sessionFactory
            sessionFactory=new MetadataSources(registry).buildMetadata().buildSessionFactory();
            // 创建session
            session=sessionFactory.openSession();
            // 通过session开始事务
            transaction=session.beginTransaction();
        } catch (Exception e) {
            StandardServiceRegistryBuilder.destroy(registry);
        }    
    }

这是hibernate-core-5.2.6Final.jar包书上对应给出的初始化代码,我运行书上给的程序没有问题,但自己代码因为多了

HibernateUtil的配置,里面用的是ServiceRegistryBuilder,对应的是hibernate-core-4.x.xFinal.jar包,

错误里面显示了58行的StandardServiceRegistryBuilder

所以我决定统一成ServiceRegistryBuilder,

@Before
    public void init(){
        //加载hibernate.cfg.xml
        final ServiceRegistry registry=new ServiceRegistryBuilder().configure().buildServiceRegistry();
        try {
            // 根据hibernate.cfg.xml配置,初始化sessionFactory
            sessionFactory=new MetadataSources(registry).buildMetadata().buildSessionFactory();
            // 创建session
            session=sessionFactory.openSession();
            // 通过session开始事务
            transaction=session.beginTransaction();
        } catch (Exception e) {
            ServiceRegistryBuilder.destroy(registry);
        }    
    }

org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 4 and column 1 in RESOURCE hibernate.cfg.xml. Message: cvc-elt.1: 找不到元素 'hibernate-configuration' 的声明。

我一直以为是自己hibernate.cfg.xml的配置错误,但我检查了很多遍,不应该啊,都是有相关代码参考的

到最后,终于开窍了,到网上直接找Hibernate测试类的完整代码,果然有不一样的版本,呜呜呜!!

 @Before
        public void init(){
            // 创建配置对象  
            Configuration config = new Configuration().configure();
         
            // 创建服务注册对象
            ServiceRegistry serviceRegistery = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
            // 创建会话工厂对象
            sessionFactory = config.buildSessionFactory(serviceRegistery);
            // 创建会话对象
            session = sessionFactory.openSession();
            // 开启事务
            transaction = session.beginTransaction();
        }


  
最终运行成功!!!

这只是我遇到关于这份代码的一小部分问题,题目字数有限,前期主要是根据错误提示去找具体的包,有些包因为版本问题所以总是莫名奇妙报错,网上对于这类问题解答很少,所以自己要学会根据提示找到包的错误;

另外,一般mysql的jar包达到5.1以上的基本就跟mysql没关系了,我试了几次,哎

这次教训还是很深刻的,一直都在不停更新bug,想法不够全面,要是早知道直接多去看看别人的测试类怎么配置的,这类代码都是现成的,多看看就行了

下面附上完整代码,希望大家少走弯路,我感觉基本关于JUnit问题这样配置一般没问题:

测试类:
 

package hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import model.User;
//测试类
public class HibernateTest {
        
        private SessionFactory sessionFactory;
        private Session session;
        private Transaction transaction;
        @Before
        public void init(){
            // 创建配置对象  
            Configuration config = new Configuration().configure();
         
            // 创建服务注册对象
            ServiceRegistry serviceRegistery = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
            // 创建会话工厂对象
            sessionFactory = config.buildSessionFactory(serviceRegistery);
            // 创建会话对象
            session = sessionFactory.openSession();
            // 开启事务
            transaction = session.beginTransaction();
        }
        
        @After
        public void destory(){
            // 提交事务
            transaction.commit();
            // 关闭会话
            session.close();
            // 关闭会话工厂
            sessionFactory.close();
        }
        


    //添加数据
    @Test
    public void testSaveUser(){
        User user=new User("hiberUser2","123456","用户");
        session.save(user);

    }
    @Test
    public void testGetUser(){
        //从数据表users中加载编号Id为1的用户对象
        User user=(User)session.get(User.class,1);
        // 在控制台输出用户对象信息
        System.out.println(user.toString());
    }

    @Test
    public void testLoadUser(){
        try {
            //从数据表users中加载编号Id为2的用户对象
            User user=(User)session.load(User.class,2);
            // 在控制台输出用户对象信息
            System.out.println(user.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Test
    public void testDeleteUser(){
        // 从数据表users中加载编号id为3的用户对象
        User user=(User)session.get(User.class, 4);
        // 删除对象 
        session.delete(user);
    }
    
    @Test
    public void testUpdateUser(){
        // 从数据表users中加载编号id为2的用户对象
        User user=(User)session.get(User.class, 10);
        // 修改数据
        user.setUsername("zhang");
        user.setPassword("123");
        // 更新对象
        session.update(user);
        
    }
    
}

hibernate.cfg.xml配置:

<!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>
		<!-- Hibernate连接的信息 -->
		<property name="connection.username">root</property>
		<property name="connection.password">111</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql:///sim</property>
		<!-- Hibernate方言 -->
		<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
		<!-- 是否打印SQL -->
		<property name="show_sql">true</property>
		<!-- 关联Hibernate的映射文件 ,引入其他子配置文件-->
		<mapping resource="model/User.hbm.xml"/>
		
	</session-factory>
</hibernate-configuration>

HibernateUtil.java 

package hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static SessionFactory sessionFactory = null; // SessionFactory对象
	// 静态块
	static {
		try {
			Configuration cfg = new Configuration().configure(); // 加载Hibernate配置文件
			sessionFactory = cfg
					.buildSessionFactory(new ServiceRegistryBuilder().applySettings(cfg.getProperties())
							.buildServiceRegistry());
		} catch (Exception e) {
			System.err.println("创建会话工厂失败");
			e.printStackTrace();
		}
	}

	/**
	 * 获取Session
	 * 
	 * @return Session
	 * @throws HibernateException
	 */
	public static Session getSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}
		return session;
	}

	/**
	 * 重建会话工厂
	 */
	public static void rebuildSessionFactory() {
		try {
			Configuration cfg = new Configuration().configure(); // 加载Hibernate配置文件
			sessionFactory = cfg
					.buildSessionFactory(new ServiceRegistryBuilder().applySettings(cfg.getProperties())
							.buildServiceRegistry());
		} catch (Exception e) {
			System.err.println("创建会话工厂失败");
			e.printStackTrace();
		}
	}

	/**
	 * 获取SessionFactory对象
	 * 
	 * @return SessionFactory对象
	 */
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * 关闭Session
	 * 
	 * @throws HibernateException
	 */
	public static void closeSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);
		if (session != null) {
			session.close(); // 关闭Session
		}
	}
}

还有lib包,气死人。。

antlr-2.7.7.jar
c3p0-0.9.1.jar
cdi-api-1.1.jar
classmate-1.3.0.jar
dom4j-1.6.1.jar
ehcache-core-2.4.3.jar
el-api-2.2.jar
geronimo-jta_1.1_spec-1.1.1.jar
hibernate-c3p0-4.1.8.Final.jar
hibernate-commons-annotations-5.0.1.Final.jar
hibernate-core-4.1.8.Final.jar
hibernate-core-5.2.6.Final.jar
hibernate-ehcache-4.1.8.Final.jar
hibernate-entitymanager-4.1.8.Final.jar
hibernate-envers-4.1.8.Final.jar
hibernate-infinispan-4.1.8.Final-tests.jar
hibernate-infinispan-4.1.8.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
hibernate-proxool-4.1.8.Final.jar
infinispan-core-5.2.0.Beta3.jar
jandex-2.0.3.Final.jar
javassist-3.20.0-GA.jar
javax.inject-1.jar
jboss-interceptors-api_1.1_spec-1.0.0.Beta1.jar
jboss-logging-3.3.0.Final.jar
jboss-marshalling-1.3.15.GA.jar
jboss-marshalling-river-1.3.15.GA.jar
jboss-transaction-api_1.1_spec-1.0.0.Final.jar
jgroups-3.2.0.CR1.jar
jsr250-api-1.0.jar
mysql-connector-java-5.1.39-bin.jar
proxool-0.8.3.jar
rhq-pluginAnnotations-3.0.4.jar
slf4j-api-1.6.1.jar
stax2-api-3.1.1.jar
staxmapper-1.1.0.Final.jar
woodstox-core-asl-4.1.1.jar

链接:https://pan.baidu.com/s/1vhjFpPZKInOVxzmLOFU_-A
提取码:r0sr 

少敲代码多睡觉!!!!!
 

    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值