论坛首页 Java企业应用论坛

IBatis3.0 xml配置方式的应用(JPA+IBatis3.0应用)

浏览 8911 次
精华帖 (0) :: 良好帖 (1) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-02-22   最后修改:2010-02-22

   最近网上出现IBatis3.0的文章本人也做了小Demo,用一下啊,哈哈。

采用JpA注解实体,采用IBatis3.0的新的开发方式:

采用xml配置IBatis的各种配置文件时数据源可以不适用commons-collections,但是在使用注解时,必须的。有点不解。

 使用的类库如下:

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
 <classpathentry kind="src" path="src"/>
 <classpathentry exported="true" kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
 <classpathentry kind="lib" path="src/commons-dbcp.jar"/>
 <classpathentry kind="lib" path="src/commons-logging.jar"/>
 <classpathentry kind="lib" path="src/commons-pool.jar"/>
 <classpathentry kind="lib" path="src/ibatis-3-core-3.0.0.227.jar"/>
 <classpathentry kind="lib" path="src/mysql-connector-java-3.2.0-alpha-bin.jar"/>
 <classpathentry kind="lib" path="src/persistence-api-1.0.jar"/>
 <classpathentry kind="lib" path="src/persistence-api-1.0-sources.jar"/>
 <classpathentry kind="lib" path="src/commons-collections-2.1.jar"/>
 <classpathentry kind="output" path="bin"/>
</classpath>

 

采用DBCP的连接池获取数据源:

可能必须jar文件为上面红色jar

 

 

备注:commons-collections如果高版本发生错误:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections/CursorableLinkedList
 at org.apache.commons.pool.impl.GenericObjectPool.<init>(GenericObjectPool.java:392)
 at org.apache.commons.pool.impl.GenericObjectPool.<init>(GenericObjectPool.java:258)
 at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:795)
 at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:540)
 at org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSessionFromDataSource(DefaultSqlSessionFactory.java:72)
 at org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSession(DefaultSqlSessionFactory.java:32)
 at com.vnvtrip.search.ibatis.utils.BaseIBatisDAO.getSqlSession(BaseIBatisDAO.java:16)
 at com.vnvtrip.search.ibatis.blog.dao.BlogDAO.findById(BlogDAO.java:30)
 at com.vnvtrip.search.ibatis.blog.test.BlogTest.main(BlogTest.java:14)

必须采用低版本  src/commons-collections-2.1.jar

 

 

如果采用IBatis3.0使用xml配置映射文件那么可以不用写对应的映射类XXX-Mapper:

 

本节采用xml配置,下节采用注解映射Mapper类。

jdbc。properties文件如下


driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/search
username=root
password=123456

 Blog.xml其实是一个sql映射文件。

 

 
<?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="BlogMapper">
<select id="findById" parameterType="java.lang.Integer" resultType="Blog">
select * from Blog where blogid =#{blogid}#
</select>
<delete id="deleteById" parameterType="java.lang.Integer">
delete Blog where blogid =#{blogid}#
</delete>
<update id="updateBlog" parameterType="Blog">
update Blog set author=#{author}#,subject=#{subject}#,content=#{content}#
, publishTime=#{publishTime}# where blogid=#{blogid}
</update>

