使用RESTful Jersey框架搭建WebService,Hibernate框架访问数据库,MySQL存储数据

时间:2021-06-11 19:35:24

现在访问服务器数据的方式有很多种,主要有两种一个是通过JDBC连接数据库,访问数据库(直接访问),一种是通过将方法发布成服务通过wsdl或者客户端访问WebService(间接访问).本文就通过一种使用很方便地WebService框架Jersey,使用Hibernate框架访问数据库,Hibernate是轻量级框架,基本不需要写JDBC代码虽然Hibernate最后的实现使用的也是JDBC,SQL语句直接调用提供的方法会自动创建数据表或者更新数据表结构,为快速开发服务提供了方便,使用非常轻便的MySQL数据库存储数据。也在网上找了很多使用访问WebService的比较多但是通过这种方式访问数据库的还是比较少,自己主要在弄IOS,想通过WebService不需要直接连接到MySQL只需要使用连接字符串访问发布的方法。这样只需要在DAO层也就是数据访问层使用调用Webserve方法获得数据。下面有一个创建Jersey的样例,英文版的,也是官方的样例,很实用,特此分享。Jersey创建创建完Jersey只需要将DAO层的代码替换成Hibernate调用代码。下面是项目的一个展示:

使用RESTful Jersey框架搭建WebService,Hibernate框架访问数据库,MySQL存储数据
使用RESTful Jersey框架搭建WebService,Hibernate框架访问数据库,MySQL存储数据
BaseDAO.java代码
package com.hnu.hibernate.dao;

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

import org.hibernate.Session;

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

Session session = HibernateUtil.getSessionFactory().openSession();

