Spring+Hibernate+Jersey整合

导入需要的jar包

Spring+Hibernate+Jersey整合_第1张图片

项目结构



Spring配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/task 
http://www.springframework.org/schema/task/spring-task-3.0.xsd">

    <bean  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>classpath:database.properties</value>
        </property>
    </bean>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${jdbc.driverClassName}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
        <property name="minPoolSize" value="${jdbc.minPoolSize}" />
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
        <property name="maxIdleTime" value="${jdbc.maxIdleTime}" />
        <property name="maxStatements" value="${jdbc.maxStatements}" />
        <property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
    </bean>

    <bean id="sessionFactory"  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
            <list>
                <value>com.test.bean</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
            </props>
        </property>
    </bean>

    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    
    <!-- Config spring annotation package -->
    <context:component-scan base-package="com.test"></context:component-scan>

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:advice id="tmAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
            <tx:method name="del*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="*" read-only="true" />
        </tx:attributes>
    </tx:advice>
    
</beans>


数据库连接配置

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
jdbc.initialPoolSize=30
jdbc.minPoolSize=20
jdbc.maxPoolSize=100
jdbc.maxIdleTime=600
jdbc.maxStatements=200
jdbc.acquireIncrement=10

hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=false
hibernate.format_sql=true

log4j配置

#log4j.rootLogger=DEBUG,A1,R
log4j.rootLogger=INFO,A1,R
log4j.logger.com.augmentum=DEBUG
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%d %6p at %C.%M(%F:%L)] %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=C://logs//a.log
log4j.appender.R.Append=true
log4j.appender.R.DatePattern=.yyyy-MM-dd.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=[%d %6p at %C.%M(%F:%L)] %m%n

web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>test</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
   
  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
   
  <!-- jersey interceptor -->
  <servlet>
    <servlet-name>JerseyServlet</servlet-name>
    <servlet-class>
       com.sun.jersey.spi.spring.container.servlet.SpringServlet
    </servlet-class>
    <init-param>
        <param-name>
            com.sun.jersey.config.property.packages    
        </param-name>
        <param-value>
            com.test.resource
        </param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>JerseyServlet</servlet-name>
    <url-pattern>/resource/*</url-pattern>
  </servlet-mapping>
</web-app>

Javabean

package com.test.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;
    @Column(name = "username")
    private String username;
    @Column(name = "password")
    private String password;


    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
    }

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    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;
    }


}

Dao层

basedao

package com.test.dao;

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

/**
 * The base interface for all the dao layer interface,it provide common method
 *
 * @author Irwin.Ai
 *
 * @param <T>
 *            The entity class type
 * @param <PK>
 *            The primary key of the entity class
 */
public interface BaseDao<T, PK extends Serializable> {
    public T add(T t);

    public void delete(T t);

    public T load(PK id);

    public T get(PK id);

    public List<T> loadAll();

    public T update(T t);

}

userdao

package com.test.dao;

import com.test.bean.User;

public interface UserDao extends BaseDao<User, Integer> {

}

Dao层实现

basedao实现

package com.test.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.test.dao.BaseDao;


/**
 * The base interface implement for all the dao layer interface implements,it
 * provide common method
 *
 * @author Irwin.Ai
 *
 * @param <T>
 *            The entity class type
 * @param <PK>
 *            The primary key of the entity class
 */
@Repository
public class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK> {

    private Class<T> entityClass;
    private HibernateTemplate hibernateTemplate;

    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }

    @Resource
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

    /**
     * Method to judge the type of class
     */
    @SuppressWarnings("unchecked")
    public BaseDaoImpl() {
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] types = ((ParameterizedType) type).getActualTypeArguments();
            this.entityClass = (Class<T>) types[0];
        }
    }

    @Override
    public T add(T t) {
        hibernateTemplate.save(t);
        return t;
    }

    @Override
    public void delete(T t) {
        hibernateTemplate.delete(t);
    }

    @Override
    public T load(PK id) {
        return hibernateTemplate.load(entityClass, id);
    }

    @Override
    public List<T> loadAll() {
        return hibernateTemplate.loadAll(entityClass);
    }

    @Override
    public T update(T t) {
        hibernateTemplate.update(t);
        return t;
    }

    @Override
    public T get(PK id) {
        return hibernateTemplate.get(entityClass, id);
    }

    /**
     * If there is a session alive, we will use it instead of open an new
     * Session.
     *
     * @return
     */
    public Session getCurrentSession() {
        Session session = hibernateTemplate.getSessionFactory()
                .getCurrentSession();
        if (session == null) {
            session = hibernateTemplate.getSessionFactory().openSession();
        }
        return session;
    }

}

userdao实现

package com.test.dao.impl;

import org.springframework.stereotype.Repository;

import com.test.bean.User;
import com.test.dao.UserDao;

@Repository
public class UserDaoImpl extends BaseDaoImpl<User, Integer> implements UserDao{

}

service层

baseservice

package com.test.service;

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

/**
 * * The base interface for all the service layer interface,it provide common
 * method
 * 
 * @author Irwin.Ai
 * 
 * @param <T>
 *            The entity class type
 * @param <PK>
 *            The primary key of the entity class
 */
public interface BaseService<T, PK extends Serializable> {

    public T add(T t);

    public void delete(T t);

    public T load(PK id);

    public T get(PK id);

    public List<T> loadAll();

    public T update(T t);

}

userservice

package com.test.service;

import com.test.bean.User;


public interface UserService extends BaseService<User, Integer> {

}

service层实现

baseservice实现

package com.test.service.impl;

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

import com.test.dao.BaseDao;
import com.test.service.BaseService;


/**
 * * The base interface implement for all the service layer interface
 * implements,it provide common method
 *
 * @author Irwin.Ai
 *
 * @param <T>
 *            The entity class type
 * @param <PK>
 *            The primary key of the entity class
 */
public class BaseServiceImpl<T, PK extends Serializable> implements
        BaseService<T, PK> {

    private BaseDao<T, PK> baseDao;

    public BaseDao<T, PK> getBaseDao() {
        return baseDao;
    }

    public void setBaseDao(BaseDao<T, PK> baseDao) {
        this.baseDao = baseDao;
    }

    @Override
    public T add(T t) {
        return baseDao.add(t);
    }

    @Override
    public void delete(T t) {
        baseDao.delete(t);
    }

    @Override
    public T load(PK id) {
        return baseDao.load(id);
    }

    @Override
    public List<T> loadAll() {
        return baseDao.loadAll();
    }

    @Override
    public T update(T t) {
        return baseDao.update(t);
    }

    @Override
    public T get(PK id) {
        return baseDao.get(id);
    }

}

userservice实现

package com.test.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.test.bean.User;
import com.test.dao.UserDao;
import com.test.service.UserService;

@Service
public class UserServiceImpl extends BaseServiceImpl<User, Integer> implements UserService {
    @Resource
    public void setBaseDao(UserDao userDao) {
        super.setBaseDao(userDao);
    }

}

jersey resource类示例

package com.test.resource;

import java.util.List;

import javax.annotation.Resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;

import com.google.gson.Gson;
import com.sun.jersey.spi.resource.Singleton;
import com.test.bean.User;
import com.test.service.UserService;

@Path("/users")
@Singleton
@Controller
public class UserResource {

    private static Logger logger = Logger.getLogger(UserResource.class);
    @Resource
    private UserService userService;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getAllUser() {
        List<User> list = null;
        String str = null;
        try {
            list = userService.loadAll();
            str = new Gson().toJson(list);
        } catch (Exception e) {
            logger.error("load all exception : ", e);
        }
        return str;
    }
}

页面访问测试

我们现在访问页面http://localhost:8080/SSJTest/resource/users

取到返回的json数据。

PS:jersey jar包必须使用同一个版本,本人使用1.13版本测试没有问题

你可能感兴趣的:(spring,jersey,hibern)