博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
第二讲:tapestry增删改查---添加数据
阅读量:6522 次
发布时间:2019-06-24

本文共 11851 字,大约阅读时间需要 39 分钟。

hot3.png

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

 

实现使用了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);
    }
}
 运行 可以添加数据了

转载于:https://my.oschina.net/shootercn/blog/53410

你可能感兴趣的文章
点赞!参展商盛赞义乌装博会!
查看>>
UWP图片编辑器(涂鸦、裁剪、合成)
查看>>
C# 通过 Renci.SshNet 实现SFTP数据传输
查看>>
别说自己懂手机 还玩Root的才是发烧友
查看>>
[C#]使用CMD命令删除文件函数
查看>>
TCP异常关闭研究分析
查看>>
vim + ctags + taglist + cscope + cppcomplete + global 使用初探
查看>>
通道封闭解决方案非常适于数据中心应用
查看>>
王洪涛:大数据技术的最终目标是应用
查看>>
从Puppet到Docker的服务迁移
查看>>
揭秘招商银行App6.0:当一个银行App开始谈智能
查看>>
海云数据AI战略发布会首提“能力服务” 人工智能赋能端客户
查看>>
location.search 通过地址栏实现页面之间的数据传输
查看>>
游戏测试方法
查看>>
Juniper推出基于云的全球攻击者数据库
查看>>
Web应用程序的开发步骤
查看>>
Linux C OSS音频编程
查看>>
美林银行采用AI应收账款方案,智能匹配对账和支付
查看>>
得力数据恢复软件怎么注册激活的?免费注册激活图文教程
查看>>
基于Docker API的工具综述
查看>>