用Jersey构建RESTful服务5--Jersey+MySQL5.6+Hibernate4.3

http://blog.csdn.net/kkkloveyou/article/details/21888283



一、总体说明

本例运行演示了用Jersey构建RESTful服务中,如何同过Hibernate将数据持久化进MySQL的过程

二、环境

1.上文的项目RestDemo

2.MySQL5.6下载http://dev.mysql.com/get/Downloads/MySQL-5.6/mysql-5.6.16-win32.zip

3.Hibernate4.3.4下载http://sourceforge.net/projects/hibernate/files/hibernate4/4.3.4.Final/hibernate-release-4.3.4.Final.zip

4.Java程序连接MySQL的驱动mysql-connector-java-5.1.29-bin.jar下载
http://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-5.1.29.zip

三、数据库准备

1.搭建MySQL数据库

2.创建数据库RestDemo ,及数据表t_user,结构如下

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `userId` varchar(50) NOT NULL,
  `userName` varchar(50) NOT NULL,
  `age` varchar(50) NOT NULL,
  PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


ps:   userId 非自增长类型,需要在业务添加

四、引入Hibernate

1.解压Hibernate的包,在lib\required文件夹下所有jar引入进项目


2.解压mysql-connector-java-5.1.29.zip,将mysql-connector-java-5.1.29-bin.jar引入进项目

3.在项目的根目录创建hibernate的配置文件hibernate.cfg.xml,内容如下:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version='1.0' encoding='utf-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
  5.   
  6. <hibernate-configuration>  
  7.    <session-factory>  
  8.    <!-- Database connection settings -->  
  9.         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>  
  10.         <property name="connection.url">jdbc:mysql://127.0.0.1:3306/RestDemo</property>  
  11.         <property name="connection.username">root</property>  
  12.         <property name="connection.password"></property>  
  13.   
  14.         <!-- JDBC connection pool (use the built-in) -->  
  15.         <property name="connection.pool_size">1</property>  
  16.   
  17.         <!-- SQL dialect -->  
  18.         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
  19.   
  20.         <!-- Enable Hibernate's automatic session context management -->  
  21.         <property name="current_session_context_class">thread</property>  
  22.   
  23.         <!-- Disable the second-level cache  -->  
  24.         <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>  
  25.    
  26.         <!-- Echo all executed SQL to stdout -->  
  27.         <property name="show_sql">true</property>  
  28.   
  29.         <!-- Drop and re-create the database schema on startup -->  
  30.         <property name="hbm2ddl.auto">update</property>  
  31.   
  32.   
  33.         <mapping resource="com/waylau/rest/bean/User.hbm.xml"/>  
  34.    
  35.     </session-factory>  
  36. </hibernate-configuration>  

4.在项目User.java 的同个目录下,创建该类的映射文件User.hbm.xml

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC  
  3.         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">  
  5.   
  6.    
  7. <hibernate-mapping package="com.waylau.rest.bean">  
  8.   
  9.     <class name="User" table="T_USER">  
  10.         <id name="userId" column="USERID"  type="string" >  
  11.             <generator class="assigned"/>  
  12.         </id>  
  13.         <property name="userName" type="string" />  
  14.         <property name="age" type="string" />  
  15.     </class>  
  16.    
  17. </hibernate-mapping>   
5.创建包com.waylau.rest.util,在该包下创建HibernateUtil.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.waylau.rest.util;  
  2.   
  3. import org.hibernate.SessionFactory;  
  4. import org.hibernate.boot.registry.StandardServiceRegistry;  
  5. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
  6. import org.hibernate.cfg.Configuration;  
  7. /** 
  8.  * Hibernate 初始化配置工具类 
  9.  * @author waylau.com 
  10.  * 2014-3-23 
  11.  */  
  12. public class HibernateUtil {  
  13.      private static Configuration configuration;  
  14.      private static SessionFactory sessionFactory;  
  15.      private static StandardServiceRegistry standardServiceRegistry;  
  16.         static {  
  17.             try {  
  18.              //第一步:读取Hibernate的配置文件  hibernamte.cfg.xml文件  
  19.               configuration = new Configuration().configure("hibernate.cfg.xml");          
  20.              //第二步:创建服务注册构建器对象,通过配置对象中加载所有的配置信息  
  21.               StandardServiceRegistryBuilder sb = new StandardServiceRegistryBuilder();  
  22.               sb.applySettings(configuration.getProperties());  
  23.              //创建注册服务  
  24.               standardServiceRegistry = sb.build();    
  25.             //第三步:创建会话工厂  
  26.               sessionFactory = configuration.buildSessionFactory(standardServiceRegistry);     
  27.             } catch (Throwable ex) {  
  28.                 // Make sure you log the exception, as it might be swallowed  
  29.                 System.err.println("Initial SessionFactory creation failed." + ex);  
  30.                 throw new ExceptionInInitializerError(ex);  
  31.             }  
  32.         }  
  33.   
  34.         public static SessionFactory getSessionFactory() {  
  35.             return sessionFactory;  
  36.         }  
  37. }  

