wuruiaoxue
武睿傲雪
2016-07-19 20:40

使用JAX-RS框架搭建WebService使用Hibernate访问MySQL出现不能实例化类问题

50

问题描述:大体思路是这样,我最近在做IOS开发想通过WebService访问服务器端数据库的数据,所以想使用Java搭建一个WebService于是在网上找资料使用Java实现的框架JAX-RS.代码如下:

com.hnu.hibernate.bean包下的Student.java类

package com.hnu.hibernate.bean;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.OneToMany;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@Entity
@Table(name="student")
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer userid;

@Column(name="username")
private String username;

@Column(name="password")
private String password;

@Column(name="realname")
private String realname;

@Column(name="age")
private Integer age;

@Column(name="nationality")
private String nationality;

@Column(name="language")
private String language;

@Column(name="year")
private float year;

@Column(name="studyabroadschool")
private String studyabroadschool;

public Integer getUserid() {
return userid;
}

public void setUserid(Integer 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;
}

public String getRealname() {
return realname;
}

public void setRealname(String realname) {
this.realname = realname;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public String getNationality() {
return nationality;
}

public void setNationality(String nationality) {
this.nationality = nationality;
}

public String getLanguage() {
return language;
}

public void setLanguage(String language) {
this.language = language;
}

public float getYear() {
return year;
}

public void setYear(float year) {
this.year = year;
}

public String getStudyabroadschool() {
return studyabroadschool;
}

public void setStudyabroadschool(String studyabroadschool) {
this.studyabroadschool = studyabroadschool;
}
}

com.hnu.hibernate.dao包

package com.hnu.hibernate.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;

import com.hnu.hibernate.util.HibernateSessionFactory;
import com.hnu.hibernate.util.HibernateUtil;
public class BaseDAO {
/**
* 插入数据
*
* @param object
*/
public int create(T object) {

    Session session = HibernateSessionFactory.getSession();

    try {
        session.beginTransaction();

        session.persist(object);

        session.getTransaction().commit();

    } catch (Exception e) {
        session.getTransaction().rollback();
        return 0;
    } finally {
        session.close();
    }
    return 1;
}

/**
 * 更新数据库
 * 
 * @param object
 */
public int update(T object) {

    Session session = HibernateSessionFactory.getSession();
    try {
        session.beginTransaction();
        session.update(object);
        session.getTransaction().commit();
    } catch (Exception e) {
        session.getTransaction().rollback();
        return 0;
    } finally {
        session.close();
    }
    return 1;
}

/**
 * 从数据库中删除
 * 
 * @param object
 */
public int delete(T object) {

    Session session = HibernateSessionFactory.getSession();

    try {
        session.beginTransaction();
        session.delete(object);
        session.getTransaction().commit();
    } catch (Exception e) {
        session.getTransaction().rollback();
        return 0;
    } finally {
        session.close();
    }
    return 1;
}

/**
 * 查找单个Entity Bean
 * 
 * @param clazz
 * @param id
 * @return
 */
@SuppressWarnings("unchecked")
public T find(Class<? extends T> clazz, Serializable id) {

    Session session = HibernateSessionFactory.getSession();
    try {
        session.beginTransaction();
        return (T) session.get(clazz, id);
    } finally {
        session.getTransaction().commit();
        session.close();
    }
}

/**
 * 查找多个Entity Bean
 * 
 * @param hql
 * @return
 */
@SuppressWarnings("unchecked")
public List<T> list(String hql) {

    Session session =HibernateSessionFactory.getSession();
    try {
        session.beginTransaction();
        return session.createQuery(hql).list();
    } finally {
        session.getTransaction().commit();
        session.close();
    }
}

}

com.hnu.hibernate.bean包下生成的WebService Javabean StudentsResource.java类

package com.hnu.hibernate.bean;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import com.hnu.hibernate.dao.BaseDAO;

@Produces("application/xml")
@Path("students")
public class StudentsResource {
private BaseDAO baseDAO=new BaseDAO();
@GET
public List getStudents() {
return baseDAO.list("from Student");
}
}

com.hnu.hibernate.util包下Hibernate获取Session的类 HibernateSessionFactory.java类

package com.hnu.hibernate.util;

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

/**

  • Configures and provides access to Hibernate sessions, tied to the
  • current thread of execution. Follows the Thread Local Session
  • pattern, see {@link http://hibernate.org/42.html }.
    */
    public class HibernateSessionFactory {

    /**

    • Location of hibernate.cfg.xml file.
    • Location should be on the classpath as Hibernate uses
    • #resourceAsStream style lookup for its configuration file.
    • The default classpath location of the hibernate config file is
    • in the default package. Use #setConfigFile() to update
    • the location of the configuration file for the current session.
      */ private static final ThreadLocal threadLocal = new ThreadLocal(); private static org.hibernate.SessionFactory sessionFactory;

    private static Configuration configuration = new Configuration();
    private static ServiceRegistry serviceRegistry;

    static {
    try {
    configuration.configure();
    serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    } catch (Exception e) {
    System.err.println("%%%% Error Creating SessionFactory %%%%");
    e.printStackTrace();
    }
    }
    private HibernateSessionFactory() {
    }

    /**

    • Returns the ThreadLocal Session instance. Lazy initialize
    • the SessionFactory if needed. *
    • @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;
      }

    /**

    • Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } }

    /**

    • Close the single hibernate session instance. *
    • @throws HibernateException
      */
      public static void closeSession() throws HibernateException {
      Session session = (Session) threadLocal.get();
      threadLocal.set(null);

      if (session != null) {
      session.close();
      }
      }

    /**

    • return session factory * / public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /*
    • return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; }

}

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">

<session-factory>
    <property name="hbm2ddl.auto">update</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/vocabularyadaptivetestingsystem?characterEncoding=UTF-8</property>
    <property name="connection.username">root</property>
    <property name="connection.password">123</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="show_sql">true</property>

    <property name="current_session_context_class">thread</property>
    <mapping class="com.hnu.hibernate.bean.Student"/>
</session-factory>

使用本地的ApplicationServer使用Hibernate访问数据库没有任何问题。但是一旦把访问Hibernate的方法部署到Tomcat服务器上,访问WebService方法没有问题,但是使用WebService调用如下代码:baseDAO.list("from Student");

就出现了如图所示的错误:
图片说明
希望各位高手帮忙看一下,搞了好久没搞出来,重分酬谢!

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答