增、删、改、查。这是开发程序最基本的、必须掌握的事。如果看不懂可以先跳过此文,先看看后面的再回来仔细阅读,应该能更好理解。
实现使用了tapestry ioc的接口开发方式,也就是一个接口DAO,一个接口方法Impl,使用的时候调用接口的方法。要做增删改查还需要实体entity以及数据库,这里使用mySql。实体与数据库的连接使用tapestry-hibernate、c3p0、mysql-connector-java.
打开项目根目录下的pom.xml,增加需要的tapestry-hibernate、c3p0、mysql-connector-java、tapestry-upload连接,代码如下:
<groupId>org.apache.tapestry</groupId>
<artifactId>tapestry-hibernate</artifactId>
<version>${tapestry-release-version}</version>
<dependency>
<groupId>org.apache.tapestry</groupId>
<artifactId>tapestry-upload</artifactId>
<version>${tapestry-release-version}</version>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.17</version>
修改服务,打开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;
@SubModule({HibernateModule.class, HibernateCoreModule.class,UploadModule.class})
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");
.add(HibernateSymbols.ENTITY_SESSION_STATE_PERSISTENCE_STRATEGY_ENABLED,
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)
long startTime = System.currentTimeMillis();
return handler.service(request, response);
long elapsed = System.currentTimeMillis() - startTime;
log.info(String.format("Request time: %d ms", elapsed));
public void contributeRequestHandler(OrderedConfiguration<RequestFilter> configuration,
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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///example?useUnicode=true&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>
</hibernate-configuration>
在数据库里面创建名为example的数据库。
创建com.tapestry.app.entities包,在包内创建User.java的实体。代码如下:
package com.tapestry.app.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@GeneratedValue(strategy = GenerationType.AUTO)
public void setId(Long id) {
public String getName() {
public void setName(String name) {
public void setAge(int age) {
public void setTime(Date time) {
创建com.tapestry.app.pages.crud包,包内创建UserCreate.java。在webapp下创建crud文件夹,文件夹内创建UserCreate.tml。他们的代码如下:
UserCreate.java
* 开发模式:Maven+Tapestry5.x+Tapestry-hibernate+Mysql
package com.tapestry.app.pages.crud;
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 {
if(user.getTime() == null){
user.setTime(new Date());
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">
<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>
创建服务,在com.tapestry.app.services包里创建操作数据的接口与方法:StartDAO.java与StartDAOImpl.java这是我写的增删改查代码,已经封装过很方便以后使用。源码如下:
StartDAO.java
package com.tapestry.app.services;
import java.io.Serializable;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
public interface StartDAO {
<T, PK extends Serializable> T findByID(Class<T> type, PK id);
<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.Map.Entry;
import org.hibernate.Query;
import org.hibernate.Session;
public class StartDAOImpl implements StartDAO {
public StartDAOImpl(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){
public <T> T update(T t){
public <T, PK extends Serializable> void deleteByID(Class<T> type, PK id){
@SuppressWarnings("unchecked")
T t = (T) session.get(type, id);
@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;
@SubModule({HibernateModule.class, HibernateCoreModule.class,UploadModule.class})
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");
.add(HibernateSymbols.ENTITY_SESSION_STATE_PERSISTENCE_STRATEGY_ENABLED,
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)
long startTime = System.currentTimeMillis();
return handler.service(request, response);
long elapsed = System.currentTimeMillis() - startTime;
log.info(String.format("Request time: %d ms", elapsed));
public void contributeRequestHandler(OrderedConfiguration<RequestFilter> configuration,
configuration.add("Timing", filter);
运行 可以添加数据了