写给自己记录,顺便留给需要的人
环境
- myeclipse2014
- jdk 1.8
- tomcat 8.0.41
- mysql 5.7.14
- maven 3.3.9
- spring 4.3.8.RELEASE
- jersey 2.25.1
- hibernate 5.2.10.Final
- 接口测试工具:postman
用到的包:pom.xml
UTF-8
4.3.8.RELEASE
2.25.1
javax
javaee-api
7.0
provided
org.glassfish.jersey.ext
jersey-spring3
${jersey.version}
org.springframework
spring-core
org.springframework
spring-web
org.springframework
spring-beans
org.codehaus.jackson
jackson-all
1.9.11
org.springframework
spring-aop
${spring.version}
org.springframework
spring-beans
${spring.version}
org.springframework
spring-core
${spring.version}
org.springframework
spring-expression
${spring.version}
org.springframework
spring-orm
${spring.version}
org.springframework
spring-web
${spring.version}
com.mchange
c3p0
0.9.5.2
org.aspectj
aspectjweaver
1.8.10
org.hibernate
hibernate-core
5.2.10.Final
mysql
mysql-connector-java
5.1.6
Spring配置:applicationContext.xml
com.ourfor.*.bean
${hibernate.hbm2ddl.auto}
${hibernate.dialect}
${hibernate.show_sql}
${hibernate.format_sql}
false
需要注意按自己项目修改的地方:
Spring要扫描的包
Spring 注解 hibernate 实体bean的包
包名.*.bean
Spring事务管理的包
- execution(* 包名..*(..)):当前包及子包下面的类
- execution(* 包名.*(..)):当前包下面的类
jdbc.properties
#-----------------------------------------------------
# 数据库配置
#-----------------------------------------------------
host=127.0.0.1
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://${host}:3306/test
jdbc.username=root
jdbc.password=toor
#-----------------------------------------------------
#c3p0配置
#-----------------------------------------------------
jdbc.c3p0.testConnectionOnCheckout=false
jdbc.c3p0.testConnectionOnCheckin=true
jdbc.c3p0.idleConnectionTestPeriod=3600
jdbc.c3p0.initialPoolSize=10
jdbc.c3p0.minPoolSize=10
jdbc.c3p0.maxPoolSize=100
jdbc.c3p0.maxIdleTime=3600
#-----------------------------------------------------
# hibernate配置
#-----------------------------------------------------
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=update
web.xml
Demo
Demo
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:applicationContext.xml
Way REST Service
org.glassfish.jersey.servlet.ServletContainer
javax.ws.rs.Application
com.ourfor.rest.RestApplication
1
Way REST Service
/rest/*
jersey2 还需指定JAX-RS application
javax.ws.rs.Application
com.ourfor.rest.RestApplication
RestApplication.java
package com.ourfor.rest;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.glassfish.jersey.server.ResourceConfig;
public class RestApplication extends ResourceConfig {
public RestApplication() {
packages("com.ourfor");
register(JacksonJsonProvider.class);
}
}
User.bean
package com.ourfor.rest.bean;
import java.io.Serializable;
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 = "t_user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "userId", unique = true)
private String userId;
@Column(name = "userName")
private String userName;
@Column(name = "age")
private String age;
@Column(name = "t")
private String t;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getT() {
return t;
}
public void setT(String t) {
this.t = t;
}
}
UserDao.java
package com.ourfor.rest.dao;
import java.util.List;
import com.ourfor.rest.bean.User;
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();
}
UserDaoImpl.java
package com.ourfor.rest.dao.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.ourfor.rest.bean.User;
import com.ourfor.rest.dao.UserDao;
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
private Session getSession() {
return sessionFactory.openSession();
}
@Override
public User getUserById(String id) {
Session s = null;
Transaction t = null;
User user = null;
try {
s = getSession();
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;
}
@Override
public boolean deleteUserById(String id) {
Session s = null;
Transaction t = null;
boolean flag = false;
try {
s = getSession();
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;
}
@Override
public boolean createUser(User user) {
Session s = null;
Transaction t = null;
boolean flag = false;
try {
s = getSession();
t = s.beginTransaction();
s.save(user);
t.commit();
flag = true;
} catch (Exception err) {
t.rollback();
err.printStackTrace();
} finally {
s.close();
}
return flag;
}
@Override
public boolean updateUser(User user) {
Session s = null;
Transaction t = null;
boolean flag = false;
try {
s = getSession();
t = s.beginTransaction();
s.update(user);
t.commit();
flag = true;
} catch (Exception err) {
t.rollback();
err.printStackTrace();
} finally {
s.close();
}
return flag;
}
@SuppressWarnings("unchecked")
@Override
public List getAllUsers() {
Session s = null;
Transaction t = null;
List uesrs = null;
try {
s = getSession();
t = s.beginTransaction();
String hql = " from User";
Query query = s.createQuery(hql);
uesrs = query.list();
t.commit();
} catch (Exception err) {
t.rollback();
err.printStackTrace();
} finally {
s.close();
}
return uesrs;
}
}
UserService.java
package com.ourfor.rest.service;
import java.util.List;
import com.ourfor.rest.bean.User;
public interface UserService {
public User getUserById(String id);
public boolean deleteUserById(String id);
public boolean createUser(User user);
public boolean updateUser(User user);
public List getAllUsers();
}
UserServiceImpl.java
package com.ourfor.rest.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ourfor.rest.bean.User;
import com.ourfor.rest.dao.UserDao;
import com.ourfor.rest.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Resource
@Autowired
private UserDao userDao;
public UserServiceImpl() {
// TODO Auto-generated constructor stub
}
@Override
public User getUserById(String id) {
return userDao.getUserById(id);
}
@Override
public boolean deleteUserById(String id) {
return userDao.deleteUserById(id);
}
@Override
public boolean createUser(User user) {
return userDao.createUser(user);
}
@Override
public boolean updateUser(User user) {
return userDao.updateUser(user);
}
@Override
public List getAllUsers() {
return userDao.getAllUsers();
}
}
UserResource.java
package com.ourfor.rest.resources;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import com.ourfor.rest.bean.User;
import com.ourfor.rest.service.impl.UserServiceImpl;
@Path("/users")
public class UserResource {
private static final Logger LOGGER = Logger.getLogger(UserResource.class.getName());
@Autowired
private UserServiceImpl userServiceImpl;
public UserResource() {
LOGGER.fine("UserResource()");
}
/**
* 增加
* @param user
*/
@POST
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public String createUser(User user)
{
if(userServiceImpl.createUser(user)){
return "{\"flag\":\"true\"}";
}else{
return "{\"flag\":\"false\"}";
}
}
/**
* 删除
* @param id
*/
@DELETE
@Produces({MediaType.APPLICATION_JSON})
@Path("{id}")
public String deleteUser(@PathParam("id")String id){
if(userServiceImpl.deleteUserById(id)){
return "{\"flag\":\"true\"}";
}else{
return "{\"flag\":\"false\"}";
}
}
/**
* 修改
* @param user
*/
@PUT
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public String updateUser(User user){
if(userServiceImpl.updateUser(user)){
return "{\"flag\":\"true\"}";
}else{
return "{\"flag\":\"false\"}";
}
}
/**
* 根据id查询
* @param id
* @return
*/
@GET
@Path("{id}")
@Produces({MediaType.APPLICATION_JSON})
public User getUserById(@PathParam("id") String id){
User user = userServiceImpl.getUserById(id);
return user;
}
/**
* 查询所有
* @return
*/
@GET
@Produces({MediaType.APPLICATION_JSON})
public List getAllUsers(){
List users = new ArrayList();
users = userServiceImpl.getAllUsers();
return users;
}
}
运行测试
- getAllUsers
- createUser
- getUserById
- updateUser
- deleteUser