Build a RESTful service with Jersey 5 -- Jersey + MySQL5.6 + Hibernate4.3

Source: Internet
Author: User

I. General description

This example demonstrates how to use Jersey to build a RESTful service and how to persistently import data into MySQL through Hibernate.

II. Environment

1. RestDemo of the above project

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

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

4. Java program connection MySQL driver mysql-connector-java-5.1.29-bin.jar download
Http://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-5.1.29.zip

Iii. Database preparation

1. Build a MySQL database

2. Create a database RestDemo and a data table t_user. The structure is as follows:

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 is not a self-increasing type and needs to be added to the business

4. Introduce Hibernate <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + MS694tG5SGliZXJuYXRltcSw/KOs1NpsaWJccmVxdWlyZWTOxLz + vNDPwsv509BqYXLS/cjrvfjP7sS/authorization = "http://www.2cto.com/uploadfile/Collfiles/20140324/20140324093339141.jpg" alt = "\"

2.decompress mysql-connector-java-5.1.29.zip, introduce the mysql-connector-java-5.1.29-bin.jar into the project

3. Create the hibernate configuration file hibernate. cfg. xml in the root directory of the project. The content is as follows:

 
    
     
           
   
    com.mysql.jdbc.Driver
           
   
    jdbc:mysql://127.0.0.1:3306/RestDemo
           
   
    root
           
           
           
   
    1
           
           
   
    org.hibernate.dialect.MySQLDialect
           
           
   
    thread
           
           
   
    org.hibernate.cache.internal.NoCacheProvider
            
           
   
    true
           
           
   
    update
           
        
  
 

4. In the same directory of Project User. java, create the ing file User. hbm. xml for this class.

  
     
          
               
            
           
           
       
   
  
5. Create the package com. waylau. rest. util and create HibernateUtil. java under the package.