<insert id="addBlog" parameterType="Blog">
insert into Blog(author,subject,content, publishTime,blogid)
values(#{author}#,#{subject}#,#{content}#,#{publishTime}#,#{blogid})
</insert>
<select id="findAll" resultType="java.util.List">
select * from Blog
</select>
</mapper>

 

 

 

IBatis的全局配置文件类:

sql-mapper.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"/>
<typeAliases>
<typeAlias type="com.vnvtrip.search.ibatis.blog.model.Blog" alias="Blog"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="Blog.xml"/>
</mappers>
</configuration>

 

Blog类:

package com.vnvtrip.search.ibatis.blog.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

 

/**
 *
 * @author longgangbai
 *
 */
@Entity
@Table(name = "blog", catalog = "search")
public class Blog implements java.io.Serializable {
 /**
  *
  */
 private static final long serialVersionUID = 1L;
 // Fields
 @Id
 @GeneratedValue(generator = "autoincrement", strategy = GenerationType.AUTO)
 private Integer blogid;
 private String author;
 private String subject;
 private String content;
 private String publishTime;

 // Constructors

 /** default constructor */
 public Blog() {
 }

 /** minimal constructor */
 public Blog(Integer blogid, String author) {
  this.blogid = blogid;
  this.author = author;
 }

 /** full constructor */
 public Blog(Integer blogid, String author, String subject, String content,
   String publishTime) {
  this.blogid = blogid;
  this.author = author;
  this.subject = subject;
  this.content = content;
  this.publishTime = publishTime;
 }

 // Property accessors
 @Id
 @Column(name = "blogid", nullable = false)
 public Integer getBlogid() {
  return this.blogid;
 }

 public void setBlogid(Integer blogid) {
  this.blogid = blogid;
 }

 @Column(name = "author", nullable = false, length = 25)
 public String getAuthor() {
  return this.author;
 }

 public void setAuthor(String author) {
  this.author = author;
 }

 @Column(name = "subject", length = 50)
 public String getSubject() {
  return this.subject;
 }

 public void setSubject(String subject) {
  this.subject = subject;
 }

 @Column(name = "content", length = 500)
 public String getContent() {
  return this.content;
 }

 public void setContent(String content) {
  this.content = content;
 }

 @Column(name = "publishTime", length = 25)
 public String getPublishTime() {
  return this.publishTime;
 }

 public void setPublishTime(String publishTime) {
  this.publishTime = publishTime;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((author == null) ? 0 : author.hashCode());
  result = prime * result + ((blogid == null) ? 0 : blogid.hashCode());
  result = prime * result + ((content == null) ? 0 : content.hashCode());
  result = prime * result
    + ((publishTime == null) ? 0 : publishTime.hashCode());
  result = prime * result + ((subject == null) ? 0 : subject.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  final Blog other = (Blog) obj;
  if (author == null) {
   if (other.author != null)
    return false;
  } else if (!author.equals(other.author))
   return false;
  if (blogid == null) {
   if (other.blogid != null)
    return false;
  } else if (!blogid.equals(other.blogid))
   return false;
  if (content == null) {
   if (other.content != null)
    return false;
  } else if (!content.equals(other.content))
   return false;
  if (publishTime == null) {
   if (other.publishTime != null)
    return false;
  } else if (!publishTime.equals(other.publishTime))
   return false;
  if (subject == null) {
   if (other.subject != null)
    return false;
  } else if (!subject.equals(other.subject))
   return false;
  return true;
 }

}

 

IbatisSessionFactory类:一个类似创建类似Hibernate的HibernateSessionFactoryUtils的类。

 

注意有颜色部分的代码:

 

写道
package com.vnvtrip.search.ibatis.utils;

import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.TransactionIsolationLevel;

/**
*
* @author longgangbai
*
*/
public class IbatisSessionFactory implements SqlSessionFactory{

/** 根据参数得到某个具体的iBatis数据源工厂实例 */
public static SqlSessionFactory getInstance(){
if(sqlSessionFactory == null)
{
initSqlSessionFactory();
}
return sqlSessionFactory;
}

private static void initSqlSessionFactory() {
String resource = "sql-mapper.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resource);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
sqlSessionFactory = builder.build(reader);
} catch (IOException e) {
System.out.println("创建iBATIS数据工厂时出现错误!");
e.printStackTrace();
}
}


// 真正“做事”的实例
private static SqlSessionFactory sqlSessionFactory = null;

public Configuration getConfiguration() {
return sqlSessionFactory.getConfiguration();
}
public SqlSession openSession() {
return sqlSessionFactory.openSession();
}
public SqlSession openSession(boolean arg0) {
return sqlSessionFactory.openSession(arg0);
}
public SqlSession openSession(Connection arg0) {
return sqlSessionFactory.openSession(arg0);
}
public SqlSession openSession(ExecutorType arg0) {
return sqlSessionFactory.openSession(arg0);
}
public SqlSession openSession(ExecutorType arg0, boolean arg1) {
return sqlSessionFactory.openSession(arg0, arg1);
}
public SqlSession openSession(ExecutorType arg0, Connection arg1) {
return sqlSessionFactory.openSession(arg0, arg1);
}

@Override
public SqlSession openSession(TransactionIsolationLevel arg0) {
return sqlSessionFactory.openSession(arg0);
}

@Override
public SqlSession openSession(ExecutorType arg0,
TransactionIsolationLevel arg1) {
return sqlSessionFactory.openSession(arg0,arg1);
}
}

 

写道
package com.vnvtrip.search.ibatis.utils;

import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
/**
*
* @author longgangbai
*
*/
public abstract class BaseIBatisDAO {

/**
*
* @return
*/
public SqlSession getSqlSession()
{
return IbatisSessionFactory.getInstance().openSession();
}
/**
* 封装好了的通用ibatis分页查询方法,只要配置好了Mapper文件,可进行任何分页查询
* @param statement 一般为xxxMapper.ooo(ooo为select标签的id值),参考UserMapper.xml
* @param paramMap 一般是由页面来的查询参数
* @param pageIndex 当前页码
* @param pageSize 每页记录数
* @return
*/
public PageBean queryByIbatis(String statement, Object paramMap, int pageIndex, int pageSize) {

SqlSession sqlSession = IbatisSessionFactory.getInstance().openSession();
PageBean pageBean = new PageBean();

int offset = PageBean.getOffset(pageIndex, pageSize);

try {
int rowCount = sqlSession.selectList(statement, paramMap).size();
int totalPage = ( rowCount + pageSize - 1 ) / pageSize ;
List resultList =sqlSession.selectList(statement, paramMap, new RowBounds(offset, pageSize));
pageBean.setPageIndex(pageIndex);
pageBean.setRowCount(rowCount);
pageBean.setTotalPage(totalPage);
pageBean.setResultList(resultList);
pageBean.setPageSize(pageSize);
pageBean.init();
} finally {
sqlSession.close();
}

return pageBean;
}
}

  

package com.vnvtrip.search.ibatis.utils;

import java.util.List;
/**
 * 
 * @author longgangbai
 *
 */
public class PageBean {   
    /**  
     * 计算所取数据集的偏移量  
     * @param pageIndex  
     * @param pageSize  
     * @return 数据偏移量  
     */  
    public static int getOffset(int pageIndex, int pageSize) {   
        return pageSize*(pageIndex - 1);   
    }   
    private List resultList; // 要返回的记录   
    private int pageIndex; // 当前页码   
    private int pageSize; // 每页记录数   
    private int rowCount; // 总记录数   
    private int totalPage; // 总页数   
       
    private boolean isFirstPage;   
    private boolean isLastPage;   
    private boolean hasPreviousPage;   
    private boolean hasNextPage;   
       
    public void init(){   
        isFirstPage = pageIndex == 1?true:false;   
        isLastPage = pageIndex == totalPage?true:false;   
        hasPreviousPage = !isFirstPage;   
        hasNextPage = !isLastPage;   
    }   
    public int getPageIndex() {   
        return pageIndex;   
    }   
    public void setPageIndex(int pageIndex) {   
        this.pageIndex = pageIndex;   
    }   
    public boolean isHasNextPage() {   
        return hasNextPage;   
    }   
    public boolean isHasPreviousPage() {   
        return hasPreviousPage;   
    }   
    public boolean isFirstPage() {   
        return isFirstPage;   
    }   
    public boolean isLastPage() {   
        return isLastPage;   
    }   
    public int getPageSize() {   
        return pageSize;   
    }   
    public void setPageSize(int pageSize) {   
        this.pageSize = pageSize;   
    }   
    public List getResultList() {   
        return resultList;   
    }   
    public void setResultList(List resultList) {   
        this.resultList = resultList;   
    }   
    public int getRowCount() {   
        return rowCount;   
    }   
    public void setRowCount(int rowCount) {   
        this.rowCount = rowCount;   
    }   
    public int getTotalPage() {   
        return totalPage;   
    }   
    public void setTotalPage(int totalPage) {   
        this.totalPage = totalPage;   
    }   
       
}  

 

 在BlogDAO中使用如下:

    /**
     * 根据主键查询
     */
    @Override
    public Blog findById(Integer id) {
 return (Blog)this.getSqlSession().selectOne("BlogMapper.findById",id);
    }

   发表时间:2010-02-22   最后修改:2010-02-22
一直觉得 JPA 的实体类Annotation对于代码过于倾入,例如:
@Column(name = "author", nullable = false, length = 25)
列属性设置如天女散花,分散到了DataObject各个属性上,可代码易读性(Readability)维护性(Maintanability)大大降低.

另外, 分页控制还要自己完成,IBatis 3 在这一点上仍然不够完善。
0 请登录后投票
   发表时间:2010-02-23  
raymond2006k 写道
一直觉得 JPA 的实体类Annotation对于代码过于倾入,例如:
@Column(name = "author", nullable = false, length = 25)
列属性设置如天女散花,分散到了DataObject各个属性上,可代码易读性(Readability)维护性(Maintanability)大大降低.

另外, 分页控制还要自己完成,IBatis 3 在这一点上仍然不够完善。



针对@Column的注解可以省略,采用默认,并不是必须的哦,怎么能说“JPA 的实体类Annotation对于代码过于倾入”,有点不解??
0 请登录后投票
   发表时间:2010-04-08  
做了两年的.net项目,现在想转向java。最近在做一个练习项目。在集成spring和ibatis遇到问题了,spring版本为2.5.6,iBATIS 3 beta 10 怎么都集成不好,tomat启动的时候就通不过,找不到iBATIS,换成iBATIS 2 就行了 ,不知道怎么回事,调查了半天也没解决,但到时包的兼容性问题。郁闷中
0 请登录后投票
   发表时间:2010-04-08  
lionhome 写道
做了两年的.net项目,现在想转向java。最近在做一个练习项目。在集成spring和ibatis遇到问题了,spring版本为2.5.6,iBATIS 3 beta 10 怎么都集成不好,tomat启动的时候就通不过,找不到iBATIS,换成iBATIS 2 就行了 ,不知道怎么回事,调查了半天也没解决,但到时包的兼容性问题。郁闷中

貌似当前Spring2.5.6和IBatis3.0没有集成(这也许可能是你集成一直报错的原因吧),如需要集成自己实现相关的几个类即可。IBatis2.0和Spring2.5.6是已经可以集成的不需要自己编辑集成的回调类等。
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics