针对用Jersey构建RESTful服务6--Jersey+SQLServer+Hibernate4.3和jerseyrestfulapi框架这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展
针对用Jersey构建RESTful服务6--Jersey+SQLServer+Hibernate4.3和jersey restful api 框架这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展android – Java jersey RESTful webservice请求、Hibernate **关于hibernate4.3版本之后org.hibernate.service.ServiceRegistryBuilder被弃用**、hibernate4.0 对 sqlserver 分页的支持、java – 使用jersey-spring3从JerseyTest容器中检索受管Bean等相关知识,希望可以帮助到你。
本文目录一览:- 用Jersey构建RESTful服务6--Jersey+SQLServer+Hibernate4.3(jersey restful api 框架)
- android – Java jersey RESTful webservice请求
- Hibernate **关于hibernate4.3版本之后org.hibernate.service.ServiceRegistryBuilder被弃用**
- hibernate4.0 对 sqlserver 分页的支持
- java – 使用jersey-spring3从JerseyTest容器中检索受管Bean
用Jersey构建RESTful服务6--Jersey+SQLServer+Hibernate4.3(jersey restful api 框架)
一、总体说明
本例运行演示了用Jersey构建RESTful服务中,如何同过Hibernate将数据持久化进sqlServer的过程
二、环境
1.上文的项目RestDemo
2.sqlServer2005三、配置
与上文MysqL的配置不同点主要在hibernate.cfg.xml文件;
配置如下:
<?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"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property> <property name="connection.url">jdbc:jtds:sqlserver://192.168.1.10:1433;RestDemo</property> <property name="connection.username">sa</property> <property name="connection.password">aA123456</property> <property name="hibernate.default_schema">RestDemo</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- sql dialect --> <property name="dialect">org.hibernate.dialect.sqlServerDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed sql to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <mapping resource="com/waylau/rest/bean/User.hbm.xml"/> </session-factory> </hibernate-configuration>四、问题
可能会出现如下错误
ERROR: 指定的架构名称 "RestDemo" 不存在,或者您没有使用该名称的权限。 三月 26,2014 3:38:43 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000232: Schema update complete Hibernate: insert into RestDemo.T_USER (userName,age,USERID) values (?,?,?) 三月 26,2014 3:38:43 下午 org.hibernate.engine.jdbc.spi.sqlExceptionHelper logExceptions WARN: sql Error: 208,sqlState: S0002 三月 26,2014 3:38:43 下午 org.hibernate.engine.jdbc.spi.sqlExceptionHelper logExceptions ERROR: 对象名 'RestDemo.T_USER' 无效。
解决方案:
将配置文件中的“hibernate.default_schema”值修改为如下即可:
<property name="hibernate.default_schema">RestDemo.dbo</property>
或者去掉上面的配置,在“User.hbm.xml”修改如下
<class name="User" table="T_USER" schema="RestDemo.dbo">
android – Java jersey RESTful webservice请求
我一直在关注一个关于宁静服务的教程,它运行正常.然而,有一些我还不太了解的东西.这是它的样子:
@Path("/hello")
public class Hello {
// This method is called if TEXT_PLAIN is request
@GET
@Produces( MediaType.TEXT_PLAIN )
public String sayPlainTextHello()
{
return "Plain hello!";
}
@GET
@Produces( MediaType.APPLICATION_JSON )
public String sayJsonTextHello()
{
return "Json hello!";
}
// This method is called if XML is request
@GET
@Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}
// This method is called if HTML is request
@GET
@Produces(MediaType.TEXT_HTML)
public String sayHtmlHello()
{
return "<html> " + "<title>" + "Hello fittemil" + "</title>"
+ "<body><h1>" + "Hello!" + "</body></h1>" + "</html> ";
}
}
困扰我的是我无法利用正确的操作.当我从浏览器请求服务时,会调用相应的sayHtmlHello()方法.但是现在我正在开发一个Android应用程序,我希望在Json中得到结果.但是当我从应用程序调用该服务时,将调用MediaType.TEXT_PLAIN方法.我的android代码看起来与此类似:
Make an HTTP request with android
如何从我的Android应用程序中调用使用MediaType.APPLICATION_JSON的方法?
此外,我想使该特定方法返回一个对象,如果我在那里得到一些指导,那将是很好的.
解决方法:
我个人有使用Jersey在Java(JAX-RS)中实现REST的经验.然后我通过Android应用程序连接到这个RESTful Web服务.
在Android应用程序中,您可以使用HTTP Client库.它支持HTTP命令,如POST,PUT,DELETE,GET.例如,使用GET命令并以JSON格式或TextPlain传输数据:
public class Client {
private String server;
public Client(String server) {
this.server = server;
}
private String getBase() {
return server;
}
public String getBaseURI(String str) {
String result = "";
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
httpconnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
httpconnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpGet getRequest = new HttpGet(getBase() + str);
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
result = getResult(response).toString();
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
public String getBaseURIText(String str) {
String result = "";
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
httpconnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
httpconnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpGet getRequest = new HttpGet(getBase() + str);
getRequest.addHeader("accept", "text/plain");
HttpResponse response = httpClient.execute(getRequest);
result = getResult(response).toString();
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException {
StringBuilder result = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024);
String output;
while ((output = br.readLine()) != null)
result.append(output);
return result;
}
}
然后在Android类中,您可以:
Client client = new Client("http://localhost:6577/Example/rest/");
String str = client.getBaseURI("Example"); // Json format
解析JSON字符串(或者可能是xml)并在ListView,GridView和…中使用它
我简要介绍了你提供的链接.那里有一个好点.您需要在API级别11或更高级别的单独线程上实现网络连接.看看这个链接:HTTP Client API level 11 or greater in Android.
这是我在Client类中使用HTTP发布对象的方式:
public String postBaseURI(String str, String strUrl) {
String result = "";
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
httpconnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
httpconnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost postRequest = new HttpPost(getBase() + strUrl);
StringEntity input = new StringEntity(str);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
result = getResult(response).toString();
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
在REST WS中,我将对象发布到数据库:
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public Response addTask(Task task) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(task);
session.getTransaction().commit();
return Response.status(Response.Status.CREATED).build();
}
Hibernate **关于hibernate4.3版本之后org.hibernate.service.ServiceRegistryBuilder被弃用**
-
之前一直都是使用hibernate4.2.21的我,有一天突然没有使用本地的jar包而是让IDEA自动下载最新版本的hibernate5.2.2之后,发现有几个经常使用的方法报错了.
//创建配置对象
Configuration config=new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry2=new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry();
//创建会话工厂对象
sessionFactory=config.buildSessionFactory(serviceRegistry2);
//会话对象
session=sessionFactory.openSession();
//开启事务
transaction=session.beginTransaction(); -
-这真是让我惊了个呆,网上一搜,好像有这个问题的人还不少,然后发现果然是hibernate版本的问题——hibernate4.3之后已经没有了org.hibernate.service.ServiceRegistryBuilder这个类,它被弃用了
-
这下子问题就迎刃而解了
-如果使用的是hibernate4.2之前的版本,那么方法就这么写:
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//创建会话工厂对象 sessionFactory = config.buildSessionFactory(serviceRegistry); //会话对象 session = sessionFactory.openSession(); //开启事务 transaction = session.beginTransaction();
-如果是hibernate4.3之后的版本,那么方法就这么写:
导入包更换:org.hibernate.boot.registry.StandardServiceRegistryBuilder;
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config .getProperties()).build();
//创建会话工厂对象 sessionFactory = config.buildSessionFactory(serviceRegistry); //会话对象 session = sessionFactory.openSession(); //开启事务 transaction = session.beginTransaction();
-甚至我还发现到hibernate5之后连上面的包都可以省略了:
//创建配置对象(读取配置文档)
Configuration config = new Configuration().configure();
//创建会话工厂对象
sessionFactory = config.buildSessionFactory();
//会话对象
session = sessionFactory.openSession();
//开启事务 transaction = session.beginTransaction();
hibernate4.0 对 sqlserver 分页的支持
想问一下 hibernate 的 q.setFirstResult (nums).setMaxResults (rows) 对 sqlserver 能准确查出数据来么,同事说 hibernate 对 sqlserver 分页支持不好。java – 使用jersey-spring3从JerseyTest容器中检索受管Bean
我们正在使用jersey-spring将泽西1.x的一些数据服务从泽西春天迁移到泽西2.x.
我们有几个继承自JerseyTest的测试类.其中一些类使用未在web.xml文件中指定的自定义applicationContext.xml文件.
为了嘲笑目标,我们会嘲笑我们泽西资源部分的一些组件.
在泽西1.x我们可以在应用程序上下文文件中模拟对象
<bean id="mockBean"factory-method="createStrictMock" autowire="byName"> <constructor-arg index="0" value="com.xxx.xxx.ClasstoMock" /> </bean>
并检索这些嘲弄的实例如下
ClasstoMock obj = (ClasstoMock)ContextLoader .getCurrentWebApplicationContext() .getAutowireCapablebeanfactory() .getBean("mockBean");
如何使用泽西 – 春季3?
我已经梳理了API docs,user guides和一些sources,但无法找到答案.
谢谢.
编辑:
我们将使用JAX-RS资源内的嘲弄bean.我们拥有@Autowired到我们的资源的服务接口.
例如
@Path(ProductResource.RESOURCE_PATH) @Component @Scope("prototype") public class ProductResource extends GenericResource<Product,BaseModel> { /* * Members */ public static final String RESOURCE_PATH = "product/"; @Autowired protected ProductService productService; ...
我们想嘲笑这些服务的期望.
例如
<bean id="productService"factory-method="createStrictMock"> <constructor-arg index="0" value="com.xxx.xxx.service.ProductService" /> </bean>
解决方法
您不能通过调用ContextLoader#getCurrentWebApplicationContext()获取一个ApplicationContext实例,因为当使用Jersey Test Framework(JerseyTest)进行单元/ e2e测试时,默认情况下,在Servlet容器之外默认使用Jersey 2.x运行时.
在这种情况下,您需要使用一些解决方法来获取ApplicationContext,方法是在测试包中实现一个ApplicationContextAware接口:
public class ApplicationContextUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext() { return applicationContext; } @Override public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { ApplicationContextUtils.applicationContext = applicationContext; } }
一旦你有这个类,不要忘记在你的应用程序上下文描述符中提到它:
... <bean/> ...
你可以在测试中使用它:
public class JerseySpringResourceTest extends JerseyTest { // ... Configure ... @Before public void mockUp() throws Exception { // ApplicationContext is ready in your @Before methods ... assertthat(ApplicationContextUtils.getApplicationContext(),notNullValue()); } @Test public void testJerseyResource() { // ... as well as in your test methods. assertthat(ApplicationContextUtils.getApplicationContext(),notNullValue()); } }
注意:如果要将应用程序部署到Servlet容器并对其执行(JerseyTest)测试,请参阅“用户指南”(特别是External container部分)中的Jersey Test Framework章节.
今天的关于用Jersey构建RESTful服务6--Jersey+SQLServer+Hibernate4.3和jersey restful api 框架的分享已经结束,谢谢您的关注,如果想了解更多关于android – Java jersey RESTful webservice请求、Hibernate **关于hibernate4.3版本之后org.hibernate.service.ServiceRegistryBuilder被弃用**、hibernate4.0 对 sqlserver 分页的支持、java – 使用jersey-spring3从JerseyTest容器中检索受管Bean的相关知识,请在本站进行查询。
本文标签: