文档章节

第二讲:tapestry增删改查---添加数据

神勇小白鼠
 神勇小白鼠
发布于 2012/04/13 14:31
字数 1394
阅读 284
收藏 1

增、删、改、查。这是开发程序最基本的、必须掌握的事。如果看不懂可以先跳过此文,先看看后面的再回来仔细阅读,应该能更好理解。

 

实现使用了tapestry ioc的接口开发方式,也就是一个接口DAO,一个接口方法Impl,使用的时候调用接口的方法。要做增删改查还需要实体entity以及数据库,这里使用mySql。实体与数据库的连接使用tapestry-hibernate、c3p0、mysql-connector-java.

 

打开项目根目录下的pom.xml,增加需要的tapestry-hibernate、c3p0、mysql-connector-java、tapestry-upload连接,代码如下:

 

<dependency>
<groupId>org.apache.tapestry</groupId>
<artifactId>tapestry-hibernate</artifactId>
<version>${tapestry-release-version}</version>
</dependency>

 <dependency>

            <groupId>org.apache.tapestry</groupId>
            <artifactId>tapestry-upload</artifactId>
            <version>${tapestry-release-version}</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.17</version>
</dependency>

 

修改服务,打开com.tapestry.app.services下的AppModule.java文件进行配置,源码如下:

 package com.tapestry.app.services;

 
import java.io.IOException;
 
import org.apache.tapestry5.*;
import org.apache.tapestry5.hibernate.HibernateCoreModule;
import org.apache.tapestry5.hibernate.HibernateModule;
import org.apache.tapestry5.hibernate.HibernateSymbols;
import org.apache.tapestry5.hibernate.HibernateTransactionAdvisor;
import org.apache.tapestry5.ioc.MappedConfiguration;
import org.apache.tapestry5.ioc.MethodAdviceReceiver;
import org.apache.tapestry5.ioc.OrderedConfiguration;
import org.apache.tapestry5.ioc.ServiceBinder;
import org.apache.tapestry5.ioc.annotations.Local;
import org.apache.tapestry5.ioc.annotations.Match;
import org.apache.tapestry5.ioc.annotations.SubModule;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.RequestFilter;
import org.apache.tapestry5.services.RequestHandler;
import org.apache.tapestry5.services.Response;
import org.apache.tapestry5.upload.services.UploadModule;
import org.apache.tapestry5.upload.services.UploadSymbols;
import org.slf4j.Logger;
 
@SubModule({HibernateModule.class, HibernateCoreModule.class,UploadModule.class})
public class AppModule
{
    public static void bind(ServiceBinder binder)
    {
        // binder.bind(MyServiceInterface.class, MyServiceImpl.class);
    }
 
    public static void contributeFactoryDefaults(
            MappedConfiguration<String, Object> configuration)
    { 
        configuration.override(SymbolConstants.APPLICATION_VERSION, "1.0");
    }
 
    public static void contributeApplicationDefaults(
            MappedConfiguration<String, Object> configuration)
    {
    configuration.add(SymbolConstants.SUPPORTED_LOCALES, "en");
        configuration.add(SymbolConstants.PRODUCTION_MODE, "false");
        configuration.add(UploadSymbols.FILESIZE_MAX, "50000000");
        configuration.add(SymbolConstants.APPLICATION_VERSION, "1.0-SNAPSHOT");
        configuration
.add(HibernateSymbols.ENTITY_SESSION_STATE_PERSISTENCE_STRATEGY_ENABLED,
"true");
    }
 
    @Match("*DAO")
public static void adviseTransactions(HibernateTransactionAdvisor advisor,
MethodAdviceReceiver receiver) {
advisor.addTransactionCommitAdvice(receiver);
}
 
    public RequestFilter buildTimingFilter(final Logger log)
    {
        return new RequestFilter()
        {
            public boolean service(Request request, Response response, RequestHandler handler)
                    throws IOException
            {
                long startTime = System.currentTimeMillis();
 
                try
                {
                    return handler.service(request, response);
                } finally
                {
                    long elapsed = System.currentTimeMillis() - startTime;
 
                    log.info(String.format("Request time: %d ms", elapsed));
                }
            }
        };
    }
 
   
    public void contributeRequestHandler(OrderedConfiguration<RequestFilter> configuration,
                                         @Local
                                         RequestFilter filter)
    {
        configuration.add("Timing", filter);
    }
}
 

 

在src/main/resources下增加hibernate.cfg.xml文件,代码如下:

<?xml version='1.0' encoding='utf-8'?>
<!--
   Copyright 2007 The Apache Software Foundation
 
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
 
       http://www.apache.org/licenses/LICENSE-2.0
 
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
 
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
  <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql:///example?useUnicode=true&amp;characterEncoding=UTF-8</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
 
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <property name="hbm2ddl.auto">update</property>
 
    <property name="hibernate.c3p0.min_size">5</property>
    <property name="hibernate.c3p0.max_size">20</property>
    <property name="hibernate.c3p0.timeout">300</property>
    <property name="hibernate.c3p0.max_statements">50</property>
    <property name="hibernate.c3p0.idle_test_period">3000</property>
 
    <property name="hibernate.generate_statistics">true</property>
  </session-factory>
 
 
</hibernate-configuration>
 

在数据库里面创建名为example的数据库。

创建com.tapestry.app.entities包,在包内创建User.java的实体。代码如下:

 

package com.tapestry.app.entities;
 
import java.util.Date;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
 
@Entity
public class User {
 
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="user_id")
private Long id;
 
private String name;
 
private int age;
 
private Date time;
 
public Long getId() {
return id;
}
 
public void setId(Long id) {
this.id = id;
}
 
public String getName() {
return name;
}
 
public void setName(String name) {
this.name = name;
}
 
public int getAge() {
return age;
}
 
public void setAge(int age) {
this.age = age;
}
 
public Date getTime() {
return time;
}
 
public void setTime(Date time) {
this.time = time;
}
}
 

创建com.tapestry.app.pages.crud包,包内创建UserCreate.java。在webapp下创建crud文件夹,文件夹内创建UserCreate.tml。他们的代码如下:

UserCreate.java

 

/**
* 项目名称:TapestryStart
* 开发模式:Maven+Tapestry5.x+Tapestry-hibernate+Mysql
* 版本:1.0
* 编写:飞风
* 时间:2012-02-29
*/
package com.tapestry.app.pages.crud;
 
import java.util.Date;
 
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
 
import com.tapestry.app.entities.User;
import com.tapestry.app.services.StartDAO;
 
public class UserCreate {
 
@Property
private User user;
 
//导入服务接口
@Inject
private StartDAO dao;
 
//初始化user实体
void onPrepare(){
user = new User();
}
 
//提交表单的时候执行存储,返回当前页面
Object onSuccess(){
//如果时间为空值输入系统当前时间
if(user.getTime() == null){
user.setTime(new Date());
}
dao.create(user);
return this;
}
}
 

UserCreate.tml

 

<html t:type="layout" title="tapestryStart Index"  t:sidebarTitle="Framework Version"
 xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd" xmlns:p="tapestry:parameter">
 <t:form>
  <t:errors/>
  <p>用户名:<t:textfield t:id="name" value="user.name" t:validate="required"/></p>
  <p>年龄:<t:textfield t:id="age" value="user.age" t:validate="required"/></p>
  <p><input type="submit" value="创建"/></p>
 </t:form>
 </html>

创建服务,在com.tapestry.app.services包里创建操作数据的接口与方法:StartDAO.java与StartDAOImpl.java这是我写的增删改查代码,已经封装过很方便以后使用。源码如下:

StartDAO.java

package com.tapestry.app.services;
 
import java.io.Serializable;
import java.util.List;
import java.util.Map;
 
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
 
 
 
 
public interface StartDAO {
 
 
<T, PK extends Serializable> T findByID(Class<T> type, PK id);
 
@CommitAfter
<T> T create(T t);
 
@CommitAfter
<T> T update(T t);
 
@CommitAfter
<T, PK extends Serializable> void deleteByID(Class<T> type, PK id);
 
<T> List<T> findWithNameQuery(String queryName, int num);
<T> List<T> findWithQuery(String queryName);
 
}
 