Package com. waylau. rest. util; import org. hibernate. sessionFactory; import org. hibernate. boot. registry. standardServiceRegistry; import org. hibernate. boot. registry. standardServiceRegistryBuilder; import org. hibernate. cfg. configuration;/*** Hibernate Initialization Configuration tool class * @ author waylau.com * 2014-3-23 */public class HibernateUtil {private static configuration Configuration; private static SessionFactory sessionFactory; private static StandardServiceRegistry standardServiceRegistry; static {try {// Step 1: Read the Hibernate configuration file hibernamte. cfg. xml file configuration = new Configuration (). configure ("hibernate. cfg. xml "); // Step 2: create a service register builder object and load all configuration information in the configuration object. StandardServiceRegistryBuilder sb = new StandardServiceRegistryBuilder (); sb. applySettings (configuration. getProperties (); // create the registration service standardServiceRegistry = sb. build (); // Step 3: Create the session factory 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 ;}}

6. Create the com. waylau. rest. dao package in the project, and create the User operation interface UserDao. java under the package.

Package com. waylau. rest. dao; import java. util. list; import com. waylau. rest. bean. user;/*** User Dao interface * @ author waylau.com * 2014-3-18 */public interface UserDao {public User getUserById (String id); public boolean deleteUserById (String id ); public boolean createUser (User user); public boolean updateUser (User user); public List
 
  
GetAllUsers ();}
 

7. Create the com. waylau. rest. dao. impl package in the project, and create the User operation interface under the package to implement UserDaoImpl. java

Package com. waylau. rest. dao. impl; import java. util. list; import org. hibernate. query; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. transaction; import com. waylau. rest. bean. user; import com. waylau. rest. dao. userDao; import com. waylau. rest. util. hibernateUtil;/*** User DAO implementation * @ author waylau.com * 2014-3-23 */public class UserDaoImpl implements UserDao {@ Overridepublic User getUserById (String id) {SessionFactory sessionFactory = HibernateUtil. getSessionFactory (); Session s = null; Transaction t = null; User user = null; try {s = sessionFactory. openSession (); t = s. beginTransaction (); String hql = "from User where userId =" + id; Query query = s. createQuery (hql); user = (User) query. uniqueResult (); t. commit ();} catch (Exception err) {t. rollback (); err. printStackTrace ();} finally {s. close () ;}return user ;}@ Overridepublic boolean deleteUserById (String id) {SessionFactory sessionFactory = HibernateUtil. getSessionFactory (); Session s = null; Transaction t = null; boolean flag = false; try {s = sessionFactory. openSession (); t = s. beginTransaction (); User user = new User (); user. setUserId (id); s. delete (user); t. commit (); flag = true;} catch (Exception err) {t. rollback (); err. printStackTrace ();} finally {s. close () ;}return flag ;}@ Overridepublic boolean createUser (User user) {SessionFactory sessionFactory = HibernateUtil. getSessionFactory (); Session s = null; Transaction t = null; boolean flag = false; try {s = sessionFactory. openSession (); t = s. beginTransaction (); s. save (user); t. commit (); flag = true;} catch (Exception err) {t. rollback (); err. printStackTrace ();} finally {s. close () ;}return flag ;}@ Overridepublic boolean updateUser (User user) {SessionFactory sessionFactory = HibernateUtil. getSessionFactory (); Session s = null; Transaction t = null; boolean flag = false; try {s = sessionFactory. openSession (); t = s. beginTransaction (); s. update (user); t. commit (); flag = true;} catch (Exception err) {t. rollback (); err. printStackTrace ();} finally {s. close () ;}return flag ;}@ Overridepublic List
 
  
GetAllUsers () {SessionFactory sessionFactory = HibernateUtil. getSessionFactory (); Session s = null; Transaction t = null; List
  
   
Uesrs = null; try {s = sessionFactory. openSession (); t = s. beginTransaction (); String hql = "select * from t_user"; Query query = s. createSQLQuery (hql ). addEntity (User. class); query. setCacheable (true); // set cache uesrs = query. list (); t. commit ();} catch (Exception err) {t. rollback (); err. printStackTrace ();} finally {s. close () ;}return uesrs ;}}
  
 

8. Modify UserResource. java under the com. waylau. rest. resources package in the project, and convert the previously simulated CURD in the memory into a database.

Package com. waylau. rest. resources; import java. util. arrayList; import java. util. list; import javax. ws. rs. path; import javax. ws. rs. produces; import javax. ws. rs. consumes; import javax. ws. rs. pathParam; import javax. ws. rs. core. mediaType; import javax. ws. rs. DELETE; import javax. ws. rs. GET; import javax. ws. rs. POST; import javax. ws. rs. PUT; import com. waylau. rest. bean. user; import com. waylau. rest. dao. impl. userDaoImpl;/*** user resource * @ author waylau.com * 2014-3-19 */@ Path ("/users") public class UserResource {private UserDaoImpl userDaoImpl = new UserDaoImpl (); /*** add * @ param user */@ POST @ Consumes ({MediaType. APPLICATION_XML, MediaType. APPLICATION_JSON}) public void createUser (User user User) {userDaoImpl. createUser (user);}/*** DELETE * @ param id */@ DELETE @ Path ("{id}") public void deleteUser (@ PathParam ("id ") string id) {userDaoImpl. deleteUserById (id);}/*** modify * @ param user */@ PUT @ Consumes (MediaType. APPLICATION_XML) public void updateUser (User user User) {userDaoImpl. updateUser (user);}/*** query by id * @ param id * @ return */@ GET @ Path ("{id}") @ Produces ({MediaType. APPLICATION_XML, MediaType. APPLICATION_JSON}) public User getUserById (@ PathParam ("id") String id) {User u = userDaoImpl. getUserById (id); return u;}/*** query all * @ return */@ GET @ Produces ({MediaType. APPLICATION_XML, MediaType. APPLICATION_JSON}) public List
 
  
GetAllUsers () {List
  
   
Users = new ArrayList
   
    
(); Users = userDaoImpl. getAllUsers (); return users ;}}
   
  
 


V. Running

1. After the server is run

2. Run the UserClient client. You can see that the database has been added, deleted, modified, and queried.

The complete project architecture is as follows:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.