try {
session.beginTransaction();

session.persist(object);

session.getTransaction().commit();

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

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

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

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

Session session = HibernateUtil.getSessionFactory().openSession();

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

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

Session session = HibernateUtil.getSessionFactory().openSession();
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 = HibernateUtil.getSessionFactory().openSession();
try {
session.beginTransaction();
return session.createQuery(hql).list();
} finally {
session.getTransaction().commit();
session.close();
}
}
}
HibernateUtil.java类
package com.hnu.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
/**
* Hibernate 初始化配置工具类
* @author waylau.com
* 2014-3-23
*/
public class HibernateUtil {
private static Configuration configuration;
private static SessionFactory sessionFactory;
private static StandardServiceRegistry standardServiceRegistry;
static {
try {
//第一步:读取Hibernate的配置文件 hibernamte.cfg.xml文件
configuration = new Configuration().configure("hibernate.cfg.xml");
//第二步:创建服务注册构建器对象,通过配置对象中加载所有的配置信息
StandardServiceRegistryBuilder sb = new StandardServiceRegistryBuilder();
sb.applySettings(configuration.getProperties());
//创建注册服务
standardServiceRegistry = sb.build();
//第三步:创建会话工厂
sessionFactory = configuration.buildSessionFactory(standardServiceRegistry);
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
hibernate.cfg.xml Hibernate配置文件
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

<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.FifthA"/>
<mapping class="com.hnu.hibernate.bean.FifthB"/>
<mapping class="com.hnu.hibernate.bean.FifthC"/>
<mapping class="com.hnu.hibernate.bean.FirstA"/>
<mapping class="com.hnu.hibernate.bean.FirstB"/>
<mapping class="com.hnu.hibernate.bean.FourthA"/>
<mapping class="com.hnu.hibernate.bean.FourthB"/>
<mapping class="com.hnu.hibernate.bean.FourthC"/>
<mapping class="com.hnu.hibernate.bean.Result"/>
<mapping class="com.hnu.hibernate.bean.SecondA"/>
<mapping class="com.hnu.hibernate.bean.SecondB"/>
<mapping class="com.hnu.hibernate.bean.Student"/>
<mapping class="com.hnu.hibernate.bean.ThirdA"/>
<mapping class="com.hnu.hibernate.bean.ThirdB"/>
</session-factory>

</hibernate-configuration>
本文使用了Annotation方式实现JPA,将JavaBean对象和数据库对象对应起来,下面只列举一个类,其他类都是类似的。
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;
}
}

WebService中的实体类中需要使用
@XmlRootElement
标签,Hibernate需要将Java类和数据库表对应起来。
StudentsResource.java是Student类的WebService类的实现,本文主要使用XML作为输入,XML作为输出,这种方式在网上很少见的,这也是很通用的做法,一般情况,是在连接字符串末尾添加?键值对的方法,XML方式主要讲输入的内容拼接成XML字符串然后将内容添加到Http Body里面传到服务中。 StudentsResource.java类
package com.hnu.hibernate.resources;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import org.hibernate.Session;
import javax.ws.rs.PUT;
import com.hnu.hibernate.dao.BaseDAO;
import com.hnu.hibernate.util.HibernateUtil;
import com.hnu.hibernate.bean.*;

@Consumes("application/xml")
@Path("students")
public class StudentsResource {
private static BaseDAO<Student> baseDAO = new BaseDAO<Student>();
@POST
@Path("create")
@Produces("text/html")
@Consumes("application/xml")
public String create(Student model) {
return String.format("%d", baseDAO.create(model));
}

@POST
@Path("remove")
@Produces("text/html")
@Consumes("application/xml")
public String remove(Student model) {
return String.format("%d", baseDAO.delete(model));
}

@POST
@Path("modify")
@Produces("text/html")
@Consumes("application/xml")
public String modify(Student model) {
return String.format("%d", baseDAO.update(model));
}

@GET
@Path("findAll")
public List<Student> findAll() {
return baseDAO.list(" from Student ");
}

@POST
@Path("findById")
@Consumes("application/xml")
public Student findById(Student model) {
return baseDAO.find(Student.class, model.getUserid());
}

@POST
@Path("findByUseridAndPassword")
@Consumes("application/xml")
@Produces("application/xml")
public Student findByUseridAndPassword(Student model) {
Session session = HibernateUtil.getSessionFactory().openSession();
Student student=null;
try {
session.beginTransaction();
student= (Student)session.createQuery("select s from Student s where s.username='"+model.getUsername()+"' and s.password='"+model.getPassword()+"'").uniqueResult();
session.getTransaction().commit();
}catch (Exception e) {
session.getTransaction().rollback();

} finally {

session.close();
}
return student;
}

@POST
@Path("findByUsernameAndRealnameAndStudyabroadschool")
@Consumes("application/xml")
@Produces("application/xml")
public Student findByUsernameAndRealnameAndStudyabroadschool(Student model) {
Session session = HibernateUtil.getSessionFactory().openSession();
Student student=null;
try {
session.beginTransaction();
student= (Student)session.createQuery("select s from Student s where s.username='"+model.getUsername()+"' and s.realname='"+model.getRealname()+"' and s.studyabroadschool='"+model.getStudyabroadschool()+"'").uniqueResult();
session.getTransaction().commit();
}catch (Exception e) {
session.getTransaction().rollback();
return null;
} finally {

session.close();
}
return student;
}

@POST
@Path("modifyUserPasswordByUserid")
@Produces("application/xml")
@Consumes("application/xml")
public String modifyUserPasswordByUserid(Student model) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
session.beginTransaction();
//先查询到该对象
Student student=(Student)session.get(Student.class, model.getUserid());
student.setPassword(model.getPassword());
session.update(student);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
return "1";
} finally {
session.close();
}
return "0";
}
}
这个类也是通过上面样例的方式添加进去的,本文主要的特色是在DAO中添加了Hibernate的方法调用数据库,一般本地访问时,只需要在DAO部分调用对应的方法就可以了,因为要发布成服务,所以可以在服务器端调用数据库。
log4j.properties
log4j.rootLogger=ERROR, stdout

log4j.category.org.hibernate.tool.hbm2ddl =DEBUG, file
log4j.category.org.hibernate.SQL =DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%p] %m%n

log4j.appender.file = org.apache.log4j.FileAppender
log4j.appender.file.File = log.txt
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=Hibernate: %m%n
最后Run AS一下项目文件就可以将服务发布到Tomcat上去了。至此所有的代码部分都已经贴出来了,在使用Jersery开发过程中出现了许多问题,比如Hibernate的HibernateSession类总是出现不能实例化的问题,这个问题主要是Hibernate的版本问题,Hibernate从4.1以后使用HibernateSession和之前的方式有所不同,不需要配置XML方式或者Annotation方式的那部分代码。网上东西虽然很多,但是个性化的实现很难找到,需要不断尝试。希望本文对有这方面问题的朋友有帮助!!