Tapestry Work With Mybatis

出处: http://www.blogjava.net/usherlight/archive/2010/01/06/308415.html

与现在最流行的SSH相比较,Tapestry能够完全替代其中Struts2和Spring,但是他还是需要一个ORM的框架。IBatis由于比较低的学习曲线,也受到很多人的喜爱。尤其是在IBatis3中引入了许多新的概念和想法,使用更加安全和便利。
本文主要介绍如何将Tapestry5.1和IBatis3进行整合。
简要步骤:
1. 准备工作
2. 数据库的建立
3. POJO的建立
4. IBatis相关配置文件的创建
5. Tapestry相关代码的完成
概要说明:
1、准备工作。这一部分是比较简单的,Eclipse之类的开发环境是必需的。Tapestry5.1、IBatis3(目前还是Beta7)、数据库(我使用的是MySql)的下载安装。
2、数据库的建立,由于是示例,所以数据库的建立也非常简单,只有一张User表,3个字段,Id,Name,Password
3、com.sample.User类,对应数据库表的3个字段,生成User类
4、IBatis配置文件:Configuration.xml,UserMapper.xml,jdbc.properties的生成, 前两个必需,最后一个可选.
5、在AppModule里,使用build方法, 添加服务生成IBatis3的SqlSessionFactory, 在需要使用SqlSessionFactory的地方,使用@InjectService注入即可
详细说明:
1、大家到各自的网站上下载相应的包好了。我只罗列一下我所用到的Lib:
    antlr-runtime-3.1.1.jar
    commons-codec-1.3.jar
    commons-lang-2.4.jar
    ibatis-3-core-3.0.0.216.jar
    javassist.jar
    log4j-1.2.14.jar
    mysql-connector-java-5.0.5.jar
    slf4j-api-1.5.10.jar
    slf4j-log4j12-1.5.10.jar
    stax2-api-3.0.1.jar
    tapestry-core-5.1.0.5.jar
    tapestry-ioc-5.1.0.5.jar
    tapestry5-annotations-5.1.0.5.jar
    woodstox-core-lgpl-4.0.7.jar
2、Create Table
DROP TABLE IF EXISTS `test`.`user`;
CREATE TABLE  `test`.`user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  `password` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

3、
package com.sample.model;
public class User {
    private long id;
    private String name;
    private String password;
    // getter and setter    ....
}

4、我把Configuration.xml和UserMapper.xml都放在src目录下,这样在部署的时候,就是生成在classes,也就是类路径的根目录下。
Configuration.xml:
<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE configuration 
  PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" 
  "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">  
<configuration> 
    <properties resource="jdbc.properties">
    </properties>
    <environments default="development"> 
        <environment id="development"> 
            <transactionManager type="JDBC"/> 
            <dataSource type="POOLED"> 
                <property name="driver" value="${jdbc.driver}"/> 
                <property name="url" value="${jdbc.url}"/> 
                <property name="username" value="${jdbc.username}"/> 
                <property name="password" value="${jdbc.password}"/>
                <property name="poolPingEnabled" value="${pingenable}"/>            
                <property name="poolPingQuery" value="${pingquery}"/>            
                <property name="poolPingConnectionsNotUsedFor" value="${pingnotusetime}"/>            
            </dataSource> 
        </environment> 
    </environments> 
    <mappers> 
        <mapper resource="UserMapper.xml"/> 
    </mappers> 
</configuration>

UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper  
    PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"  
    "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
    
<mapper namespace="com.sample.model.UserMapper">
    <select id="selectUser" parameterType="int" resultType="com.sample.model.User">  
        select * from user where id = #{id}  
    </select>
</mapper>

jdbc.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/test?autoReconnect=true
jdbc.username=root
jdbc.password=root
pingenable=true
pingquery=SELECT 1
pingoldertime=0
pingnotusetime=3600000

5、
package com.sample.web.services;
public class AppModule {
    public static SqlSessionFactory buildSqlSessionFactory() {
        try {
            String resource = "Configuration.xml";
            Reader reader = Resources.getResourceAsReader(resource);
            return new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            logger.warn("failed to build SqlSessionFactory: ", e);
            return null;
        }
    }

private static Logger logger = LoggerFactory.getLogger(AppModule.class);
}

package com.sample.model;
public interface UserMapper {
    public User selectUser(int id);
}

package com.pc.sample.web.pages;
public class Layout {
    @InjectService("SqlSessionFactory")
    private SqlSessionFactory sqlMapper;
    public String getUserName() {
        if ( sqlMapper == null ) {
            return "null-mapper";
        }
        SqlSession session = sqlMapper.openSession();
        try {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            if ( userMapper == null ) {
                return "null-userMapper";
            }
            User user = userMapper.selectUser(1);
            if ( user == null ) {
                return "null-user";
            }
            return user.getName();
        } catch (Exception e) {
            return "exception-" + e.getMessage();
        } finally {
            session.close();
        }
    }
}

几个注意事项:
1, 因为我的IBatis的配置文件Configuration.xml是放在类路径的根目录下,所以在初始化SqlSessionFactory的时候,直 接用String resource = "Configuration.xml";就行了,否则需要添加相应的路径,比如:把Configuration.xml与User类放在一起,也就是在 com.sample.model这个package中,那么就要写成:String resource = "com/sample/model/Configuration.xml";
同样,在Configuration.xml中,指定UserMapper.xml的规则也是这样的。
2,UserMapper的使用。Mapper的使用是IBatis3中才有的新功能,也是IBatis用户指南中推荐使用的方式。因为这样使用的话,就完全避免了类型的强制转换,实现了类型安全。
需要注意的是UserMapper只是一个接口。我们不需要提供这个接口的具体实现。IBatis3会自动生成一个具体的实例。

其中的方法名必须与UserMapper.xml中的select语句的id一样。在我的例子中是selectUser.
另外,此方法的返回值的类型必须与UserMapper.xml中配置的returnType一致。
最后要提醒的是UserMapper.xml中的namespace必须是UserMapper的全类名,在本例中就是com.sample.model.UserMapper

Tapestry Work With Mybatis

时间: 2024-08-27 03:28:34

Tapestry Work With Mybatis的相关文章

maven和mybatis

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersi

Spring+Mybatis+Maven 整合配置

1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans default-autowire="byName" 3 xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:sche

Spring+Mybatis+Maven+web整合

<?xml version="1.0" encoding="UTF-8"?> <beans default-autowire="byName" xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation

使用MyBatis Generator自动生成实体、mapper和dao层

通过MyBatis Generator可以自动生成实体.mapper和dao层,记录一下怎么用的. 主要步骤: 关于mybatis从数据库反向生成实体.DAO.mapper: 参考文章:http://www.cnblogs.com/wangkeai/p/6934683.html第一种方式:main方法运行(推荐) 1.在pom.xml中加入插件依赖: 2.写mbgConfiguration.xml文件,jdbc.properties文件 3.写/SSM/src/main/java/main/Ge

SSM整合(spring,spirngmvc,mybatis)

整合思路   准备环境:导入jar包(spring mybatis  dbcp连接池  mysql驱动包 log4j) 工程结构: --------------------------- 1.  整合dao mybatis和spring进行整合   applicationContext-dao.xml 配置: 1.数据源 2.SqlSessionFactory 3.mapper扫描器 创建po以及mapper(通过逆向工程,这里不再演示) 针对综合查询mapper,一般情况会有关联查询,建议自定

SpringBoot 2.SpringBoot整合Mybatis

一.创建Springboot的配置文件:application.properties SpringApplication 会从 application.properties 文件中加载配置信息,下面是添加Spring配置信息的文件目录顺序: 当前目录下的/config子目录中 当前目录中 一个 classpath 包下的 /config 目录中 classpath 根目录中 大家根据自己习惯来即可. /application.properties 文件配置如下: spring.datasourc

springMVC+MyBatis+Spring 整合(3)

spring mvc 与mybatis 的整合. 加入配置文件: spring-mybaits.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xm

MyBatis学习(四)XML配置文件之SQL映射的XML文件

SQL映射文件常用的元素: 1.select 查询语句是MyBatis最常用的语句之一. 执行简单查询的select元素是非常简单的: <select id="selectUser" parameterType="int" resultType="hashmap"> SELECT * FROM PERSON WHERE ID = #{id} </select> 这个语句被称作selectUser,接受一个int类型的参数,

MyBatis框架中Mapper映射配置的使用及原理解析(七) MapperProxy,MapperProxyFactory

从上文<MyBatis框架中Mapper映射配置的使用及原理解析(六) MapperRegistry> 中我们知道DefaultSqlSession的getMapper方法,最后是通过MapperRegistry对象获得Mapper实例: public <T> T getMapper(Class<T> type, SqlSession sqlSession) { final MapperProxyFactory<T> mapperProxyFactory =