增、刪、改、查。這是開發程序最基本的、必須掌握的事。若是看不懂能夠先跳過此文,先看看後面的再回來仔細閱讀,應該能更好理解。html
實現使用了tapestry ioc的接口開發方式,也就是一個接口DAO,一個接口方法Impl,使用的時候調用接口的方法。要作增刪改查還須要實體entity以及數據庫,這裏使用mySql。實體與數據庫的鏈接使用tapestry-hibernate、c3p0、mysql-connector-java.java
打開項目根目錄下的pom.xml,增長鬚要的tapestry-hibernate、c3p0、mysql-connector-java、tapestry-upload鏈接,代碼以下:mysql
<dependency>
<groupId>org.apache.tapestry</groupId>
<artifactId>tapestry-hibernate</artifactId>
<version>${tapestry-release-version}</version>
</dependency>
<dependency>web
<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文件進行配置,源碼以下:sql
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文件,代碼以下:express
<?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&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的數據庫。apache
建立com.tapestry.app.entities包,在包內建立User.java的實體。代碼以下:session
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。他們的代碼以下:app
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);
}
}