StartDAOImpl.java

 package com.tapestry.app.services;

 
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
 
import org.hibernate.Query;
import org.hibernate.Session;
 
 
 
 
 
public class StartDAOImpl implements StartDAO {
 
private Session session;
 
public StartDAOImpl(Session session){
this.session = session;
}
 
 
@SuppressWarnings("unchecked")
public <T, PK extends Serializable> T findByID(Class<T> type, PK id){
return (T) session.get(type, id);
}
 
 
public <T> T create(T t){
session.persist(t);
session.flush();
session.refresh(t);
//session.save(t);
return t;
}
 
 
 
 
public <T> T update(T t){
session.merge(t);
return t;
}
 
public <T, PK extends Serializable> void deleteByID(Class<T> type, PK id){
@SuppressWarnings("unchecked")
T t = (T) session.get(type, id);
session.delete(t);
}
 
@SuppressWarnings("unchecked")
public <T> List<T> findWithNameQuery(String queryName, int num){
return session.createQuery(queryName).setMaxResults(num).list();
}
 
@SuppressWarnings("unchecked")
public <T> List<T> findWithQuery(String queryName){
return session.createQuery(queryName).list();
}
    
}
 

最后修改下AppModule.java把服务绑定起来,代码如下:

package com.tapestry.app.services;
 
import java.io.IOException;
 
import org.apache.tapestry5.*;
import org.apache.tapestry5.hibernate.HibernateCoreModule;
import org.apache.tapestry5.hibernate.HibernateModule;
import org.apache.tapestry5.hibernate.HibernateSymbols;
import org.apache.tapestry5.hibernate.HibernateTransactionAdvisor;
import org.apache.tapestry5.ioc.MappedConfiguration;
import org.apache.tapestry5.ioc.MethodAdviceReceiver;
import org.apache.tapestry5.ioc.OrderedConfiguration;
import org.apache.tapestry5.ioc.ServiceBinder;
import org.apache.tapestry5.ioc.annotations.Local;
import org.apache.tapestry5.ioc.annotations.Match;
import org.apache.tapestry5.ioc.annotations.SubModule;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.RequestFilter;
import org.apache.tapestry5.services.RequestHandler;
import org.apache.tapestry5.services.Response;
import org.apache.tapestry5.upload.services.UploadModule;
import org.apache.tapestry5.upload.services.UploadSymbols;
import org.slf4j.Logger;
 
@SubModule({HibernateModule.class, HibernateCoreModule.class,UploadModule.class})
public class AppModule
{
    public static void bind(ServiceBinder binder)
    {
        binder.bind(StartDAO.class, StartDAOImpl.class);
    }
 
    public static void contributeFactoryDefaults(
            MappedConfiguration<String, Object> configuration)
    { 
        configuration.override(SymbolConstants.APPLICATION_VERSION, "1.0");
    }
 
    public static void contributeApplicationDefaults(
            MappedConfiguration<String, Object> configuration)
    {
    configuration.add(SymbolConstants.SUPPORTED_LOCALES, "en");
        configuration.add(SymbolConstants.PRODUCTION_MODE, "false");
        configuration.add(UploadSymbols.FILESIZE_MAX, "50000000");
        configuration.add(SymbolConstants.APPLICATION_VERSION, "1.0-SNAPSHOT");
        configuration
.add(HibernateSymbols.ENTITY_SESSION_STATE_PERSISTENCE_STRATEGY_ENABLED,
"true");
    }
 
    @Match("*DAO")
public static void adviseTransactions(HibernateTransactionAdvisor advisor,
MethodAdviceReceiver receiver) {
advisor.addTransactionCommitAdvice(receiver);
}
 