6.在项目中建com.waylau.rest.dao包,在该包下建立User操作的接口UserDao.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.waylau.rest.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.waylau.rest.bean.User;  
  6.    
  7.   
  8. /** 
  9.  * User Dao 接口 
  10.  * @author waylau.com 
  11.  * 2014-3-18 
  12.  */  
  13. public interface UserDao {  
  14.       
  15.     public User getUserById(String id);  
  16.   
  17.     public boolean deleteUserById(String id);  
  18.   
  19.     public boolean createUser(User user);  
  20.   
  21.     public boolean updateUser(User user);  
  22.   
  23.     public List<User> getAllUsers();  
  24. }  

7.在项目中建com.waylau.rest.dao.impl包,在该包下建立User操作接口的实现UserDaoImpl.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.waylau.rest.dao.impl;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.Query;  
  6. import org.hibernate.Session;  
  7. import org.hibernate.SessionFactory;  
  8. import org.hibernate.Transaction;  
  9.   
  10. import com.waylau.rest.bean.User;  
  11. import com.waylau.rest.dao.UserDao;  
  12. import com.waylau.rest.util.HibernateUtil;  
  13. /** 
  14.  * 用户DAO实现 
  15.  * @author waylau.com 
  16.  * 2014-3-23 
  17.  */  
  18. public class UserDaoImpl implements UserDao {  
  19.   
  20.     @Override  
  21.     public User getUserById(String id) {  
  22.         SessionFactory sessionFactory = HibernateUtil.getSessionFactory();   
  23.         Session s = null;  
  24.         Transaction t = null;  
  25.         User user = null;  
  26.         try{  
  27.          s = sessionFactory.openSession();  
  28.          t = s.beginTransaction();  
  29.          String hql = "from User where userId="+id;    
  30.          Query query = s.createQuery(hql);    
  31.          user = (User) query.uniqueResult();   
  32.          t.commit();  
  33.         }catch(Exception err){  
  34.         t.rollback();  
  35.         err.printStackTrace();  
  36.         }finally{  
  37.         s.close();  
  38.         }  
  39.         return user;  
  40.     }  
  41.   
  42.     @Override  
  43.     public boolean deleteUserById(String id) {  
  44.         SessionFactory sessionFactory = HibernateUtil.getSessionFactory();   
  45.         Session s = null;  
  46.         Transaction t = null;  
  47.         boolean flag = false;  
  48.         try{  
  49.          s = sessionFactory.openSession();  
  50.          t = s.beginTransaction();  
  51.          User user = new User();    
  52.          user.setUserId(id);  
  53.          s.delete(user);  
  54.          t.commit();  
  55.          flag = true;  
  56.         }catch(Exception err){  
  57.         t.rollback();  
  58.         err.printStackTrace();  
  59.         }finally{  
  60.         s.close();  
  61.         }  
  62.         return flag;  
  63.     }  
  64.   
  65.     @Override  
  66.     public boolean createUser(User user) {  
  67.         SessionFactory sessionFactory = HibernateUtil.getSessionFactory();   
  68.         Session s = null;  
  69.         Transaction t = null;  
  70.         boolean flag = false;  
  71.         try{  
  72.          s = sessionFactory.openSession();  
  73.          t = s.beginTransaction();  
  74.          s.save(user);  
  75.          t.commit();  
  76.          flag = true;  
  77.         }catch(Exception err){  
  78.         t.rollback();  
  79.         err.printStackTrace();  
  80.         }finally{  
  81.         s.close();  
  82.         }  
  83.         return flag;  
  84.     }  
  85.   
  86.     @Override  
  87.     public boolean updateUser(User user) {  
  88.         SessionFactory sessionFactory = HibernateUtil.getSessionFactory();   
  89.         Session s = null;  
  90.         Transaction t = null;  
  91.         boolean flag = false;  
  92.         try{  
  93.          s = sessionFactory.openSession();  
  94.          t = s.beginTransaction();  
  95.          s.update(user);  
  96.          t.commit();  
  97.          flag = true;  
  98.         }catch(Exception err){  
  99.         t.rollback();  
  100.         err.printStackTrace();  
  101.         }finally{  
  102.         s.close();  
  103.         }  
  104.         return flag;  
  105.     }  
  106.   
  107.     @Override  
  108.     public List<User> getAllUsers() {  
  109.         SessionFactory sessionFactory = HibernateUtil.getSessionFactory();   
  110.         Session s = null;  
  111.         Transaction t = null;  
  112.         List<User> uesrs = null;  
  113.         try{  
  114.          s = sessionFactory.openSession();  
  115.          t = s.beginTransaction();  
  116.          String hql = "select * from t_user";    
  117.          Query query = s.createSQLQuery(hql).addEntity(User.class);    
  118.          query.setCacheable(true); // 设置缓存    
  119.          uesrs = query.list();    
  120.          t.commit();  
  121.         }catch(Exception err){  
  122.         t.rollback();  
  123.         err.printStackTrace();  
  124.         }finally{  
  125.         s.close();  
  126.         }  
  127.         return uesrs;  
  128.     }  
  129.   
  130. }  

8.修改项目中 com.waylau.rest.resources包下的UserResource.java,使之前在内存中模拟CURD转为在数据库中实现

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.waylau.rest.resources;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import javax.ws.rs.Path;  
  7. import javax.ws.rs.Produces;  
  8. import javax.ws.rs.Consumes;  
  9. import javax.ws.rs.PathParam;  
  10. import javax.ws.rs.core.MediaType;  
  11. import javax.ws.rs.DELETE;  
  12. import javax.ws.rs.GET;  
  13. import javax.ws.rs.POST;  
  14. import javax.ws.rs.PUT;  
  15.   
  16. import com.waylau.rest.bean.User;  
  17. import com.waylau.rest.dao.impl.UserDaoImpl;  
  18.   
  19. /** 
  20.  * 用户资源 
  21.  * @author waylau.com 
  22.  * 2014-3-19 
  23.  */  
  24. @Path("/users")  
  25. public class UserResource {  
  26.     private UserDaoImpl userDaoImpl = new UserDaoImpl();  
  27.     /** 
  28.      * 增加 
  29.      * @param user 
  30.      */  
  31.     @POST  
  32.     @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})  
  33.     public void createUser(User user)  
  34.     {  
  35.         userDaoImpl.createUser(user);  
  36.     }  
  37.       
  38.     /** 
  39.      * 删除 
  40.      * @param id 
  41.      */  
  42.     @DELETE  
  43.     @Path("{id}")  
  44.     public void deleteUser(@PathParam("id")String id){  
  45.         userDaoImpl.deleteUserById(id);  
  46.     }  
  47.       
  48.     /** 
  49.      * 修改 
  50.      * @param user 
  51.      */  
  52.     @PUT  
  53.     @Consumes(MediaType.APPLICATION_XML)  
  54.     public void updateUser(User user){  
  55.         userDaoImpl.updateUser(user);  
  56.     }  
  57.    
  58.     /** 
  59.      * 根据id查询 
  60.      * @param id 
  61.      * @return 
  62.      */  
  63.     @GET  
  64.     @Path("{id}")  
  65.     @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})  
  66.     public User getUserById(@PathParam("id") String id){  
  67.         User u = userDaoImpl.getUserById(id);  
  68.         return u;  
  69.     }  
  70.      
  71.     /** 
  72.      * 查询所有 
  73.      * @return 
  74.      */  
  75.     @GET  
  76.     @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})  
  77.     public List<User> getAllUsers(){       
  78.         List<User> users = new ArrayList<User>();     
  79.         users = userDaoImpl.getAllUsers();  
  80.         return users;  
  81.     }  
  82.       
  83.       
  84. }  


五、运行

1.将服务端运行后

2.运行UserClient客户端,可以看到数据库已经实现增删改查

完整项目架构如下:




=====================完整项目代码已经上传===================

https://github.com/waylau/Restdemo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值