    public RequestFilter buildTimingFilter(final Logger log)
    {
        return new RequestFilter()
        {
            public boolean service(Request request, Response response, RequestHandler handler)
                    throws IOException
            {
                long startTime = System.currentTimeMillis();
 
                try
                {
                    return handler.service(request, response);
                } finally
                {
                    long elapsed = System.currentTimeMillis() - startTime;
 
                    log.info(String.format("Request time: %d ms", elapsed));
                }
            }
        };
    }
 
   
    public void contributeRequestHandler(OrderedConfiguration<RequestFilter> configuration,
                                         @Local
                                         RequestFilter filter)
    {
        configuration.add("Timing", filter);
    }
}
 运行 http://localhost/crud/usercreate可以添加数据了

本文转载自:http://flywind.org/technologydetail/20

共有 人打赏支持
神勇小白鼠
粉丝 56
博文 296
码字总数 36952
作品 0
海淀
技术主管
私信 提问
tapestry组件库

Apache Tapestry 5.4 即将发布,它将完美支持Jquery,我个人偏好 Jquery EasyUI,于是开发出基于 Tapestry 5.4版本的 Jquery EasyUI 组件库,Jquery EasyUI 的日历不方便使用,集成了 My97Da...

偏锋书生
2014/08/26
1K
0
第四讲:tapestry增删改查---修改数据

思路:在UserList页面传递user的id到修改也UesrUpdate页面,再查询出所有对应的数据。 修改UserList.tml页面,代码如下: <html t:type="layout" title="tapestryStart Index" t:sidebarTit......

神勇小白鼠
2012/04/13
0
0
第三讲:tapestry增删改查---查询数据

思路:使用loop组件循环显示每条增加的数据,添加用户使用了pagelink。 在com.tapestry.app.pages.crud包里创建UserList.java,在webapp/crud里创建UserList.tml代码如下: UserList.java 项...

神勇小白鼠
2012/04/13
0
0
Mybatis接口编程方式实现增删改查

前面一章Mybatis入门概述及第一个Mybatis实例实现增删改查 ,已经搭建好了eclipse,mybatis,mysql的环境,并且实现了一个简单的查询。请注意,这种方式是用SqlSession实例来直接执行已映射的S...

waj清风
2018/12/18
0
0
【笔记】数据库主从读写分离

1、原理:让主数据库(master)处理事务性增、改、删操作(INSERT、UPDATE、DELETE),而从数据库(slave)处理SELECT查询操作。 2.1、 为了确保数据库产品的稳定性,很多数据库拥有双机热备...

Aeggainety
2017/12/18
0
0

没有更多内容

加载失败,请刷新页面

加载更多

Prometheus简介

Prometheus是什么? Prometheus(普罗米修斯)是一套最初在SoundCloud上构建的开源监视和告警系统 。 特征 普罗米修斯的主要特点是: 具有由度量名称和键/值对标识的时间序列数据的多维数据模...

阿dai学长
7分钟前
0
0
“阿里巴巴小程序繁星计划”:20亿扶持200万小程序开发者和100万商家

3月21日,在2019阿里云峰会·北京站上,阿里巴巴旗下的阿里云、支付宝、淘宝、钉钉、高德等联合发布“阿里巴巴小程序繁星计划”:提供20亿元补贴,扶持200万+小程序开发者、100万+商家。凡入...

阿里云云栖社区
18分钟前
0
0
Android 动画Animation

动画分为视图动画(view animation)和属性动画(property animation),视图动画又分为帧动画和补间动画 视图动画控件(iv)点击事件(OnClickListener接口)触发位置在原位置 1.帧动画(Fra...

Coding缘
41分钟前
1
0
Mysql-常用日期查询

今天: SELECT * FROM A WHERE create_time = create_time(now()); 昨天: SELECT * FROM A WHERE TO_DAYS( NOW( ) ) - TO_DAYS( create_time) <= 1; 最近7天: SELECT * FROM A where DATE......

米饭有毒
42分钟前
1
0
如何离线分析Kafka海量业务消息?1分钟快速为您支招

场景介绍 说起Kafka,许多使用者对它是又爱又恨。Kafka是一种分布式的、基于发布/订阅的消息系统,其极致体验让人欲罢不能,但操心的运维、复杂的安全策略、可靠性易用性的缺失等,仍需要使用...

中间件小哥
45分钟前
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部